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

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