Added sample agent + log file writing/parsing
[progcomp2013.git] / qchess / src / game.py
1
2
3 log_file = None
4
5 def log(s):
6         if log_file != None:
7                 import datetime
8                 log_file.write(str(datetime.datetime.now()) + " : " + s + "\n")
9
10 def log_init(board, players):
11         if log_file != None:
12                 import datetime
13                 log_file.write("# Log starts " + str(datetime.datetime.now()) + "\n")
14                 for p in players:
15                         log_file.write("# " + p.colour + " : " + p.name + "\n")
16                 
17                 log_file.write("# Initial board\n")
18                 for x in range(0, w):
19                         for y in range(0, h):
20                                 if board.grid[x][y] != None:
21                                         log_file.write(str(board.grid[x][y]) + "\n")
22
23                 log_file.write("# Start game\n")
24         
25
26 # A thread that runs the game
27 class GameThread(StoppableThread):
28         def __init__(self, board, players):
29                 StoppableThread.__init__(self)
30                 self.board = board
31                 self.players = players
32                 self.state = {"turn" : None} # The game state
33                 self.error = 0 # Whether the thread exits with an error
34                 self.lock = threading.RLock() #lock for access of self.state
35                 self.cond = threading.Condition() # conditional for some reason, I forgot
36                 self.final_result = ""
37                 
38                 
39
40         # Run the game (run in new thread with start(), run in current thread with run())
41         def run(self):
42                 result = ""
43                 while not self.stopped():
44                         
45                         for p in self.players:
46                                 with self.lock:
47                                         if isinstance(p, NetworkSender):
48                                                 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
49                                         else:
50                                                 self.state["turn"] = p
51                                 #try:
52                                 if True:
53                                         [x,y] = p.select() # Player selects a square
54                                         if self.stopped():
55                                                 break
56
57                                         
58                                                 
59
60                                         result = self.board.select(x, y, colour = p.colour)                             
61                                         for p2 in self.players:
62                                                 p2.update(result) # Inform players of what happened
63
64
65                                         log(result)
66
67                                         target = self.board.grid[x][y]
68                                         if isinstance(graphics, GraphicsThread):
69                                                 with graphics.lock:
70                                                         graphics.state["moves"] = self.board.possible_moves(target)
71                                                         graphics.state["select"] = target
72
73                                         time.sleep(turn_delay)
74
75
76                                         if len(self.board.possible_moves(target)) == 0:
77                                                 #print "Piece cannot move"
78                                                 target.deselect()
79                                                 if isinstance(graphics, GraphicsThread):
80                                                         with graphics.lock:
81                                                                 graphics.state["moves"] = None
82                                                                 graphics.state["select"] = None
83                                                                 graphics.state["dest"] = None
84                                                 continue
85
86                                         try:
87                                                 [x2,y2] = p.get_move() # Player selects a destination
88                                         except:
89                                                 self.stop()
90
91                                         if self.stopped():
92                                                 break
93
94                                         self.board.update_move(x, y, x2, y2)
95                                         result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
96                                         for p2 in self.players:
97                                                 p2.update(result) # Inform players of what happened
98
99                                         log(result)
100
101                                         if isinstance(graphics, GraphicsThread):
102                                                 with graphics.lock:
103                                                         graphics.state["moves"] = [[x2,y2]]
104
105                                         time.sleep(turn_delay)
106
107                                         if isinstance(graphics, GraphicsThread):
108                                                 with graphics.lock:
109                                                         graphics.state["select"] = None
110                                                         graphics.state["dest"] = None
111                                                         graphics.state["moves"] = None
112
113                         # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
114                         #       except Exception,e:
115                         #               result = e.message
116                         #               #sys.stderr.write(result + "\n")
117                         #               
118                         #               self.stop()
119                         #               with self.lock:
120                         #                       self.final_result = self.state["turn"].colour + " " + e.message
121
122                                 if self.board.king["black"] == None:
123                                         if self.board.king["white"] == None:
124                                                 with self.lock:
125                                                         self.final_result = self.state["turn"].colour + " DRAW"
126                                         else:
127                                                 with self.lock:
128                                                         self.final_result = "white"
129                                         self.stop()
130                                 elif self.board.king["white"] == None:
131                                         with self.lock:
132                                                 self.final_result = "black"
133                                         self.stop()
134                                                 
135
136                                 if self.stopped():
137                                         break
138
139
140                 for p2 in self.players:
141                         p2.quit(self.final_result)
142
143                 log(self.final_result)
144
145                 graphics.stop()
146
147         
148 # A thread that replays a log file
149 class ReplayThread(GameThread):
150         def __init__(self, players, src, end=False,max_lines=None):
151                 self.board = Board(style="empty")
152                 GameThread.__init__(self, self.board, players)
153                 self.src = src
154                 self.max_lines = max_lines
155                 self.line_number = 0
156                 self.end = end
157
158                 try:
159                         while self.src.readline().strip(" \r\n") != "# Initial board":
160                                 self.line_number += 1
161                 
162                         line = self.src.readline().strip(" \r\n")
163                         
164                         while line != "# Start game":
165                                 #print "Reading line " + str(line)
166                                 self.line_number += 1
167                                 [x,y] = map(int, line.split("at")[1].strip(" \r\n").split(","))
168                                 colour = line.split(" ")[0]
169                                 current_type = line.split(" ")[1]
170                                 types = map(lambda e : e.strip(" [],'"), line.split(" ")[2:4])
171                                 p = Piece(colour, x, y, types)
172                                 if current_type != "unknown":
173                                         p.current_type = current_type
174                                         p.choice = types.index(current_type)
175
176                                 self.board.pieces[colour].append(p)
177                                 self.board.grid[x][y] = p
178                                 if current_type == "king":
179                                         self.board.king[colour] = p
180
181                                 line = self.src.readline().strip(" \r\n")
182                                 
183                 except Exception, e:
184                         raise Exception("FILE line: " + str(self.line_number) + " \""+str(line)+"\"") #\n" + e.message)
185         
186         def run(self):
187                 i = 0
188                 phase = 0
189                 count = 0
190                 line = self.src.readline().strip(" \r\n")
191                 while line != "# EOF":
192                         count += 1
193                         if self.max_lines != None and count > self.max_lines:
194                                 self.stop()
195
196                         if self.stopped():
197                                 break
198
199                         with self.lock:
200                                 self.state["turn"] = self.players[i]
201
202                         line = line.split(":")
203                         result = line[len(line)-1].strip(" \r\n")
204                         log(result)
205
206                         try:
207                                 self.board.update(result)
208                         except:
209                                 self.final_result = result
210                                 self.stop()
211                                 break
212
213                         [x,y] = map(int, result.split(" ")[0:2])
214                         target = self.board.grid[x][y]
215
216                         if isinstance(graphics, GraphicsThread):
217                                 if phase == 0:
218                                         with graphics.lock:
219                                                 graphics.state["moves"] = self.board.possible_moves(target)
220                                                 graphics.state["select"] = target
221
222                                         if self.end:
223                                                 time.sleep(turn_delay)
224
225                                 elif phase == 1:
226                                         [x2,y2] = map(int, result.split(" ")[3:5])
227                                         with graphics.lock:
228                                                 graphics.state["moves"] = [[x2,y2]]
229
230                                         if self.end:
231                                                 time.sleep(turn_delay)
232
233                                         with graphics.lock:
234                                                 graphics.state["select"] = None
235                                                 graphics.state["dest"] = None
236                                                 graphics.state["moves"] = None
237                                                 
238
239
240                         
241
242                         for p in self.players:
243                                 p.update(result)
244                         
245                         phase = (phase + 1) % 2
246                         if phase == 0:
247                                 i = (i + 1) % 2
248
249                         line = self.src.readline().strip(" \r\n")
250
251                 if self.max_lines != None and self.max_lines > count:
252                         sys.stderr.write(sys.argv[0] + " : Replaying from file; stopping at last line (" + str(count) + ")\n")
253                         sys.stderr.write(sys.argv[0] + " : (You requested line " + str(self.max_lines) + ")\n")
254
255                 if self.end and isinstance(graphics, GraphicsThread):
256                         #graphics.stop()
257                         pass # Let the user stop the display
258                 elif not self.end:
259                         global game
260                         game = GameThread(self.board, self.players)
261                         game.run()
262                 
263
264                 
265
266 def opponent(colour):
267         if colour == "white":
268                 return "black"
269         else:
270                 return "white"

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