a62e280a6efc46a268d2926850ecc7f22270b133
[progcomp2013.git] / qchess / src / game.py
1
2
3
4         
5
6 # A thread that runs the game
7 class GameThread(StoppableThread):
8         def __init__(self, board, players):
9                 StoppableThread.__init__(self)
10                 self.board = board
11                 self.players = players
12                 self.state = {"turn" : None} # The game state
13                 self.error = 0 # Whether the thread exits with an error
14                 self.lock = threading.RLock() #lock for access of self.state
15                 self.cond = threading.Condition() # conditional for some reason, I forgot
16                 self.final_result = ""
17                 
18                 
19
20         # Run the game (run in new thread with start(), run in current thread with run())
21         def run(self):
22                 result = ""
23                 while not self.stopped():
24                         
25                         for p in self.players:
26                                 with self.lock:
27                                         if isinstance(p, NetworkSender):
28                                                 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
29                                         else:
30                                                 self.state["turn"] = p
31                                 #try:
32                                 if True:
33                                         [x,y] = p.select() # Player selects a square
34                                         if self.stopped():
35                                                 break
36
37                                         
38                                                 
39
40                                         result = self.board.select(x, y, colour = p.colour)                             
41                                         for p2 in self.players:
42                                                 p2.update(result) # Inform players of what happened
43
44
45                                         log(result)
46
47                                         target = self.board.grid[x][y]
48                                         if isinstance(graphics, GraphicsThread):
49                                                 with graphics.lock:
50                                                         graphics.state["moves"] = self.board.possible_moves(target)
51                                                         graphics.state["select"] = target
52
53                                         time.sleep(turn_delay)
54
55
56                                         if len(self.board.possible_moves(target)) == 0:
57                                                 #print "Piece cannot move"
58                                                 target.deselect()
59                                                 if isinstance(graphics, GraphicsThread):
60                                                         with graphics.lock:
61                                                                 graphics.state["moves"] = None
62                                                                 graphics.state["select"] = None
63                                                                 graphics.state["dest"] = None
64                                                 continue
65
66                                         try:
67                                                 [x2,y2] = p.get_move() # Player selects a destination
68                                         except:
69                                                 self.stop()
70
71                                         if self.stopped():
72                                                 break
73
74                                         if isinstance(log_file, HttpLog):
75                                                 log_file.prelog()
76
77                                         self.board.update_move(x, y, x2, y2)
78                                         result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
79                                         for p2 in self.players:
80                                                 p2.update(result) # Inform players of what happened
81
82                                         log(result)                                     
83
84                                         if isinstance(graphics, GraphicsThread):
85                                                 with graphics.lock:
86                                                         graphics.state["moves"] = [[x2,y2]]
87
88                                         time.sleep(turn_delay)
89
90                                         if isinstance(graphics, GraphicsThread):
91                                                 with graphics.lock:
92                                                         graphics.state["select"] = None
93                                                         graphics.state["dest"] = None
94                                                         graphics.state["moves"] = None
95
96                         # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
97                         #       except Exception,e:
98                         #               result = e.message
99                         #               #sys.stderr.write(result + "\n")
100                         #               
101                         #               self.stop()
102                         #               with self.lock:
103                         #                       self.final_result = self.state["turn"].colour + " " + e.message
104
105                                 if self.board.king["black"] == None:
106                                         if self.board.king["white"] == None:
107                                                 with self.lock:
108                                                         self.final_result = self.state["turn"].colour + " DRAW"
109                                         else:
110                                                 with self.lock:
111                                                         self.final_result = "white"
112                                         self.stop()
113                                 elif self.board.king["white"] == None:
114                                         with self.lock:
115                                                 self.final_result = "black"
116                                         self.stop()
117                                                 
118
119                                 if self.stopped():
120                                         break
121
122
123                 for p2 in self.players:
124                         p2.quit(self.final_result)
125
126                 log(self.final_result)
127
128                 if isinstance(graphics, GraphicsThread):
129                         graphics.stop()
130
131         
132 # A thread that replays a log file
133 class ReplayThread(GameThread):
134         def __init__(self, players, src, end=False,max_lines=None):
135                 self.board = Board(style="empty")
136                 GameThread.__init__(self, self.board, players)
137                 self.src = src
138                 self.max_lines = max_lines
139                 self.line_number = 0
140                 self.end = end
141
142                 self.setup()
143
144         def setup(self):
145                 sys.stderr.write("setup called for ReplayThread\n")
146                 if True:
147                         while self.src.readline().strip(" \r\n") != "# Initial board":
148                                 self.line_number += 1
149                 
150                         line = self.src.readline().strip(" \r\n")
151                         
152                         while line != "# Start game":
153                                 #print "Reading line " + str(line)
154                                 self.line_number += 1
155                                 [x,y] = map(int, line.split("at")[1].strip(" \r\n").split(","))
156                                 colour = line.split(" ")[0]
157                                 current_type = line.split(" ")[1]
158                                 types = map(lambda e : e.strip(" [],'"), line.split(" ")[2:4])
159                                 p = Piece(colour, x, y, types)
160                                 if current_type != "unknown":
161                                         p.current_type = current_type
162                                         p.choice = types.index(current_type)
163
164                                 self.board.pieces[colour].append(p)
165                                 self.board.grid[x][y] = p
166                                 if current_type == "king":
167                                         self.board.king[colour] = p
168
169                                 line = self.src.readline().strip(" \r\n")
170                                 
171                 #except Exception, e:
172                 #       raise Exception("FILE line: " + str(self.line_number) + " \""+str(line)+"\"") #\n" + e.message)
173         
174         def run(self):
175                 i = 0
176                 phase = 0
177                 count = 0
178                 line = self.src.readline().strip(" \r\n")
179                 while line != "# EOF":
180                         sys.stderr.write(sys.argv[0] + " : " + str(self.__class__.__name__) + " read: " + str(line) + "\n")
181                         count += 1
182                         if self.max_lines != None and count > self.max_lines:
183                                 self.stop()
184
185                         if self.stopped():
186                                 break
187
188                         with self.lock:
189                                 self.state["turn"] = self.players[i]
190
191                         line = line.split(":")
192                         result = line[len(line)-1].strip(" \r\n")
193                         
194
195                         try:
196                                 self.board.update(result)
197                         except Exception, e:
198                                 sys.stderr.write("Exception! " + str(e.message) + "\n")
199                                 self.final_result = result
200                                 self.stop()
201                                 break
202
203                         log(result)
204
205                         [x,y] = map(int, result.split(" ")[0:2])
206                         target = self.board.grid[x][y]
207
208                         if isinstance(graphics, GraphicsThread):
209                                 if phase == 0:
210                                         with graphics.lock:
211                                                 graphics.state["moves"] = self.board.possible_moves(target)
212                                                 graphics.state["select"] = target
213
214                                         if self.end:
215                                                 time.sleep(turn_delay)
216
217                                 elif phase == 1:
218                                         [x2,y2] = map(int, result.split(" ")[3:5])
219                                         with graphics.lock:
220                                                 graphics.state["moves"] = [[x2,y2]]
221
222                                         if self.end:
223                                                 time.sleep(turn_delay)
224
225                                         with graphics.lock:
226                                                 graphics.state["select"] = None
227                                                 graphics.state["dest"] = None
228                                                 graphics.state["moves"] = None
229                                                 
230
231
232                         
233
234                         for p in self.players:
235                                 p.update(result)
236                         
237                         phase = (phase + 1) % 2
238                         if phase == 0:
239                                 i = (i + 1) % 2
240                         
241                         line = self.src.readline().strip(" \r\n")
242
243                 sys.stderr.write(sys.argv[0] + " : " + str(self.__class__.__name__) + " finished...\n")
244
245                 if self.max_lines != None and self.max_lines > count:
246                         sys.stderr.write(sys.argv[0] + " : Replaying from file; stopping at last line (" + str(count) + ")\n")
247                         sys.stderr.write(sys.argv[0] + " : (You requested line " + str(self.max_lines) + ")\n")
248
249                 if self.end and isinstance(graphics, GraphicsThread):
250                         #graphics.stop()
251                         pass # Let the user stop the display
252                 elif not self.end:
253                         global game
254                         game = GameThread(self.board, self.players)
255                         game.run()
256                 
257
258                 
259
260 def opponent(colour):
261         if colour == "white":
262                 return "black"
263         else:
264                 return "white"

UCC git Repository :: git.ucc.asn.au