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

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