Dedicated server stuff should now work
[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                         # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
136                         #       except Exception,e:
137                         #               result = e.message
138                         #               #sys.stderr.write(result + "\n")
139                         #               
140                         #               self.stop()
141                         #               with self.lock:
142                         #                       self.final_result = self.state["turn"].colour + " " + e.message
143
144                                 end = self.board.end_condition()
145                                 if end != None:         
146                                         with self.lock:
147                                                 if end == "DRAW":
148                                                         self.final_result = self.state["turn"].colour + " " + end
149                                                 else:
150                                                         self.final_result = end
151                                         self.stop()
152                                 
153                                 if self.stopped():
154                                         break
155
156
157                 for p2 in self.players:
158                         p2.quit(self.final_result)
159
160                 log(self.final_result)
161
162                 if isinstance(graphics, GraphicsThread):
163                         graphics.stop()
164
165         
166 # A thread that replays a log file
167 class ReplayThread(GameThread):
168         def __init__(self, players, src, end=False,max_moves=None):
169                 self.board = Board(style="empty")
170                 self.board.max_moves = max_moves
171                 GameThread.__init__(self, self.board, players)
172                 self.src = src
173                 self.end = end
174
175                 self.reset_board(self.src.readline())
176
177         def reset_board(self, line):
178                 agent_str = ""
179                 self_str = ""
180                 while line != "# Start game" and line != "# EOF":
181                         
182                         while line == "":
183                                 line = self.src.readline().strip(" \r\n")
184                                 continue
185
186                         if line[0] == '#':
187                                 line = self.src.readline().strip(" \r\n")
188                                 continue
189
190                         self_str += line + "\n"
191
192                         if self.players[0].name == "dummy" and self.players[1].name == "dummy":
193                                 line = self.src.readline().strip(" \r\n")
194                                 continue
195                         
196                         tokens = line.split(" ")
197                         types = map(lambda e : e.strip("[] ,'"), tokens[2:4])
198                         for i in range(len(types)):
199                                 if types[i][0] == "?":
200                                         types[i] = "unknown"
201
202                         agent_str += tokens[0] + " " + tokens[1] + " " + str(types) + " ".join(tokens[4:]) + "\n"
203                         line = self.src.readline().strip(" \r\n")
204
205                 for p in self.players:
206                         p.reset_board(agent_str)
207                 
208                 
209                 self.board.reset_board(self_str)
210
211         
212         def run(self):
213                 move_count = 0
214                 last_line = ""
215                 line = self.src.readline().strip(" \r\n")
216                 while line != "# EOF":
217
218
219                         if self.stopped():
220                                 break
221                         
222                         if len(line) <= 0:
223                                 continue
224                                         
225
226                         if line[0] == '#':
227                                 last_line = line
228                                 line = self.src.readline().strip(" \r\n")
229                                 continue
230
231                         tokens = line.split(" ")
232                         if tokens[0] == "white" or tokens[0] == "black":
233                                 self.reset_board(line)
234                                 last_line = line
235                                 line = self.src.readline().strip(" \r\n")
236                                 continue
237
238                         move = line.split(":")
239                         move = move[len(move)-1].strip(" \r\n")
240                         tokens = move.split(" ")
241                         
242                         
243                         try:
244                                 [x,y] = map(int, tokens[0:2])
245                         except:
246                                 last_line = line
247                                 self.stop()
248                                 break
249
250                         log(move)
251
252                         target = self.board.grid[x][y]
253                         with self.lock:
254                                 if target.colour == "white":
255                                         self.state["turn"] = self.players[0]
256                                 else:
257                                         self.state["turn"] = self.players[1]
258                         
259                         move_piece = (tokens[2] == "->")
260                         if move_piece:
261                                 [x2,y2] = map(int, tokens[len(tokens)-2:])
262
263                         if isinstance(graphics, GraphicsThread):
264                                 with graphics.lock:
265                                         graphics.state["select"] = target
266                                         
267                         if not move_piece:
268                                 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
269                                 if isinstance(graphics, GraphicsThread):
270                                         with graphics.lock:
271                                                 if target.current_type != "unknown":
272                                                         graphics.state["moves"] = self.board.possible_moves(target)
273                                                 else:
274                                                         graphics.state["moves"] = None
275                                         time.sleep(turn_delay)
276                         else:
277                                 self.board.update_move(x, y, x2, y2)
278                                 if isinstance(graphics, GraphicsThread):
279                                         with graphics.lock:
280                                                 graphics.state["moves"] = [[x2,y2]]
281                                         time.sleep(turn_delay)
282                                         with graphics.lock:
283                                                 graphics.state["select"] = None
284                                                 graphics.state["moves"] = None
285                                                 graphics.state["dest"] = None
286                         
287
288                         
289                         
290                         
291                         for p in self.players:
292                                 p.update(move)
293
294                         last_line = line
295                         line = self.src.readline().strip(" \r\n")
296                         
297                         
298                         end = self.board.end_condition()
299                         if end != None:
300                                 self.final_result = end
301                                 self.stop()
302                                 break
303                                         
304                                                 
305                                                 
306
307                         
308                                         
309
310
311                         
312
313                                 
314                         
315
316                 
317
318                 if self.end and isinstance(graphics, GraphicsThread):
319                         #graphics.stop()
320                         pass # Let the user stop the display
321                 elif not self.end and self.board.end_condition() == None:
322                         global game
323                         # Work out the last move
324                                         
325                         t = last_line.split(" ")
326                         if t[len(t)-2] == "black":
327                                 self.players.reverse()
328                         elif t[len(t)-2] == "white":
329                                 pass
330                         elif self.state["turn"] != None and self.state["turn"].colour == "white":
331                                 self.players.reverse()
332
333
334                         game = GameThread(self.board, self.players)
335                         game.run()
336                 else:
337                         pass
338
339                 
340
341 def opponent(colour):
342         if colour == "white":
343                 return "black"
344         else:
345                 return "white"

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