16f26d72a8699d78f170aa87ac0f5191829f80d4
[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                                         result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
75                                         log(result)
76
77                                         self.board.update_move(x, y, x2, y2)
78                                         
79                                         for p2 in self.players:
80                                                 p2.update(result) # Inform players of what happened
81
82                                                                                 
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                                 end = self.board.end_condition()
106                                 if end != None:         
107                                         with self.lock:
108                                                 if end == "DRAW":
109                                                         self.final_result = self.state["turn"].colour + " " + end
110                                                 else:
111                                                         self.final_result = end
112                                         self.stop()
113                                 
114                                 if self.stopped():
115                                         break
116
117
118                 for p2 in self.players:
119                         p2.quit(self.final_result)
120
121                 log(self.final_result)
122
123                 if isinstance(graphics, GraphicsThread):
124                         graphics.stop()
125
126         
127 # A thread that replays a log file
128 class ReplayThread(GameThread):
129         def __init__(self, players, src, end=False,max_moves=None):
130                 self.board = Board(style="empty")
131                 self.board.max_moves = max_moves
132                 GameThread.__init__(self, self.board, players)
133                 self.src = src
134                 self.end = end
135
136                 self.reset_board(self.src.readline())
137
138         def reset_board(self, line):
139                 agent_str = ""
140                 self_str = ""
141                 while line != "# Start game" and line != "# EOF":
142                         
143                         while line == "":
144                                 line = self.src.readline().strip(" \r\n")
145                                 continue
146
147                         if line[0] == '#':
148                                 line = self.src.readline().strip(" \r\n")
149                                 continue
150
151                         self_str += line + "\n"
152
153                         if self.players[0].name == "dummy" and self.players[1].name == "dummy":
154                                 line = self.src.readline().strip(" \r\n")
155                                 continue
156                         
157                         tokens = line.split(" ")
158                         types = map(lambda e : e.strip("[] ,'"), tokens[2:4])
159                         for i in range(len(types)):
160                                 if types[i][0] == "?":
161                                         types[i] = "unknown"
162
163                         agent_str += tokens[0] + " " + tokens[1] + " " + str(types) + " ".join(tokens[4:]) + "\n"
164                         line = self.src.readline().strip(" \r\n")
165
166                 for p in self.players:
167                         p.reset_board(agent_str)
168                 
169                 
170                 self.board.reset_board(self_str)
171
172         
173         def run(self):
174                 move_count = 0
175                 last_line = ""
176                 line = self.src.readline().strip(" \r\n")
177                 while line != "# EOF":
178
179
180                         if self.stopped():
181                                 break
182                         
183                                         
184
185                         if line[0] == '#':
186                                 last_line = line
187                                 line = self.src.readline().strip(" \r\n")
188                                 continue
189
190                         tokens = line.split(" ")
191                         if tokens[0] == "white" or tokens[0] == "black":
192                                 self.reset_board(line)
193                                 last_line = line
194                                 line = self.src.readline().strip(" \r\n")
195                                 continue
196
197                         move = line.split(":")
198                         move = move[len(move)-1].strip(" \r\n")
199                         tokens = move.split(" ")
200                         
201                         
202                         try:
203                                 [x,y] = map(int, tokens[0:2])
204                         except:
205                                 last_line = line
206                                 self.stop()
207                                 break
208
209                         log(move)
210
211                         target = self.board.grid[x][y]
212                         with self.lock:
213                                 if target.colour == "white":
214                                         self.state["turn"] = self.players[0]
215                                 else:
216                                         self.state["turn"] = self.players[1]
217                         
218                         move_piece = (tokens[2] == "->")
219                         if move_piece:
220                                 [x2,y2] = map(int, tokens[len(tokens)-2:])
221
222                         if isinstance(graphics, GraphicsThread):
223                                 with graphics.lock:
224                                         graphics.state["select"] = target
225                                         
226                         if not move_piece:
227                                 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
228                                 if isinstance(graphics, GraphicsThread):
229                                         with graphics.lock:
230                                                 graphics.state["moves"] = self.board.possible_moves(target)
231                                         time.sleep(turn_delay)
232                         else:
233                                 self.board.update_move(x, y, x2, y2)
234                                 if isinstance(graphics, GraphicsThread):
235                                         with graphics.lock:
236                                                 graphics.state["moves"] = [[x2,y2]]
237                                         time.sleep(turn_delay)
238                                         with graphics.lock:
239                                                 graphics.state["select"] = None
240                                                 graphics.state["moves"] = None
241                                                 graphics.state["dest"] = None
242                         
243
244                         
245                         
246                         
247                         for p in self.players:
248                                 p.update(move)
249
250                         last_line = line
251                         line = self.src.readline().strip(" \r\n")
252                         
253                         
254                         end = self.board.end_condition()
255                         if end != None:
256                                 self.final_result = end
257                                 self.stop()
258                                 break
259                                         
260                                                 
261                                                 
262
263                         
264                                         
265
266
267                         
268
269                                 
270                         
271
272                 
273
274                 if self.end and isinstance(graphics, GraphicsThread):
275                         #graphics.stop()
276                         pass # Let the user stop the display
277                 elif not self.end and self.board.end_condition() == None:
278                         global game
279                         # Work out the last move
280                                         
281                         t = last_line.split(" ")
282                         if t[len(t)-2] == "black":
283                                 self.players.reverse()
284                         elif t[len(t)-2] == "white":
285                                 pass
286                         elif self.state["turn"] != None and self.state["turn"].colour == "white":
287                                 self.players.reverse()
288
289
290                         game = GameThread(self.board, self.players)
291                         game.run()
292                 else:
293                         pass
294
295                 
296
297 def opponent(colour):
298         if colour == "white":
299                 return "black"
300         else:
301                 return "white"

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