6972c5c2bdc959cae413a31389edc394ecfd7e55
[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, server = True):
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                 self.server = server
18                 
19                 
20                         
21                 
22                 
23
24         # Run the game (run in new thread with start(), run in current thread with run())
25         def run(self):
26                 result = ""
27                 while not self.stopped():
28                         
29                         for p in self.players:
30                                 with self.lock:
31                                         self.state["turn"] = p.base_player()
32                                 try:
33                                 #if True:
34                                         [x,y] = p.select() # Player selects a square
35                                         if self.stopped():
36                                                 #debug("Quitting in select")
37                                                 break
38                                                 
39                                         if isinstance(p, NetworkPlayer):
40                                                 if p.network.server == True:
41                                                         result = self.board.select(x, y, colour = p.colour)
42                                                 else:
43                                                         result = None
44                                                         
45                                         else:
46                                                 result = self.board.select(x, y, colour = p.colour)
47                                         
48                                         result = p.update(result)
49                                         if self.stopped():
50                                                 break
51                                         for p2 in self.players:
52                                                 if p2 == p:
53                                                         continue
54                                                 p2.update(result) # Inform players of what happened
55                                                 if self.stopped():
56                                                         break
57                                         
58                                         if self.stopped():
59                                                 break
60
61
62                                         log(result)
63
64                                         target = self.board.grid[x][y]
65                                         if isinstance(graphics, GraphicsThread):
66                                                 with graphics.lock:
67                                                         graphics.state["moves"] = self.board.possible_moves(target)
68                                                         graphics.state["select"] = target
69
70                                         time.sleep(turn_delay)
71
72
73                                         if len(self.board.possible_moves(target)) == 0:
74                                                 #print "Piece cannot move"
75                                                 target.deselect()
76                                                 if isinstance(graphics, GraphicsThread):
77                                                         with graphics.lock:
78                                                                 graphics.state["moves"] = None
79                                                                 graphics.state["select"] = None
80                                                                 graphics.state["dest"] = None
81                                                 continue
82
83                                         #try:
84                                         [x2,y2] = p.get_move() # Player selects a destination
85                                         #except:
86                                         #       self.stop()
87
88                                         if self.stopped():
89                                                 #debug("Quitting in get_move")
90                                                 break
91                                         
92                                         if isinstance(p, NetworkPlayer):
93                                                 if p.network.server == True:
94                                                         result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
95                                                         self.board.update_move(x, y, x2, y2)
96                                                 else:
97                                                         result = None
98                                                         
99                                         else:
100                                                 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
101                                                 self.board.update_move(x, y, x2, y2)
102                                         
103                                         result = p.update(result)
104                                         if self.stopped():
105                                                 break
106                                         for p2 in self.players:
107                                                 if p2 == p:
108                                                         continue
109                                                 p2.update(result) # Inform players of what happened
110                                                 if self.stopped():
111                                                         break
112                                         
113                                         if self.stopped():
114                                                 break
115                                         
116                                         
117                                                                                         
118                                         log(result)
119
120
121                                                                                 
122
123                                         if isinstance(graphics, GraphicsThread):
124                                                 with graphics.lock:
125                                                         graphics.state["moves"] = [[x2,y2]]
126
127                                         time.sleep(turn_delay)
128
129                                         if isinstance(graphics, GraphicsThread):
130                                                 with graphics.lock:
131                                                         graphics.state["select"] = None
132                                                         graphics.state["dest"] = None
133                                                         graphics.state["moves"] = None
134
135                         
136                                         end = self.board.end_condition()
137                                         if end != None:         
138                                                 with self.lock:
139                                                         if end == "DRAW":
140                                                                 self.final_result = self.state["turn"].colour + " " + end
141                                                         else:
142                                                                 self.final_result = end
143                                                 self.stop()
144                                 
145                                         if self.stopped():
146                                                 break
147                                 except Exception,e:
148                                 #if False:
149                                         result = e.message
150                                         #sys.stderr.write(result + "\n")
151                                         
152                                         self.stop()
153                                         
154                                         with self.lock:
155                                                 self.final_result = self.state["turn"].colour + " " + e.message
156                                         break
157
158
159
160                 for p2 in self.players:
161                         p2.quit(self.final_result)
162
163                 log(self.final_result)
164
165                 if isinstance(graphics, GraphicsThread):
166                         graphics.stop()
167
168         
169 # A thread that replays a log file
170 class ReplayThread(GameThread):
171         def __init__(self, players, src, end=False,max_moves=None):
172                 self.board = Board(style="empty")
173                 self.board.max_moves = max_moves
174                 GameThread.__init__(self, self.board, players)
175                 self.src = src
176                 self.end = end
177
178                 self.reset_board(self.src.readline())
179
180         def reset_board(self, line):
181                 agent_str = ""
182                 self_str = ""
183                 while line != "# Start game" and line != "# EOF":
184                         
185                         while line == "":
186                                 line = self.src.readline().strip(" \r\n")
187                                 continue
188
189                         if line[0] == '#':
190                                 line = self.src.readline().strip(" \r\n")
191                                 continue
192
193                         self_str += line + "\n"
194
195                         if self.players[0].name == "dummy" and self.players[1].name == "dummy":
196                                 line = self.src.readline().strip(" \r\n")
197                                 continue
198                         
199                         tokens = line.split(" ")
200                         types = map(lambda e : e.strip("[] ,'"), tokens[2:4])
201                         for i in range(len(types)):
202                                 if types[i][0] == "?":
203                                         types[i] = "unknown"
204
205                         agent_str += tokens[0] + " " + tokens[1] + " " + str(types) + " ".join(tokens[4:]) + "\n"
206                         line = self.src.readline().strip(" \r\n")
207
208                 for p in self.players:
209                         p.reset_board(agent_str)
210                 
211                 
212                 self.board.reset_board(self_str)
213
214         
215         def run(self):
216                 move_count = 0
217                 last_line = ""
218                 line = self.src.readline().strip(" \r\n")
219                 while line != "# EOF":
220
221
222                         if self.stopped():
223                                 break
224                         
225                         if len(line) <= 0:
226                                 continue
227                                         
228
229                         if line[0] == '#':
230                                 last_line = line
231                                 line = self.src.readline().strip(" \r\n")
232                                 continue
233
234                         tokens = line.split(" ")
235                         if tokens[0] == "white" or tokens[0] == "black":
236                                 self.reset_board(line)
237                                 last_line = line
238                                 line = self.src.readline().strip(" \r\n")
239                                 continue
240
241                         move = line.split(":")
242                         move = move[len(move)-1].strip(" \r\n")
243                         tokens = move.split(" ")
244                         
245                         
246                         try:
247                                 [x,y] = map(int, tokens[0:2])
248                         except:
249                                 last_line = line
250                                 self.stop()
251                                 break
252
253                         log(move)
254
255                         target = self.board.grid[x][y]
256                         with self.lock:
257                                 if target.colour == "white":
258                                         self.state["turn"] = self.players[0]
259                                 else:
260                                         self.state["turn"] = self.players[1]
261                         
262                         move_piece = (tokens[2] == "->")
263                         if move_piece:
264                                 [x2,y2] = map(int, tokens[len(tokens)-2:])
265
266                         if isinstance(graphics, GraphicsThread):
267                                 with graphics.lock:
268                                         graphics.state["select"] = target
269                                         
270                         if not move_piece:
271                                 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
272                                 if isinstance(graphics, GraphicsThread):
273                                         with graphics.lock:
274                                                 if target.current_type != "unknown":
275                                                         graphics.state["moves"] = self.board.possible_moves(target)
276                                                 else:
277                                                         graphics.state["moves"] = None
278                                         time.sleep(turn_delay)
279                         else:
280                                 self.board.update_move(x, y, x2, y2)
281                                 if isinstance(graphics, GraphicsThread):
282                                         with graphics.lock:
283                                                 graphics.state["moves"] = [[x2,y2]]
284                                         time.sleep(turn_delay)
285                                         with graphics.lock:
286                                                 graphics.state["select"] = None
287                                                 graphics.state["moves"] = None
288                                                 graphics.state["dest"] = None
289                         
290
291                         
292                         
293                         
294                         for p in self.players:
295                                 p.update(move)
296
297                         last_line = line
298                         line = self.src.readline().strip(" \r\n")
299                         
300                         
301                         end = self.board.end_condition()
302                         if end != None:
303                                 self.final_result = end
304                                 self.stop()
305                                 break
306                                         
307                                                 
308                                                 
309
310                         
311                                         
312
313
314                         
315
316                                 
317                         
318
319                 
320
321                 if self.end and isinstance(graphics, GraphicsThread):
322                         #graphics.stop()
323                         pass # Let the user stop the display
324                 elif not self.end and self.board.end_condition() == None:
325                         global game
326                         # Work out the last move
327                                         
328                         t = last_line.split(" ")
329                         if t[len(t)-2] == "black":
330                                 self.players.reverse()
331                         elif t[len(t)-2] == "white":
332                                 pass
333                         elif self.state["turn"] != None and self.state["turn"].colour == "white":
334                                 self.players.reverse()
335
336
337                         game = GameThread(self.board, self.players)
338                         game.run()
339                 else:
340                         pass
341
342                 
343
344 def opponent(colour):
345         if colour == "white":
346                 return "black"
347         else:
348                 return "white"

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