8deeddb3cc0c5991a8dfddd7c524c43002a5d6a9
[progcomp2013.git] / qchess / qchess.py
1 #!/usr/bin/python -u
2 import random
3
4 # I know using non-abreviated strings is inefficient, but this is python, who cares?
5 # Oh, yeah, this stores the number of pieces of each type in a normal chess game
6 piece_types = {"pawn" : 8, "bishop" : 2, "knight" : 2, "rook" : 2, "queen" : 1, "king" : 1, "unknown" : 0}
7
8 # Class to represent a quantum chess piece
9 class Piece():
10         def __init__(self, colour, x, y, types):
11                 self.colour = colour # Colour (string) either "white" or "black"
12                 self.x = x # x coordinate (0 - 8), none of this fancy 'a', 'b' shit here
13                 self.y = y # y coordinate (0 - 8)
14                 self.types = types # List of possible types the piece can be (should just be two)
15                 self.current_type = "unknown" # Current type
16                 self.choice = -1 # Index of the current type in self.types (-1 = unknown type)
17                 
18                 
19                 self.last_state = None
20                 
21                 self.move_pattern = None
22                 self.coverage = None
23                 self.possible_moves = {}
24                 
25
26         def init_from_copy(self, c):
27                 self.colour = c.colour
28                 self.x = c.x
29                 self.y = c.y
30                 self.types = c.types[:]
31                 self.current_type = c.current_type
32                 self.choice = c.choice
33                 
34                 self.last_state = None
35                 self.move_pattern = None
36
37         
38
39         # Make a string for the piece (used for debug)
40         def __str__(self):
41                 return str(self.colour) + " " + str(self.current_type) + " " + str(self.types) + " at " + str(self.x) + ","+str(self.y)  
42
43         # Draw the piece in a pygame surface
44         def draw(self, window, grid_sz = [80,80], style="quantum"):
45
46                 # First draw the image corresponding to self.current_type
47                 img = images[self.colour][self.current_type]
48                 rect = img.get_rect()
49                 if style == "classical":
50                         offset = [-rect.width/2, -rect.height/2]
51                 else:
52                         offset = [-rect.width/2,-3*rect.height/4] 
53                 window.blit(img, (self.x * grid_sz[0] + grid_sz[0]/2 + offset[0], self.y * grid_sz[1] + grid_sz[1]/2 + offset[1]))
54                 
55                 
56                 if style == "classical":
57                         return
58
59                 # Draw the two possible types underneath the current_type image
60                 for i in range(len(self.types)):
61                         if always_reveal_states == True or self.types[i][0] != '?':
62                                 if self.types[i][0] == '?':
63                                         img = small_images[self.colour][self.types[i][1:]]
64                                 else:
65                                         img = small_images[self.colour][self.types[i]]
66                         else:
67                                 img = small_images[self.colour]["unknown"] # If the type hasn't been revealed, show a placeholder
68
69                         
70                         rect = img.get_rect()
71                         offset = [-rect.width/2,-rect.height/2] 
72                         
73                         if i == 0:
74                                 target = (self.x * grid_sz[0] + grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])                             
75                         else:
76                                 target = (self.x * grid_sz[0] + 4*grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])                           
77                                 
78                         window.blit(img, target) # Blit shit
79         
80         # Collapses the wave function!          
81         def select(self):
82                 if self.current_type == "unknown" or not self.choice in [0,1]:
83                         self.choice = random.randint(0,1)
84                         if self.types[self.choice][0] == '?':
85                                 self.types[self.choice] = self.types[self.choice][1:]
86                         self.current_type = self.types[self.choice]
87                 return self.choice
88
89         # Uncollapses (?) the wave function!
90         def deselect(self):
91                 #print "Deselect called"
92                 if (self.x + self.y) % 2 != 0:
93                         if (self.types[0] != self.types[1]) or (self.types[0][0] == '?' or self.types[1][0] == '?'):
94                                 self.current_type = "unknown"
95                                 self.choice = -1
96                         else:
97                                 self.choice = 0 # Both the two types are the same
98
99         # The sad moment when you realise that you do not understand anything about a subject you studied for 4 years...
100 # --- piece.py --- #
101 [w,h] = [8,8] # Width and height of board(s)
102
103 always_reveal_states = False
104
105 # Class to represent a quantum chess board
106 class Board():
107         # Initialise; if master=True then the secondary piece types are assigned
108         #       Otherwise, they are left as unknown
109         #       So you can use this class in Agent programs, and fill in the types as they are revealed
110         def __init__(self, style="agent"):
111                 self.style = style
112                 self.pieces = {"white" : [], "black" : []}
113                 self.grid = [[None] * w for _ in range(h)] # 2D List (you can get arrays in python, somehow, but they scare me)
114                 self.unrevealed_types = {"white" : piece_types.copy(), "black" : piece_types.copy()}
115                 self.king = {"white" : None, "black" : None} # We need to keep track of the king, because he is important
116                 self.max_moves = None
117                 self.moves = 0
118                 self.move_stack = []
119                 for c in ["black", "white"]:
120                         del self.unrevealed_types[c]["unknown"]
121
122                 if style == "empty":
123                         return
124
125                 # Add all the pieces with known primary types
126                 for i in range(0, 2):
127                         
128                         s = ["black", "white"][i]
129                         c = self.pieces[s]
130                         y = [0, h-1][i]
131
132                         c.append(Piece(s, 0, y, ["rook"]))
133                         c.append(Piece(s, 1, y, ["knight"]))
134                         c.append(Piece(s, 2, y, ["bishop"]))
135                         k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
136                         k.current_type = "king"
137                         self.king[s] = k
138                         c.append(k)
139                         c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
140                         c.append(Piece(s, 5, y, ["bishop"]))
141                         c.append(Piece(s, 6, y, ["knight"]))
142                         c.append(Piece(s, 7, y, ["rook"]))
143                         
144                         if y == 0: 
145                                 y += 1 
146                         else: 
147                                 y -= 1
148                         
149                         # Lots of pawn
150                         for x in range(0, w):
151                                 c.append(Piece(s, x, y, ["pawn"]))
152
153                         types_left = {}
154                         types_left.update(piece_types)
155                         del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
156                         del types_left["unknown"] # We certainly don't want these!
157                         for piece in c:
158                                 # Add to grid
159                                 self.grid[piece.x][piece.y] = piece 
160
161                                 if len(piece.types) > 1:
162                                         continue                                
163                                 if style == "agent": # Assign placeholder "unknown" secondary type
164                                         piece.types.append("unknown")
165                                         continue
166
167                                 elif style == "quantum":
168                                         # The master allocates the secondary types
169                                         choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
170                                         types_left[choice] -= 1
171                                         if types_left[choice] <= 0:
172                                                 del types_left[choice]
173                                         piece.types.append('?' + choice)
174                                 elif style == "classical":
175                                         piece.types.append(piece.types[0])
176                                         piece.current_type = piece.types[0]
177                                         piece.choice = 0
178
179         def clone(self):
180                 newboard = Board(master = False)
181                 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
182                 mypieces = self.pieces["white"] + self.pieces["black"]
183
184                 for i in range(len(mypieces)):
185                         newpieces[i].init_from_copy(mypieces[i])
186         
187         # Reset the board from a string
188         def reset_board(self, s):
189                 self.pieces = {"white" : [], "black" : []}
190                 self.king = {"white" : None, "black" : None}
191                 self.grid = [[None] * w for _ in range(h)]
192                 for x in range(w):
193                         for y in range(h):
194                                 self.grid[x][y] = None
195
196                 for line in s.split("\n"):
197                         if line == "":
198                                 continue
199                         if line[0] == "#":
200                                 continue
201
202                         tokens = line.split(" ")
203                         [x, y] = map(int, tokens[len(tokens)-1].split(","))
204                         current_type = tokens[1]
205                         types = map(lambda e : e.strip(" '[],"), line.split('[')[1].split(']')[0].split(','))
206                         
207                         target = Piece(tokens[0], x, y, types)
208                         target.current_type = current_type
209                         
210                         try:
211                                 target.choice = types.index(current_type)
212                         except:
213                                 target.choice = -1
214
215                         self.pieces[tokens[0]].append(target)
216                         if target.current_type == "king":
217                                 self.king[tokens[0]] = target
218
219                         self.grid[x][y] = target
220                         
221
222         def display_grid(self, window = None, grid_sz = [80,80]):
223                 if window == None:
224                         return # I was considering implementing a text only display, then I thought "Fuck that"
225
226                 # The indentation is getting seriously out of hand...
227                 for x in range(0, w):
228                         for y in range(0, h):
229                                 if (x + y) % 2 == 0:
230                                         c = pygame.Color(200,200,200)
231                                 else:
232                                         c = pygame.Color(64,64,64)
233                                 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
234
235         def display_pieces(self, window = None, grid_sz = [80,80]):
236                 if window == None:
237                         return
238                 for p in self.pieces["white"] + self.pieces["black"]:
239                         p.draw(window, grid_sz, self.style)
240
241         # Draw the board in a pygame window
242         def display(self, window = None):
243                 self.display_grid(window)
244                 self.display_pieces(window)
245                 
246
247                 
248
249         def verify(self):
250                 for x in range(w):
251                         for y in range(h):
252                                 if self.grid[x][y] == None:
253                                         continue
254                                 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
255                                         raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
256
257         # Select a piece on the board (colour is the colour of whoever is doing the selecting)
258         def select(self, x,y, colour=None):
259                 if not self.on_board(x, y): # Get on board everyone!
260                         raise Exception("BOUNDS")
261
262                 piece = self.grid[x][y]
263                 if piece == None:
264                         raise Exception("EMPTY")
265
266                 if colour != None and piece.colour != colour:
267                         raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
268
269                 # I'm not quite sure why I made this return a string, but screw logical design
270                 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
271
272
273         # Update the board when a piece has been selected
274         # "type" is apparently reserved, so I'll use "state"
275         def update_select(self, x, y, type_index, state):
276                 piece = self.grid[x][y]
277                 if piece.types[type_index] == "unknown":
278                         if not state in self.unrevealed_types[piece.colour].keys():
279                                 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
280                         self.unrevealed_types[piece.colour][state] -= 1
281                         if self.unrevealed_types[piece.colour][state] <= 0:
282                                 del self.unrevealed_types[piece.colour][state]
283
284                 piece.types[type_index] = state
285                 piece.current_type = state
286
287                 if len(self.possible_moves(piece)) <= 0:
288                         piece.deselect() # Piece can't move; deselect it
289                         
290                 # Piece needs to recalculate moves
291                 piece.possible_moves = None
292                 
293         # Update the board when a piece has been moved
294         def update_move(self, x, y, x2, y2):
295                                 
296                 piece = self.grid[x][y]
297                 #print "Moving " + str(x) + "," + str(y) + " to " + str(x2) + "," + str(y2) + "; possible_moves are " + str(self.possible_moves(piece))
298                 
299                 if not [x2,y2] in self.possible_moves(piece):
300                         raise Exception("ILLEGAL move " + str(x2)+","+str(y2))
301                 
302                 self.grid[x][y] = None
303                 taken = self.grid[x2][y2]
304                 if taken != None:
305                         if taken.current_type == "king":
306                                 self.king[taken.colour] = None
307                         self.pieces[taken.colour].remove(taken)
308                 self.grid[x2][y2] = piece
309                 piece.x = x2
310                 piece.y = y2
311
312                 # If the piece is a pawn, and it reaches the final row, it becomes a queen
313                 # I know you are supposed to get a choice
314                 # But that would be effort
315                 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
316                         if self.style == "classical":
317                                 piece.types[0] = "queen"
318                                 piece.types[1] = "queen"
319                         else:
320                                 piece.types[piece.choice] = "queen"
321                         piece.current_type = "queen"
322
323                 piece.deselect() # Uncollapse (?) the wavefunction!
324                 self.moves += 1
325                 
326                 # All other pieces need to recalculate moves
327                 for p in self.pieces["white"] + self.pieces["black"]:
328                         p.possible_moves = None
329                 
330                 #self.verify()  
331
332         # Update the board from a string
333         # Guesses what to do based on the format of the string
334         def update(self, result):
335                 #print "Update called with \"" + str(result) + "\""
336                 # String always starts with 'x y'
337                 try:
338                         s = result.split(" ")
339                         [x,y] = map(int, s[0:2])        
340                 except:
341                         raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
342
343                 piece = self.grid[x][y]
344                 if piece == None:
345                         raise Exception("EMPTY")
346
347                 # If a piece is being moved, the third token is '->'
348                 # We could get away with just using four integers, but that wouldn't look as cool
349                 if "->" in s:
350                         # Last two tokens are the destination
351                         try:
352                                 [x2,y2] = map(int, s[3:])
353                         except:
354                                 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
355
356                         # Move the piece (take opponent if possible)
357                         self.update_move(x, y, x2, y2)
358                         
359                 else:
360                         # Otherwise we will just assume a piece has been selected
361                         try:
362                                 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
363                                 state = s[3] # The last token is a string identifying the type
364                         except:
365                                 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
366
367                         # Select the piece
368                         self.update_select(x, y, type_index, state)
369
370                 return result
371
372         # Gets each piece that could reach the given square and the probability that it could reach that square 
373         # Will include allied pieces that defend the attacker
374         def coverage(self, x, y, colour = None, reject_allied = True):
375                 result = {}
376                 
377                 if colour == None:
378                         pieces = self.pieces["white"] + self.pieces["black"]
379                 else:
380                         pieces = self.pieces[colour]
381
382                 for p in pieces:
383                         prob = self.probability_grid(p, reject_allied)[x][y]
384                         if prob > 0:
385                                 result.update({p : prob})
386                 
387                 #self.verify()
388                 return result
389
390
391                 
392
393
394         # Associates each square with a probability that the piece could move into it
395         # Look, I'm doing all the hard work for you here...
396         def probability_grid(self, p, reject_allied = True):
397                 
398                 result = [[0.0] * w for _ in range(h)]
399                 if not isinstance(p, Piece):
400                         return result
401
402                 if p.current_type != "unknown":
403                         #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
404                         for point in self.possible_moves(p, reject_allied):
405                                 result[point[0]][point[1]] = 1.0
406                         return result
407                 
408                 
409                 for i in range(len(p.types)):
410                         t = p.types[i]
411                         prob = 1.0 / float(len(p.types))
412                         if t == "unknown" or p.types[i][0] == '?':
413                                 total_types = 0
414                                 for t2 in self.unrevealed_types[p.colour].keys():
415                                         total_types += self.unrevealed_types[p.colour][t2]
416                                 
417                                 for t2 in self.unrevealed_types[p.colour].keys():
418                                         prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
419                                         #p.current_type = t2
420                                         for point in self.possible_moves(p, reject_allied, state=t2):
421                                                 result[point[0]][point[1]] += prob2 * prob
422                                 
423                         else:
424                                 #p.current_type = t
425                                 for point in self.possible_moves(p, reject_allied, state=t):
426                                                 result[point[0]][point[1]] += prob
427                 
428                 #self.verify()
429                 #p.current_type = "unknown"
430                 return result
431
432         def prob_is_type(self, p, state):
433                 prob = 0.5
434                 result = 0
435                 for i in range(len(p.types)):
436                         t = p.types[i]
437                         if t == state:
438                                 result += prob
439                                 continue        
440                         if t == "unknown" or p.types[i][0] == '?':
441                                 total_prob = 0
442                                 for t2 in self.unrevealed_types[p.colour].keys():
443                                         total_prob += self.unrevealed_types[p.colour][t2]
444                                 for t2 in self.unrevealed_types[p.colour].keys():
445                                         if t2 == state:
446                                                 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
447                                 
448
449
450         # Get all squares that the piece could move into
451         # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
452         # reject_allied indicates whether squares occupied by allied pieces will be removed
453         # (set to false to check for defense)
454         def possible_moves(self, p, reject_allied = True, state=None):
455                 if p == None:
456                         raise Exception("SANITY: No piece")
457                 
458                 
459                 
460                 if state != None and state != p.current_type:
461                         old_type = p.current_type
462                         p.current_type = state
463                         result = self.possible_moves(p, reject_allied, state=None)
464                         p.current_type = old_type
465                         return result
466                 
467                 
468                 
469                 
470                 result = []
471                 
472
473                 
474                 if p.current_type == "unknown":
475                         raise Exception("SANITY: Piece state unknown")
476                         # The below commented out code causes things to break badly
477                         #for t in p.types:
478                         #       if t == "unknown":
479                         #               continue
480                         #       p.current_type = t
481                         #       result += self.possible_moves(p)                                                
482                         #p.current_type = "unknown"
483                         #return result
484
485                 if p.current_type == "king":
486                         result = [[p.x-1,p.y],[p.x+1,p.y],[p.x,p.y-1],[p.x,p.y+1], [p.x-1,p.y-1],[p.x-1,p.y+1],[p.x+1,p.y-1],[p.x+1,p.y+1]]
487                 elif p.current_type == "queen":
488                         for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
489                                 result += self.scan(p.x, p.y, d[0], d[1])
490                 elif p.current_type == "bishop":
491                         for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
492                                 result += self.scan(p.x, p.y, d[0], d[1])
493                 elif p.current_type == "rook":
494                         for d in [[-1,0],[1,0],[0,-1],[0,1]]:
495                                 result += self.scan(p.x, p.y, d[0], d[1])
496                 elif p.current_type == "knight":
497                         # I would use two lines, but I'm not sure how python likes that
498                         result = [[p.x-2, p.y-1], [p.x-2, p.y+1], [p.x+2, p.y-1], [p.x+2,p.y+1], [p.x-1,p.y-2], [p.x-1, p.y+2],[p.x+1,p.y-2],[p.x+1,p.y+2]]
499                 elif p.current_type == "pawn":
500                         if p.colour == "white":
501                                 
502                                 # Pawn can't move forward into occupied square
503                                 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
504                                         result = [[p.x,p.y-1]]
505                                 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
506                                         if not self.on_board(f[0], f[1]):
507                                                 continue
508                                         if self.grid[f[0]][f[1]] != None:  # Pawn can take diagonally
509                                                 result.append(f)
510                                 if p.y == h-2:
511                                         # Slightly embarrassing if the pawn jumps over someone on its first move...
512                                         if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
513                                                 result.append([p.x, p.y-2])
514                         else:
515                                 # Vice versa for the black pawn
516                                 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
517                                         result = [[p.x,p.y+1]]
518
519                                 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
520                                         if not self.on_board(f[0], f[1]):
521                                                 continue
522                                         if self.grid[f[0]][f[1]] != None:
523                                                 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
524                                                 result.append(f)
525                                 if p.y == 1:
526                                         if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
527                                                 result.append([p.x, p.y+2])
528
529                         #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
530
531                 # Remove illegal moves
532                 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
533                 for point in result[:]: 
534
535                         if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
536                                 result.remove(point) # Remove locations outside the board
537                                 continue
538                         g = self.grid[point[0]][point[1]]
539                         
540                         if g != None and (g.colour == p.colour and reject_allied == True):
541                                 result.remove(point) # Remove allied pieces
542                 
543                 #self.verify()
544                 
545                 p.possible_moves = result
546                 return result
547
548
549         # Scans in a direction until it hits a piece, returns all squares in the line
550         # (includes the final square (which contains a piece), but not the original square)
551         def scan(self, x, y, vx, vy):
552                 p = []
553                         
554                 xx = x
555                 yy = y
556                 while True:
557                         xx += vx
558                         yy += vy
559                         if not self.on_board(xx, yy):
560                                 break
561                         if not [xx,yy] in p:
562                                 p.append([xx, yy])
563                         g = self.grid[xx][yy]
564                         if g != None:
565                                 return p        
566                                         
567                 return p
568
569         # Returns "white", "black" or "DRAW" if the game should end
570         def end_condition(self):
571                 if self.king["white"] == None:
572                         if self.king["black"] == None:
573                                 return "DRAW" # This shouldn't happen
574                         return "black"
575                 elif self.king["black"] == None:
576                         return "white"
577                 elif len(self.pieces["white"]) == 1 and len(self.pieces["black"]) == 1:
578                         return "DRAW"
579                 elif self.max_moves != None and self.moves > self.max_moves:
580                         return "DRAW"
581                 return None
582
583
584         # I typed the full statement about 30 times before writing this function...
585         def on_board(self, x, y):
586                 return (x >= 0 and x < w) and (y >= 0 and y < h)
587         
588         # Pushes a move temporarily
589         def push_move(self, piece, x, y):
590                 target = self.grid[x][y]
591                 self.move_stack.append([piece, target, piece.x, piece.y, x, y])
592                 [piece.x, piece.y] = [x, y]
593                 self.grid[x][y] = piece
594                 self.grid[piece.x][piece.y] = None
595                 
596                 for p in self.pieces["white"] + self.pieces["black"]:
597                         p.possible_moves = None
598                 
599         # Restore move
600         def pop_move(self):
601                 #print str(self.move_stack)
602                 [piece, target, x1, y1, x2, y2] = self.move_stack[len(self.move_stack)-1]
603                 self.move_stack = self.move_stack[:-1]
604                 piece.x = x1
605                 piece.y = y1
606                 self.grid[x1][y1] = piece
607                 if target != None:
608                         target.x = x2
609                         target.y = y2
610                 self.grid[x2][y2] = target
611                 
612                 for p in self.pieces["white"] + self.pieces["black"]:
613                                 p.possible_moves = None
614                 
615 # --- board.py --- #
616 import subprocess
617 import select
618 import platform
619 import re
620
621 agent_timeout = -1.0 # Timeout in seconds for AI players to make moves
622                         # WARNING: Won't work for windows based operating systems
623
624 if platform.system() == "Windows":
625         agent_timeout = -1 # Hence this
626
627 # A player who can't play
628 class Player():
629         def __init__(self, name, colour):
630                 self.name = name
631                 self.colour = colour
632
633         def update(self, result):
634                 pass
635
636         def reset_board(self, s):
637                 pass
638
639 # Player that runs from another process
640 class ExternalAgent(Player):
641
642
643         def __init__(self, name, colour):
644                 Player.__init__(self, name, colour)
645                 self.p = subprocess.Popen(name,bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,universal_newlines=True)
646                 
647                 self.send_message(colour)
648
649         def send_message(self, s):
650                 if agent_timeout > 0.0:
651                         ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
652                 else:
653                         ready = [self.p.stdin]
654                 if self.p.stdin in ready:
655                         #sys.stderr.write("Writing \'" + s + "\' to " + str(self.p) + "\n")
656                         try:
657                                 self.p.stdin.write(s + "\n")
658                         except:
659                                 raise Exception("UNRESPONSIVE")
660                 else:
661                         raise Exception("TIMEOUT")
662
663         def get_response(self):
664                 if agent_timeout > 0.0:
665                         ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
666                 else:
667                         ready = [self.p.stdout]
668                 if self.p.stdout in ready:
669                         #sys.stderr.write("Reading from " + str(self.p) + " 's stdout...\n")
670                         try:
671                                 result = self.p.stdout.readline().strip(" \t\r\n")
672                                 #sys.stderr.write("Read \'" + result + "\' from " + str(self.p) + "\n")
673                                 return result
674                         except: # Exception, e:
675                                 raise Exception("UNRESPONSIVE")
676                 else:
677                         raise Exception("TIMEOUT")
678
679         def select(self):
680
681                 self.send_message("SELECTION?")
682                 line = self.get_response()
683                 
684                 try:
685                         m = re.match("\s*(\d+)\s+(\d+)\s*", line)
686                         result = map(int, [m.group(1), m.group(2)])
687                 except:
688                         raise Exception("GIBBERISH \"" + str(line) + "\"")
689                 return result
690
691         def update(self, result):
692                 #print "Update " + str(result) + " called for AgentPlayer"
693                 self.send_message(result)
694
695
696         def get_move(self):
697                 
698                 self.send_message("MOVE?")
699                 line = self.get_response()
700                 
701                 try:
702                         m = re.match("\s*(\d+)\s+(\d+)\s*", line)
703                         result = map(int, [m.group(1), m.group(2)])
704
705                 except:
706                         raise Exception("GIBBERISH \"" + str(line) + "\"")
707                 return result
708
709         def reset_board(self, s):
710                 self.send_message("BOARD")
711                 for line in s.split("\n"):
712                         self.send_message(line.strip(" \r\n"))
713                 self.send_message("END BOARD")
714
715         def quit(self, final_result):
716                 try:
717                         self.send_message("QUIT " + final_result)
718                 except:
719                         self.p.kill()
720
721 # So you want to be a player here?
722 class HumanPlayer(Player):
723         def __init__(self, name, colour):
724                 Player.__init__(self, name, colour)
725                 
726         # Select your preferred account
727         def select(self):
728                 if isinstance(graphics, GraphicsThread):
729                         # Basically, we let the graphics thread do some shit and then return that information to the game thread
730                         graphics.cond.acquire()
731                         # We wait for the graphics thread to select a piece
732                         while graphics.stopped() == False and graphics.state["select"] == None:
733                                 graphics.cond.wait() # The difference between humans and machines is that humans sleep
734                         select = graphics.state["select"]
735                         
736                         
737                         graphics.cond.release()
738                         if graphics.stopped():
739                                 return [-1,-1]
740                         return [select.x, select.y]
741                 else:
742                         # Since I don't display the board in this case, I'm not sure why I filled it in...
743                         while True:
744                                 sys.stdout.write("SELECTION?\n")
745                                 try:
746                                         p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
747                                 except:
748                                         sys.stderr.write("ILLEGAL GIBBERISH\n")
749                                         continue
750         # It's your move captain
751         def get_move(self):
752                 if isinstance(graphics, GraphicsThread):
753                         graphics.cond.acquire()
754                         while graphics.stopped() == False and graphics.state["dest"] == None:
755                                 graphics.cond.wait()
756                         graphics.cond.release()
757                         
758                         return graphics.state["dest"]
759                 else:
760
761                         while True:
762                                 sys.stdout.write("MOVE?\n")
763                                 try:
764                                         p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
765                                 except:
766                                         sys.stderr.write("ILLEGAL GIBBERISH\n")
767                                         continue
768
769         # Are you sure you want to quit?
770         def quit(self, final_result):
771                 if graphics == None:            
772                         sys.stdout.write("QUIT " + final_result + "\n")
773
774         # Completely useless function
775         def update(self, result):
776                 if isinstance(graphics, GraphicsThread):
777                         pass
778                 else:
779                         sys.stdout.write(result + "\n") 
780
781
782 # Default internal player (makes random moves)
783 class InternalAgent(Player):
784         def __init__(self, name, colour):
785                 Player.__init__(self, name, colour)
786                 self.choice = None
787
788                 self.board = Board(style = "agent")
789
790
791
792         def update(self, result):
793                 
794                 self.board.update(result)
795                 self.board.verify()
796
797         def reset_board(self, s):
798                 self.board.reset_board(s)
799
800         def quit(self, final_result):
801                 pass
802
803 class AgentRandom(InternalAgent):
804         def __init__(self, name, colour):
805                 InternalAgent.__init__(self, name, colour)
806
807         def select(self):
808                 while True:
809                         self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
810                         all_moves = []
811                         # Check that the piece has some possibility to move
812                         tmp = self.choice.current_type
813                         if tmp == "unknown": # For unknown pieces, try both types
814                                 for t in self.choice.types:
815                                         if t == "unknown":
816                                                 continue
817                                         self.choice.current_type = t
818                                         all_moves += self.board.possible_moves(self.choice)
819                         else:
820                                 all_moves = self.board.possible_moves(self.choice)
821                         self.choice.current_type = tmp
822                         if len(all_moves) > 0:
823                                 break
824                 return [self.choice.x, self.choice.y]
825
826         def get_move(self):
827                 moves = self.board.possible_moves(self.choice)
828                 move = moves[random.randint(0, len(moves)-1)]
829                 return move
830
831
832 # Terrible, terrible hacks
833
834 def run_agent(agent):
835         #sys.stderr.write(sys.argv[0] + " : Running agent " + str(agent) + "\n")
836         while True:
837                 line = sys.stdin.readline().strip(" \r\n")
838                 if line == "SELECTION?":
839                         #sys.stderr.write(sys.argv[0] + " : Make selection\n")
840                         [x,y] = agent.select() # Gets your agent's selection
841                         #sys.stderr.write(sys.argv[0] + " : Selection was " + str(agent.choice) + "\n")
842                         sys.stdout.write(str(x) + " " + str(y) + "\n")                          
843                 elif line == "MOVE?":
844                         #sys.stderr.write(sys.argv[0] + " : Make move\n")
845                         [x,y] = agent.get_move() # Gets your agent's move
846                         sys.stdout.write(str(x) + " " + str(y) + "\n")
847                 elif line.split(" ")[0] == "QUIT":
848                         #sys.stderr.write(sys.argv[0] + " : Quitting\n")
849                         agent.quit(" ".join(line.split(" ")[1:])) # Quits the game
850                         break
851                 elif line.split(" ")[0] == "BOARD":
852                         s = ""
853                         line = sys.stdin.readline().strip(" \r\n")
854                         while line != "END BOARD":
855                                 s += line + "\n"
856                                 line = sys.stdin.readline().strip(" \r\n")
857                         agent.board.reset_board(s)
858                         
859                 else:
860                         agent.update(line) # Updates agent.board
861         return 0
862
863
864 # Sort of works?
865
866 class ExternalWrapper(ExternalAgent):
867         def __init__(self, agent):
868                 run = "python -u -c \"import sys;import os;from qchess import *;agent = " + agent.__class__.__name__ + "('" + agent.name + "','"+agent.colour+"');sys.stdin.readline();sys.exit(run_agent(agent))\""
869                 # str(run)
870                 ExternalAgent.__init__(self, run, agent.colour)
871
872         
873
874 # --- player.py --- #
875 # A sample agent
876
877
878 class AgentBishop(AgentRandom): # Inherits from AgentRandom (in qchess)
879         def __init__(self, name, colour):
880                 InternalAgent.__init__(self, name, colour)
881                 self.value = {"pawn" : 1, "bishop" : 3, "knight" : 3, "rook" : 5, "queen" : 9, "king" : 100, "unknown" : 4}
882
883                 self.aggression = 2.0 # Multiplier for scoring due to aggressive actions
884                 self.defence = 1.0 # Multiplier for scoring due to defensive actions
885                 
886                 self.depth = 0 # Current depth
887                 self.max_depth = 2 # Recurse this many times (for some reason, makes more mistakes when this is increased???)
888                 self.recurse_for = -1 # Recurse for the best few moves each times (less than 0 = all moves)
889
890                 for p in self.board.pieces["white"] + self.board.pieces["black"]:
891                         p.last_moves = None
892                         p.selected_moves = None
893
894                 
895
896         def get_value(self, piece):
897                 if piece == None:
898                         return 0.0
899                 return float(self.value[piece.types[0]] + self.value[piece.types[1]]) / 2.0
900                 
901         # Score possible moves for the piece
902         
903         def prioritise_moves(self, piece):
904
905                 #sys.stderr.write(sys.argv[0] + " : " + str(self) + " prioritise called for " + str(piece) + "\n")
906
907                 
908                 
909                 grid = self.board.probability_grid(piece)
910                 #sys.stderr.write("\t Probability grid " + str(grid) + "\n")
911                 moves = []
912                 for x in range(w):
913                         for y in range(h):
914                                 if grid[x][y] < 0.3: # Throw out moves with < 30% probability
915                                         #sys.stderr.write("\tReject " + str(x) + "," + str(y) + " (" + str(grid[x][y]) + ")\n")
916                                         continue
917
918                                 target = self.board.grid[x][y]
919                         
920                                 
921                                 
922                                 
923                                 # Get total probability that the move is protected
924                                 self.board.push_move(piece, x, y)
925                                 
926
927                                 
928                                 defenders = self.board.coverage(x, y, piece.colour, reject_allied = False)
929                                 d_prob = 0.0
930                                 for d in defenders.keys():
931                                         d_prob += defenders[d]
932                                 if len(defenders.keys()) > 0:
933                                         d_prob /= float(len(defenders.keys()))
934
935                                 if (d_prob > 1.0):
936                                         d_prob = 1.0
937
938                                 # Get total probability that the move is threatened
939                                 attackers = self.board.coverage(x, y, opponent(piece.colour), reject_allied = False)
940                                 a_prob = 0.0
941                                 for a in attackers.keys():
942                                         a_prob += attackers[a]
943                                 if len(attackers.keys()) > 0:
944                                         a_prob /= float(len(attackers.keys()))
945
946                                 if (a_prob > 1.0):
947                                         a_prob = 1.0
948
949                                 self.board.pop_move()
950                                 
951
952                                 
953                                 # Score of the move
954                                 value = self.aggression * (1.0 + d_prob) * self.get_value(target) - self.defence * (1.0 - d_prob) * a_prob * self.get_value(piece)
955
956                                 # Adjust score based on movement of piece out of danger
957                                 attackers = self.board.coverage(piece.x, piece.y, opponent(piece.colour))
958                                 s_prob = 0.0
959                                 for a in attackers.keys():
960                                         s_prob += attackers[a]
961                                 if len(attackers.keys()) > 0:
962                                         s_prob /= float(len(attackers.keys()))
963
964                                 if (s_prob > 1.0):
965                                         s_prob = 1.0
966                                 value += self.defence * s_prob * self.get_value(piece)
967                                 
968                                 # Adjust score based on probability that the move is actually possible
969                                 moves.append([[x, y], grid[x][y] * value])
970
971                 moves.sort(key = lambda e : e[1], reverse = True)
972                 #sys.stderr.write(sys.argv[0] + ": Moves for " + str(piece) + " are " + str(moves) + "\n")
973
974                 piece.last_moves = moves
975                 piece.selected_moves = None
976
977                 
978
979                 
980                 return moves
981
982         def select_best(self, colour):
983
984                 self.depth += 1
985                 all_moves = {}
986                 for p in self.board.pieces[colour]:
987                         self.choice = p # Temporarily pick that piece
988                         m = self.prioritise_moves(p)
989                         if len(m) > 0:
990                                 all_moves.update({p : m[0]})
991
992                 if len(all_moves.items()) <= 0:
993                         return None
994                 
995                 
996                 opts = all_moves.items()
997                 opts.sort(key = lambda e : e[1][1], reverse = True)
998
999                 if self.depth >= self.max_depth:
1000                         self.depth -= 1
1001                         return list(opts[0])
1002
1003                 if self.recurse_for >= 0:
1004                         opts = opts[0:self.recurse_for]
1005                 #sys.stderr.write(sys.argv[0] + " : Before recurse, options are " + str(opts) + "\n")
1006
1007                 # Take the best few moves, and recurse
1008                 for choice in opts[0:self.recurse_for]:
1009                         [xx,yy] = [choice[0].x, choice[0].y] # Remember position
1010                         [nx,ny] = choice[1][0] # Target
1011                         [choice[0].x, choice[0].y] = [nx, ny] # Set position
1012                         target = self.board.grid[nx][ny] # Remember piece in spot
1013                         self.board.grid[xx][yy] = None # Remove piece
1014                         self.board.grid[nx][ny] = choice[0] # Replace with moving piece
1015                         
1016                         # Recurse
1017                         best_enemy_move = self.select_best(opponent(choice[0].colour))
1018                         choice[1][1] -= best_enemy_move[1][1] / float(self.depth + 1.0)
1019                         
1020                         [choice[0].x, choice[0].y] = [xx, yy] # Restore position
1021                         self.board.grid[nx][ny] = target # Restore taken piece
1022                         self.board.grid[xx][yy] = choice[0] # Restore moved piece
1023                         
1024                 
1025
1026                 opts.sort(key = lambda e : e[1][1], reverse = True)
1027                 #sys.stderr.write(sys.argv[0] + " : After recurse, options are " + str(opts) + "\n")
1028
1029                 self.depth -= 1
1030                 return list(opts[0])
1031
1032                 
1033
1034         # Returns [x,y] of selected piece
1035         def select(self):
1036                 #sys.stderr.write("Getting choice...")
1037                 self.choice = self.select_best(self.colour)[0]
1038                 
1039                 #sys.stderr.write(" Done " + str(self.choice)+"\n")
1040                 return [self.choice.x, self.choice.y]
1041         
1042         # Returns [x,y] of square to move selected piece into
1043         def get_move(self):
1044                 #sys.stderr.write("Choice is " + str(self.choice) + "\n")
1045                 self.choice.selected_moves = self.choice.last_moves
1046                 moves = self.prioritise_moves(self.choice)
1047                 if len(moves) > 0:
1048                         return moves[0][0]
1049                 else:
1050                         return AgentRandom.get_move(self)
1051
1052 # --- agent_bishop.py --- #
1053 import multiprocessing
1054
1055 # Hacky alternative to using select for timing out players
1056
1057 # WARNING: Do not wrap around HumanPlayer or things breakify
1058 # WARNING: Do not use in general or things breakify
1059
1060 class Sleeper(multiprocessing.Process):
1061         def __init__(self, timeout):
1062                 multiprocessing.Process.__init__(self)
1063                 self.timeout = timeout
1064
1065         def run(self):
1066                 time.sleep(self.timeout)
1067
1068
1069 class Worker(multiprocessing.Process):
1070         def __init__(self, function, args, q):
1071                 multiprocessing.Process.__init__(self)
1072                 self.function = function
1073                 self.args = args
1074                 self.q = q
1075
1076         def run(self):
1077                 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args) 
1078                 self.q.put(self.function(*self.args))
1079                 
1080                 
1081
1082 def TimeoutFunction(function, args, timeout):
1083         q = multiprocessing.Queue()
1084         w = Worker(function, args, q)
1085         s = Sleeper(timeout)
1086         w.start()
1087         s.start()
1088         while True: # Busy loop of crappyness
1089                 if not w.is_alive():
1090                         s.terminate()
1091                         result = q.get()
1092                         w.join()
1093                         #print "TimeoutFunction gets " + str(result)
1094                         return result
1095                 elif not s.is_alive():
1096                         w.terminate()
1097                         s.join()
1098                         raise Exception("TIMEOUT")
1099
1100         
1101                 
1102
1103 # A player that wraps another player and times out its moves
1104 # Uses threads
1105 # A (crappy) alternative to the use of select()
1106 class TimeoutPlayer(Player):
1107         def __init__(self, base_player, timeout):
1108                 Player.__init__(self, base_player.name, base_player.colour)
1109                 self.base_player = base_player
1110                 self.timeout = timeout
1111                 
1112         def select(self):
1113                 return TimeoutFunction(self.base_player.select, [], self.timeout)
1114                 
1115         
1116         def get_move(self):
1117                 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
1118
1119         def update(self, result):
1120                 return TimeoutFunction(self.base_player.update, [result], self.timeout)
1121
1122         def quit(self, final_result):
1123                 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
1124 # --- timeout_player.py --- #
1125 import socket
1126 import select
1127
1128 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
1129 network_timeout_delay = 1.0 # Maximum time between two characters being received
1130
1131 class Network():
1132         def __init__(self, colour, address = None):
1133                 self.socket = socket.socket()
1134                 #self.socket.setblocking(0)
1135
1136                 if colour == "white":
1137                         self.port = 4562
1138                 else:
1139                         self.port = 4563
1140
1141                 self.src = None
1142
1143         #       print str(self) + " listens on port " + str(self.port)
1144
1145                 if address == None:
1146                         self.host = socket.gethostname()
1147                         self.socket.bind((self.host, self.port))
1148                         self.socket.listen(5)   
1149
1150                         self.src, self.address = self.socket.accept()
1151                         self.src.send("ok\n")
1152                         if self.get_response() == "QUIT":
1153                                 self.src.close()
1154                 else:
1155                         self.host = address
1156                         self.socket.connect((address, self.port))
1157                         self.src = self.socket
1158                         self.src.send("ok\n")
1159                         if self.get_response() == "QUIT":
1160                                 self.src.close()
1161
1162         def get_response(self):
1163                 # Timeout the start of the message (first character)
1164                 if network_timeout_start > 0.0:
1165                         ready = select.select([self.src], [], [], network_timeout_start)[0]
1166                 else:
1167                         ready = [self.src]
1168                 if self.src in ready:
1169                         s = self.src.recv(1)
1170                 else:
1171                         raise Exception("UNRESPONSIVE")
1172
1173
1174                 while s[len(s)-1] != '\n':
1175                         # Timeout on each character in the message
1176                         if network_timeout_delay > 0.0:
1177                                 ready = select.select([self.src], [], [], network_timeout_delay)[0]
1178                         else:
1179                                 ready = [self.src]
1180                         if self.src in ready:
1181                                 s += self.src.recv(1) 
1182                         else:
1183                                 raise Exception("UNRESPONSIVE")
1184
1185                 return s.strip(" \r\n")
1186
1187         def send_message(self,s):
1188                 if network_timeout_start > 0.0:
1189                         ready = select.select([], [self.src], [], network_timeout_start)[1]
1190                 else:
1191                         ready = [self.src]
1192
1193                 if self.src in ready:
1194                         self.src.send(s + "\n")
1195                 else:
1196                         raise Exception("UNRESPONSIVE")
1197
1198         def check_quit(self, s):
1199                 s = s.split(" ")
1200                 if s[0] == "QUIT":
1201                         with game.lock:
1202                                 game.final_result = " ".join(s[1:]) + " " + str(opponent(self.colour))
1203                         game.stop()
1204                         return True
1205
1206                 
1207
1208 class NetworkSender(Player,Network):
1209         def __init__(self, base_player, address = None):
1210                 self.base_player = base_player
1211                 Player.__init__(self, base_player.name, base_player.colour)
1212
1213                 self.address = address
1214
1215         def connect(self):
1216                 Network.__init__(self, self.base_player.colour, self.address)
1217
1218
1219
1220         def select(self):
1221                 [x,y] = self.base_player.select()
1222                 choice = self.board.grid[x][y]
1223                 s = str(x) + " " + str(y)
1224                 #print str(self) + ".select sends " + s
1225                 self.send_message(s)
1226                 return [x,y]
1227
1228         def get_move(self):
1229                 [x,y] = self.base_player.get_move()
1230                 s = str(x) + " " + str(y)
1231                 #print str(self) + ".get_move sends " + s
1232                 self.send_message(s)
1233                 return [x,y]
1234
1235         def update(self, s):
1236                 self.base_player.update(s)
1237                 s = s.split(" ")
1238                 [x,y] = map(int, s[0:2])
1239                 selected = self.board.grid[x][y]
1240                 if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
1241                         s = " ".join(s[0:3])
1242                         for i in range(2):
1243                                 if selected.types_revealed[i] == True:
1244                                         s += " " + str(selected.types[i])
1245                                 else:
1246                                         s += " unknown"
1247                         #print str(self) + ".update sends " + s
1248                         self.send_message(s)
1249                                 
1250
1251         def quit(self, final_result):
1252                 self.base_player.quit(final_result)
1253                 #self.src.send("QUIT " + str(final_result) + "\n")
1254                 self.src.close()
1255
1256 class NetworkReceiver(Player,Network):
1257         def __init__(self, colour, address=None):
1258                 
1259                 Player.__init__(self, address, colour)
1260
1261                 self.address = address
1262
1263                 self.board = None
1264
1265         def connect(self):
1266                 Network.__init__(self, self.colour, self.address)
1267                         
1268
1269         def select(self):
1270                 
1271                 s = self.get_response()
1272                 #print str(self) + ".select gets " + s
1273                 [x,y] = map(int,s.split(" "))
1274                 if x == -1 and y == -1:
1275                         #print str(self) + ".select quits the game"
1276                         with game.lock:
1277                                 game.final_state = "network terminated " + self.colour
1278                         game.stop()
1279                 return [x,y]
1280         def get_move(self):
1281                 s = self.get_response()
1282                 #print str(self) + ".get_move gets " + s
1283                 [x,y] = map(int,s.split(" "))
1284                 if x == -1 and y == -1:
1285                         #print str(self) + ".get_move quits the game"
1286                         with game.lock:
1287                                 game.final_state = "network terminated " + self.colour
1288                         game.stop()
1289                 return [x,y]
1290
1291         def update(self, result):
1292                 
1293                 result = result.split(" ")
1294                 [x,y] = map(int, result[0:2])
1295                 selected = self.board.grid[x][y]
1296                 if selected != None and selected.colour == self.colour and len(result) > 2 and not "->" in result:
1297                         s = self.get_response()
1298                         #print str(self) + ".update - receives " + str(s)
1299                         s = s.split(" ")
1300                         selected.choice = int(s[2])
1301                         for i in range(2):
1302                                 selected.types[i] = str(s[3+i])
1303                                 if s[3+i] == "unknown":
1304                                         selected.types_revealed[i] = False
1305                                 else:
1306                                         selected.types_revealed[i] = True
1307                         selected.current_type = selected.types[selected.choice] 
1308                 else:
1309                         pass
1310                         #print str(self) + ".update - ignore result " + str(result)                     
1311                 
1312
1313         def quit(self, final_result):
1314                 self.src.close()
1315         
1316 # --- network.py --- #
1317 import threading
1318
1319 # A thread that can be stopped!
1320 # Except it can only be stopped if it checks self.stopped() periodically
1321 # So it can sort of be stopped
1322 class StoppableThread(threading.Thread):
1323         def __init__(self):
1324                 threading.Thread.__init__(self)
1325                 self._stop = threading.Event()
1326
1327         def stop(self):
1328                 self._stop.set()
1329
1330         def stopped(self):
1331                 return self._stop.isSet()
1332 # --- thread_util.py --- #
1333 log_files = []
1334 import datetime
1335 import urllib2
1336
1337 class LogFile():
1338         def __init__(self, log):        
1339                 
1340                 self.log = log
1341                 self.logged = []
1342                 self.log.write("# Log starts " + str(datetime.datetime.now()) + "\n")
1343
1344         def write(self, s):
1345                 now = datetime.datetime.now()
1346                 self.log.write(str(now) + " : " + s + "\n")
1347                 self.logged.append((now, s))
1348
1349         def setup(self, board, players):
1350                 
1351                 for p in players:
1352                         self.log.write("# " + p.colour + " : " + p.name + "\n")
1353                 
1354                 self.log.write("# Initial board\n")
1355                 for x in range(0, w):
1356                         for y in range(0, h):
1357                                 if board.grid[x][y] != None:
1358                                         self.log.write(str(board.grid[x][y]) + "\n")
1359
1360                 self.log.write("# Start game\n")
1361
1362         def close(self):
1363                 self.log.write("# EOF\n")
1364                 if self.log != sys.stdout:
1365                         self.log.close()
1366
1367 class ShortLog(LogFile):
1368         def __init__(self, file_name):
1369                 if file_name == "":
1370                         self.log = sys.stdout
1371                 else:
1372                         self.log = open(file_name, "w", 0)
1373                 LogFile.__init__(self, self.log)
1374                 self.file_name = file_name
1375                 self.phase = 0
1376
1377         def write(self, s):
1378                 now = datetime.datetime.now()
1379                 self.logged.append((now, s))
1380                 
1381                 if self.phase == 0:
1382                         if self.log != sys.stdout:
1383                                 self.log.close()
1384                                 self.log = open(self.file_name, "w", 0)
1385                         self.log.write("# Short log updated " + str(datetime.datetime.now()) + "\n")    
1386                         LogFile.setup(self, game.board, game.players)
1387
1388                 elif self.phase == 1:
1389                         for message in self.logged[len(self.logged)-2:]:
1390                                 self.log.write(str(message[0]) + " : " + message[1] + "\n")
1391
1392                 self.phase = (self.phase + 1) % 2               
1393                 
1394         def close(self):
1395                 if self.phase == 1:
1396                         ending = self.logged[len(self.logged)-1]
1397                         self.log.write(str(ending[0]) + " : " + ending[1] + "\n")
1398                 self.log.write("# EOF\n")
1399                 if self.log != sys.stdout:
1400                         self.log.close()
1401                 
1402
1403 class HeadRequest(urllib2.Request):
1404         def get_method(self):
1405                 return "HEAD"
1406
1407 class HttpGetter(StoppableThread):
1408         def __init__(self, address):
1409                 StoppableThread.__init__(self)
1410                 self.address = address
1411                 self.log = urllib2.urlopen(address)
1412                 self.lines = []
1413                 self.lock = threading.RLock() #lock for access of self.state
1414                 self.cond = threading.Condition() # conditional
1415
1416         def run(self):
1417                 while not self.stopped():
1418                         line = self.log.readline()
1419                         if line == "":
1420                                 date_mod = datetime.datetime.strptime(self.log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1421                                 self.log.close()
1422         
1423                                 next_log = urllib2.urlopen(HeadRequest(self.address))
1424                                 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1425                                 while date_new <= date_mod and not self.stopped():
1426                                         next_log = urllib2.urlopen(HeadRequest(self.address))
1427                                         date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1428                                 if self.stopped():
1429                                         break
1430
1431                                 self.log = urllib2.urlopen(self.address)
1432                                 line = self.log.readline()
1433
1434                         self.cond.acquire()
1435                         self.lines.append(line)
1436                         self.cond.notifyAll()
1437                         self.cond.release()
1438
1439                         #sys.stderr.write(" HttpGetter got \'" + str(line) + "\'\n")
1440
1441                 self.log.close()
1442                                 
1443                                 
1444         
1445                 
1446                 
1447 class HttpReplay():
1448         def __init__(self, address):
1449                 self.getter = HttpGetter(address)
1450                 self.getter.start()
1451                 
1452         def readline(self):
1453                 self.getter.cond.acquire()
1454                 while len(self.getter.lines) == 0:
1455                         self.getter.cond.wait()
1456                         
1457                 result = self.getter.lines[0]
1458                 self.getter.lines = self.getter.lines[1:]
1459                 self.getter.cond.release()
1460
1461                 return result
1462                         
1463                         
1464         def close(self):
1465                 self.getter.stop()
1466
1467 class FileReplay():
1468         def __init__(self, filename):
1469                 self.f = open(filename, "r", 0)
1470                 self.filename = filename
1471                 self.mod = os.path.getmtime(filename)
1472                 self.count = 0
1473         
1474         def readline(self):
1475                 line = self.f.readline()
1476                 
1477                 while line == "":
1478                         mod2 = os.path.getmtime(self.filename)
1479                         if mod2 > self.mod:
1480                                 #sys.stderr.write("File changed!\n")
1481                                 self.mod = mod2
1482                                 self.f.close()
1483                                 self.f = open(self.filename, "r", 0)
1484                                 
1485                                 new_line = self.f.readline()
1486                                 
1487                                 if " ".join(new_line.split(" ")[0:3]) != "# Short log":
1488                                         for i in range(self.count):
1489                                                 new_line = self.f.readline()
1490                                                 #sys.stderr.write("Read back " + str(i) + ": " + str(new_line) + "\n")
1491                                         new_line = self.f.readline()
1492                                 else:
1493                                         self.count = 0
1494                                 
1495                                 line = new_line
1496
1497                 self.count += 1
1498                 return line
1499
1500         def close(self):
1501                 self.f.close()
1502                 
1503                                                 
1504 def log(s):
1505         for l in log_files:
1506                 l.write(s)
1507                 
1508
1509 def log_init(board, players):
1510         for l in log_files:
1511                 l.setup(board, players)
1512
1513 # --- log.py --- #
1514
1515
1516
1517         
1518
1519 # A thread that runs the game
1520 class GameThread(StoppableThread):
1521         def __init__(self, board, players):
1522                 StoppableThread.__init__(self)
1523                 self.board = board
1524                 self.players = players
1525                 self.state = {"turn" : None} # The game state
1526                 self.error = 0 # Whether the thread exits with an error
1527                 self.lock = threading.RLock() #lock for access of self.state
1528                 self.cond = threading.Condition() # conditional for some reason, I forgot
1529                 self.final_result = ""
1530                 
1531                 
1532
1533         # Run the game (run in new thread with start(), run in current thread with run())
1534         def run(self):
1535                 result = ""
1536                 while not self.stopped():
1537                         
1538                         for p in self.players:
1539                                 with self.lock:
1540                                         if isinstance(p, NetworkSender):
1541                                                 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
1542                                         else:
1543                                                 self.state["turn"] = p
1544                                 #try:
1545                                 if True:
1546                                         [x,y] = p.select() # Player selects a square
1547                                         if self.stopped():
1548                                                 break
1549
1550                                         
1551                                                 
1552
1553                                         result = self.board.select(x, y, colour = p.colour)                             
1554                                         for p2 in self.players:
1555                                                 p2.update(result) # Inform players of what happened
1556
1557
1558                                         log(result)
1559
1560                                         target = self.board.grid[x][y]
1561                                         if isinstance(graphics, GraphicsThread):
1562                                                 with graphics.lock:
1563                                                         graphics.state["moves"] = self.board.possible_moves(target)
1564                                                         graphics.state["select"] = target
1565
1566                                         time.sleep(turn_delay)
1567
1568
1569                                         if len(self.board.possible_moves(target)) == 0:
1570                                                 #print "Piece cannot move"
1571                                                 target.deselect()
1572                                                 if isinstance(graphics, GraphicsThread):
1573                                                         with graphics.lock:
1574                                                                 graphics.state["moves"] = None
1575                                                                 graphics.state["select"] = None
1576                                                                 graphics.state["dest"] = None
1577                                                 continue
1578
1579                                         try:
1580                                                 [x2,y2] = p.get_move() # Player selects a destination
1581                                         except:
1582                                                 self.stop()
1583
1584                                         if self.stopped():
1585                                                 break
1586
1587                                         result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1588                                         log(result)
1589
1590                                         self.board.update_move(x, y, x2, y2)
1591                                         
1592                                         for p2 in self.players:
1593                                                 p2.update(result) # Inform players of what happened
1594
1595                                                                                 
1596
1597                                         if isinstance(graphics, GraphicsThread):
1598                                                 with graphics.lock:
1599                                                         graphics.state["moves"] = [[x2,y2]]
1600
1601                                         time.sleep(turn_delay)
1602
1603                                         if isinstance(graphics, GraphicsThread):
1604                                                 with graphics.lock:
1605                                                         graphics.state["select"] = None
1606                                                         graphics.state["dest"] = None
1607                                                         graphics.state["moves"] = None
1608
1609                         # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
1610                         #       except Exception,e:
1611                         #               result = e.message
1612                         #               #sys.stderr.write(result + "\n")
1613                         #               
1614                         #               self.stop()
1615                         #               with self.lock:
1616                         #                       self.final_result = self.state["turn"].colour + " " + e.message
1617
1618                                 end = self.board.end_condition()
1619                                 if end != None:         
1620                                         with self.lock:
1621                                                 if end == "DRAW":
1622                                                         self.final_result = self.state["turn"].colour + " " + end
1623                                                 else:
1624                                                         self.final_result = end
1625                                         self.stop()
1626                                 
1627                                 if self.stopped():
1628                                         break
1629
1630
1631                 for p2 in self.players:
1632                         p2.quit(self.final_result)
1633
1634                 log(self.final_result)
1635
1636                 if isinstance(graphics, GraphicsThread):
1637                         graphics.stop()
1638
1639         
1640 # A thread that replays a log file
1641 class ReplayThread(GameThread):
1642         def __init__(self, players, src, end=False,max_moves=None):
1643                 self.board = Board(style="empty")
1644                 self.board.max_moves = max_moves
1645                 GameThread.__init__(self, self.board, players)
1646                 self.src = src
1647                 self.end = end
1648
1649                 self.reset_board(self.src.readline())
1650
1651         def reset_board(self, line):
1652                 agent_str = ""
1653                 self_str = ""
1654                 while line != "# Start game" and line != "# EOF":
1655                         
1656                         while line == "":
1657                                 line = self.src.readline().strip(" \r\n")
1658                                 continue
1659
1660                         if line[0] == '#':
1661                                 line = self.src.readline().strip(" \r\n")
1662                                 continue
1663
1664                         self_str += line + "\n"
1665
1666                         if self.players[0].name == "dummy" and self.players[1].name == "dummy":
1667                                 line = self.src.readline().strip(" \r\n")
1668                                 continue
1669                         
1670                         tokens = line.split(" ")
1671                         types = map(lambda e : e.strip("[] ,'"), tokens[2:4])
1672                         for i in range(len(types)):
1673                                 if types[i][0] == "?":
1674                                         types[i] = "unknown"
1675
1676                         agent_str += tokens[0] + " " + tokens[1] + " " + str(types) + " ".join(tokens[4:]) + "\n"
1677                         line = self.src.readline().strip(" \r\n")
1678
1679                 for p in self.players:
1680                         p.reset_board(agent_str)
1681                 
1682                 
1683                 self.board.reset_board(self_str)
1684
1685         
1686         def run(self):
1687                 move_count = 0
1688                 last_line = ""
1689                 line = self.src.readline().strip(" \r\n")
1690                 while line != "# EOF":
1691
1692
1693                         if self.stopped():
1694                                 break
1695                         
1696                         if len(line) <= 0:
1697                                 continue
1698                                         
1699
1700                         if line[0] == '#':
1701                                 last_line = line
1702                                 line = self.src.readline().strip(" \r\n")
1703                                 continue
1704
1705                         tokens = line.split(" ")
1706                         if tokens[0] == "white" or tokens[0] == "black":
1707                                 self.reset_board(line)
1708                                 last_line = line
1709                                 line = self.src.readline().strip(" \r\n")
1710                                 continue
1711
1712                         move = line.split(":")
1713                         move = move[len(move)-1].strip(" \r\n")
1714                         tokens = move.split(" ")
1715                         
1716                         
1717                         try:
1718                                 [x,y] = map(int, tokens[0:2])
1719                         except:
1720                                 last_line = line
1721                                 self.stop()
1722                                 break
1723
1724                         log(move)
1725
1726                         target = self.board.grid[x][y]
1727                         with self.lock:
1728                                 if target.colour == "white":
1729                                         self.state["turn"] = self.players[0]
1730                                 else:
1731                                         self.state["turn"] = self.players[1]
1732                         
1733                         move_piece = (tokens[2] == "->")
1734                         if move_piece:
1735                                 [x2,y2] = map(int, tokens[len(tokens)-2:])
1736
1737                         if isinstance(graphics, GraphicsThread):
1738                                 with graphics.lock:
1739                                         graphics.state["select"] = target
1740                                         
1741                         if not move_piece:
1742                                 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
1743                                 if isinstance(graphics, GraphicsThread):
1744                                         with graphics.lock:
1745                                                 if target.current_type != "unknown":
1746                                                         graphics.state["moves"] = self.board.possible_moves(target)
1747                                                 else:
1748                                                         graphics.state["moves"] = None
1749                                         time.sleep(turn_delay)
1750                         else:
1751                                 self.board.update_move(x, y, x2, y2)
1752                                 if isinstance(graphics, GraphicsThread):
1753                                         with graphics.lock:
1754                                                 graphics.state["moves"] = [[x2,y2]]
1755                                         time.sleep(turn_delay)
1756                                         with graphics.lock:
1757                                                 graphics.state["select"] = None
1758                                                 graphics.state["moves"] = None
1759                                                 graphics.state["dest"] = None
1760                         
1761
1762                         
1763                         
1764                         
1765                         for p in self.players:
1766                                 p.update(move)
1767
1768                         last_line = line
1769                         line = self.src.readline().strip(" \r\n")
1770                         
1771                         
1772                         end = self.board.end_condition()
1773                         if end != None:
1774                                 self.final_result = end
1775                                 self.stop()
1776                                 break
1777                                         
1778                                                 
1779                                                 
1780
1781                         
1782                                         
1783
1784
1785                         
1786
1787                                 
1788                         
1789
1790                 
1791
1792                 if self.end and isinstance(graphics, GraphicsThread):
1793                         #graphics.stop()
1794                         pass # Let the user stop the display
1795                 elif not self.end and self.board.end_condition() == None:
1796                         global game
1797                         # Work out the last move
1798                                         
1799                         t = last_line.split(" ")
1800                         if t[len(t)-2] == "black":
1801                                 self.players.reverse()
1802                         elif t[len(t)-2] == "white":
1803                                 pass
1804                         elif self.state["turn"] != None and self.state["turn"].colour == "white":
1805                                 self.players.reverse()
1806
1807
1808                         game = GameThread(self.board, self.players)
1809                         game.run()
1810                 else:
1811                         pass
1812
1813                 
1814
1815 def opponent(colour):
1816         if colour == "white":
1817                 return "black"
1818         else:
1819                 return "white"
1820 # --- game.py --- #
1821 try:
1822         import pygame
1823 except:
1824         pass
1825 import os
1826
1827 # Dictionary that stores the unicode character representations of the different pieces
1828 # Chess was clearly the reason why unicode was invented
1829 # For some reason none of the pygame chess implementations I found used them!
1830 piece_char = {"white" : {"king" : u'\u2654',
1831                          "queen" : u'\u2655',
1832                          "rook" : u'\u2656',
1833                          "bishop" : u'\u2657',
1834                          "knight" : u'\u2658',
1835                          "pawn" : u'\u2659',
1836                          "unknown" : '?'},
1837                 "black" : {"king" : u'\u265A',
1838                          "queen" : u'\u265B',
1839                          "rook" : u'\u265C',
1840                          "bishop" : u'\u265D',
1841                          "knight" : u'\u265E',
1842                          "pawn" : u'\u265F',
1843                          "unknown" : '?'}}
1844
1845 images = {"white" : {}, "black" : {}}
1846 small_images = {"white" : {}, "black" : {}}
1847
1848 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
1849
1850         # Get the font sizes
1851         l_size = 5*(grid_sz[0] / 8)
1852         s_size = 3*(grid_sz[0] / 8)
1853
1854         for c in piece_char.keys():
1855                 
1856                 if c == "black":
1857                         for p in piece_char[c].keys():
1858                                 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
1859                                 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})         
1860                 elif c == "white":
1861                         for p in piece_char[c].keys():
1862                                 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1863                                 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1864                                 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1865                                 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1866         
1867
1868 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
1869         if not os.path.exists(image_dir):
1870                 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
1871         for c in piece_char.keys():
1872                 for p in piece_char[c].keys():
1873                         images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
1874                         small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
1875 # --- images.py --- #
1876 graphics_enabled = True
1877 try:
1878         import pygame
1879 except:
1880         graphics_enabled = False
1881         
1882 import time
1883
1884
1885
1886 # A thread to make things pretty
1887 class GraphicsThread(StoppableThread):
1888         def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1889                 StoppableThread.__init__(self)
1890                 
1891                 self.board = board
1892                 pygame.init()
1893                 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1894                 pygame.display.set_caption(title)
1895
1896                 #print "Initialised properly"
1897                 
1898                 self.grid_sz = grid_sz[:]
1899                 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
1900                 self.error = 0
1901                 self.lock = threading.RLock()
1902                 self.cond = threading.Condition()
1903                 self.sleep_timeout = None
1904                 self.last_event = time.time()
1905
1906                 #print "Test font"
1907                 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
1908
1909                 #load_images()
1910                 load_images()
1911
1912                 """
1913                 for c in images.keys():
1914                         for p in images[c].keys():
1915                                 images[c][p] = images[c][p].convert(self.window)
1916                                 small_images[c][p] = small_images[c][p].convert(self.window)
1917                 """
1918
1919                 
1920         
1921
1922
1923         # On the run from the world
1924         def run(self):
1925                 
1926                 while not self.stopped():
1927                         
1928                         if self.sleep_timeout == None or (time.time() - self.last_event) < self.sleep_timeout:
1929                         
1930                                 #print "Display grid"
1931                                 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
1932
1933                                 #print "Display overlay"
1934                                 self.overlay()
1935
1936                                 #print "Display pieces"
1937                                 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board                
1938                                 
1939                         else:
1940                                 self.window.fill((0,0,0))
1941
1942                         pygame.display.flip()
1943
1944                         for event in pygame.event.get():
1945                                 self.last_event = time.time()
1946                                 if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_q):
1947                                         if isinstance(game, GameThread):
1948                                                 with game.lock:
1949                                                         game.final_result = ""
1950                                                         if game.state["turn"] != None:
1951                                                                 game.final_result = game.state["turn"].colour + " "
1952                                                         game.final_result += "terminated"
1953                                                 game.stop()
1954                                         self.stop()
1955                                         break
1956                                 elif event.type == pygame.MOUSEBUTTONDOWN:
1957                                         self.mouse_down(event)
1958                                         
1959                                 elif event.type == pygame.MOUSEBUTTONUP:
1960                                         self.mouse_up(event)                    
1961                                 
1962                                 
1963                                         
1964
1965                                 
1966                                                                 
1967                                                 
1968                                                 
1969                 self.message("Game ends, result \""+str(game.final_result) + "\"")
1970                 time.sleep(1)
1971
1972                 # Wake up anyone who is sleeping
1973                 self.cond.acquire()
1974                 self.cond.notify()
1975                 self.cond.release()
1976
1977                 pygame.quit() # Time to say goodbye
1978
1979         # Mouse release event handler
1980         def mouse_up(self, event):
1981                 if event.button == 3:
1982                         with self.lock:
1983                                 self.state["overlay"] = None
1984                 elif event.button == 2:
1985                         with self.lock:
1986                                 self.state["coverage"] = None   
1987
1988         # Mouse click event handler
1989         def mouse_down(self, event):
1990                 if event.button == 1:
1991                         m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
1992                         if isinstance(game, GameThread):
1993                                 with game.lock:
1994                                         p = game.state["turn"]
1995                         else:
1996                                         p = None
1997                                         
1998                                         
1999                         if isinstance(p, HumanPlayer):
2000                                 with self.lock:
2001                                         s = self.board.grid[m[0]][m[1]]
2002                                         select = self.state["select"]
2003                                 if select == None:
2004                                         if s != None and s.colour != p.colour:
2005                                                 self.message("Wrong colour") # Look at all this user friendliness!
2006                                                 time.sleep(1)
2007                                                 return
2008                                         # Notify human player of move
2009                                         self.cond.acquire()
2010                                         with self.lock:
2011                                                 self.state["select"] = s
2012                                                 self.state["dest"] = None
2013                                         self.cond.notify()
2014                                         self.cond.release()
2015                                         return
2016
2017                                 if select == None:
2018                                         return
2019                                                 
2020                                         
2021                                 if self.state["moves"] == None:
2022                                         return
2023
2024                                 if not m in self.state["moves"]:
2025                                         self.message("Illegal Move") # I still think last year's mouse interface was adequate
2026                                         time.sleep(2)
2027                                         return
2028                                                 
2029                                 with self.lock:
2030                                         if self.state["dest"] == None:
2031                                                 self.cond.acquire()
2032                                                 self.state["dest"] = m
2033                                                 self.state["select"] = None
2034                                                 self.state["moves"] = None
2035                                                 self.cond.notify()
2036                                                 self.cond.release()
2037                 elif event.button == 3:
2038                         m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2039                         if isinstance(game, GameThread):
2040                                 with game.lock:
2041                                         p = game.state["turn"]
2042                         else:
2043                                 p = None
2044                                         
2045                                         
2046                         if isinstance(p, HumanPlayer):
2047                                 with self.lock:
2048                                         self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
2049
2050                 elif event.button == 2:
2051                         m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2052                         if isinstance(game, GameThread):
2053                                 with game.lock:
2054                                         p = game.state["turn"]
2055                         else:
2056                                 p = None
2057                         
2058                         
2059                         if isinstance(p, HumanPlayer):
2060                                 with self.lock:
2061                                         self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
2062                                 
2063         # Draw the overlay
2064         def overlay(self):
2065
2066                 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
2067                 # Draw square over the selected piece
2068                 with self.lock:
2069                         select = self.state["select"]
2070                 if select != None:
2071                         mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
2072                         square_img.fill(pygame.Color(0,255,0,64))
2073                         self.window.blit(square_img, mp)
2074                 # If a piece is selected, draw all reachable squares
2075                 # (This quality user interface has been patented)
2076                 with self.lock:
2077                         m = self.state["moves"]
2078                 if m != None:
2079                         square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
2080                         for move in m:
2081                                 mp = [self.grid_sz[i] * move[i] for i in range(2)]
2082                                 self.window.blit(square_img, mp)
2083                 # If a piece is overlayed, show all squares that it has a probability to reach
2084                 with self.lock:
2085                         m = self.state["overlay"]
2086                 if m != None:
2087                         for x in range(w):
2088                                 for y in range(h):
2089                                         if m[x][y] > 0.0:
2090                                                 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
2091                                                 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
2092                                                 self.window.blit(square_img, mp)
2093                                                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2094                                                 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
2095                                                 self.window.blit(text, mp)
2096                                 
2097                 # If a square is selected, highlight all pieces that have a probability to reach it
2098                 with self.lock:                         
2099                         m = self.state["coverage"]
2100                 if m != None:
2101                         for p in m:
2102                                 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
2103                                 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
2104                                 self.window.blit(square_img, mp)
2105                                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2106                                 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
2107                                 self.window.blit(text, mp)
2108                         # Draw a square where the mouse is
2109                 # This also serves to indicate who's turn it is
2110                 
2111                 if isinstance(game, GameThread):
2112                         with game.lock:
2113                                 turn = game.state["turn"]
2114                 else:
2115                         turn = None
2116
2117                 if isinstance(turn, HumanPlayer):
2118                         mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
2119                         square_img.fill(pygame.Color(0,0,255,128))
2120                         if turn.colour == "white":
2121                                 c = pygame.Color(255,255,255)
2122                         else:
2123                                 c = pygame.Color(0,0,0)
2124                         pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
2125                         self.window.blit(square_img, mp)
2126
2127         # Message in a bottle
2128         def message(self, string, pos = None, colour = None, font_size = 20):
2129                 #print "Drawing message..."
2130                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2131                 if colour == None:
2132                         colour = pygame.Color(0,0,0)
2133                 
2134                 text = font.render(string, 1, colour)
2135         
2136
2137                 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
2138                 s.fill(pygame.Color(128,128,128))
2139
2140                 tmp = self.window.get_size()
2141
2142                 if pos == None:
2143                         pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
2144                 else:
2145                         pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
2146                 
2147
2148                 rect = (pos[0], pos[1], text.get_width(), text.get_height())
2149         
2150                 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
2151                 self.window.blit(s, pos)
2152                 self.window.blit(text, pos)
2153
2154                 pygame.display.flip()
2155
2156         def getstr(self, prompt = None):
2157                 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
2158                 s.blit(self.window, (0,0))
2159                 result = ""
2160
2161                 while True:
2162                         #print "LOOP"
2163                         if prompt != None:
2164                                 self.message(prompt)
2165                                 self.message(result, pos = (0, 1))
2166         
2167                         pygame.event.pump()
2168                         for event in pygame.event.get():
2169                                 if event.type == pygame.QUIT:
2170                                         return None
2171                                 if event.type == pygame.KEYDOWN:
2172                                         if event.key == pygame.K_BACKSPACE:
2173                                                 result = result[0:len(result)-1]
2174                                                 self.window.blit(s, (0,0)) # Revert the display
2175                                                 continue
2176                                 
2177                                                 
2178                                         try:
2179                                                 if event.unicode == '\r':
2180                                                         return result
2181                                         
2182                                                 result += str(event.unicode)
2183                                         except:
2184                                                 continue
2185
2186
2187         # Function to pick a button
2188         def SelectButton(self, choices, prompt = None, font_size=20):
2189
2190                 #print "Select button called!"
2191                 self.board.display_grid(self.window, self.grid_sz)
2192                 if prompt != None:
2193                         self.message(prompt)
2194                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2195                 targets = []
2196                 sz = self.window.get_size()
2197
2198                 
2199                 for i in range(len(choices)):
2200                         c = choices[i]
2201                         
2202                         text = font.render(c, 1, pygame.Color(0,0,0))
2203                         p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
2204                         targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
2205
2206                 while True:
2207                         mp =pygame.mouse.get_pos()
2208                         for i in range(len(choices)):
2209                                 c = choices[i]
2210                                 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
2211                                         font_colour = pygame.Color(255,0,0)
2212                                         box_colour = pygame.Color(0,0,255,128)
2213                                 else:
2214                                         font_colour = pygame.Color(0,0,0)
2215                                         box_colour = pygame.Color(128,128,128)
2216                                 
2217                                 text = font.render(c, 1, font_colour)
2218                                 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
2219                                 s.fill(box_colour)
2220                                 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
2221                                 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
2222                                 self.window.blit(s, targets[i][0:2])
2223                                 
2224         
2225                         pygame.display.flip()
2226
2227                         for event in pygame.event.get():
2228                                 if event.type == pygame.QUIT:
2229                                         return None
2230                                 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
2231                                         for i in range(len(targets)):
2232                                                 t = targets[i]
2233                                                 if event.pos[0] > t[0] and event.pos[0] < t[2]:
2234                                                         if event.pos[1] > t[1] and event.pos[1] < t[3]:
2235                                                                 return i
2236                                                 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
2237                 
2238
2239         # Function to pick players in a nice GUI way
2240         def SelectPlayers(self, players = []):
2241
2242
2243                 #print "SelectPlayers called"
2244                 
2245                 missing = ["white", "black"]
2246                 for p in players:
2247                         missing.remove(p.colour)
2248
2249                 for colour in missing:
2250                         
2251                         
2252                         choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
2253                         if choice == 0:
2254                                 players.append(HumanPlayer("human", colour))
2255                         elif choice == 1:
2256                                 import inspect
2257                                 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2258                                 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2259                                 internal_agents.remove(('InternalAgent', InternalAgent)) 
2260                                 if len(internal_agents) > 0:
2261                                         choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
2262                                 else:
2263                                         choice2 = 1
2264
2265                                 if choice2 == 0:
2266                                         agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
2267                                         players.append(agent[1](agent[0], colour))                                      
2268                                 elif choice2 == 1:
2269                                         try:
2270                                                 import Tkinter
2271                                                 from tkFileDialog import askopenfilename
2272                                                 root = Tkinter.Tk() # Need a root to make Tkinter behave
2273                                                 root.withdraw() # Some sort of magic incantation
2274                                                 path = askopenfilename(parent=root, initialdir="../agents",title=
2275 'Choose an agent.')
2276                                                 if path == "":
2277                                                         return self.SelectPlayers()
2278                                                 players.append(make_player(path, colour))       
2279                                         except:
2280                                                 
2281                                                 p = None
2282                                                 while p == None:
2283                                                         self.board.display_grid(self.window, self.grid_sz)
2284                                                         pygame.display.flip()
2285                                                         path = self.getstr(prompt = "Enter path:")
2286                                                         if path == None:
2287                                                                 return None
2288         
2289                                                         if path == "":
2290                                                                 return self.SelectPlayers()
2291         
2292                                                         try:
2293                                                                 p = make_player(path, colour)
2294                                                         except:
2295                                                                 self.board.display_grid(self.window, self.grid_sz)
2296                                                                 pygame.display.flip()
2297                                                                 self.message("Invalid path!")
2298                                                                 time.sleep(1)
2299                                                                 p = None
2300                                                 players.append(p)
2301                         elif choice == 2:
2302                                 address = ""
2303                                 while address == "":
2304                                         self.board.display_grid(self.window, self.grid_sz)
2305                                         
2306                                         address = self.getstr(prompt = "Address? (leave blank for server)")
2307                                         if address == None:
2308                                                 return None
2309                                         if address == "":
2310                                                 address = None
2311                                                 continue
2312                                         try:
2313                                                 map(int, address.split("."))
2314                                         except:
2315                                                 self.board.display_grid(self.window, self.grid_sz)
2316                                                 self.message("Invalid IPv4 address!")
2317                                                 address = ""
2318
2319                                 players.append(NetworkReceiver(colour, address))
2320                         else:
2321                                 return None
2322                 #print str(self) + ".SelectPlayers returns " + str(players)
2323                 return players
2324                         
2325                                 
2326                         
2327 # --- graphics.py --- #
2328 #!/usr/bin/python -u
2329
2330 # Do you know what the -u does? It unbuffers stdin and stdout
2331 # I can't remember why, but last year things broke without that
2332
2333 """
2334         UCC::Progcomp 2013 Quantum Chess game
2335         @author Sam Moore [SZM] "matches"
2336         @copyright The University Computer Club, Incorporated
2337                 (ie: You can copy it for not for profit purposes)
2338 """
2339
2340 # system python modules or whatever they are called
2341 import sys
2342 import os
2343 import time
2344
2345 turn_delay = 0.5
2346 sleep_timeout = None
2347 [game, graphics] = [None, None]
2348
2349 def make_player(name, colour):
2350         if name[0] == '@':
2351                 if name[1:] == "human":
2352                         return HumanPlayer(name, colour)
2353                 s = name[1:].split(":")
2354                 if s[0] == "network":
2355                         address = None
2356                         if len(s) > 1:
2357                                 address = s[1]
2358                         return NetworkReceiver(colour, address)
2359                 if s[0] == "internal":
2360
2361                         import inspect
2362                         internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2363                         internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2364                         internal_agents.remove(('InternalAgent', InternalAgent)) 
2365                         
2366                         if len(s) != 2:
2367                                 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
2368                                 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2369                                 return None
2370
2371                         for a in internal_agents:
2372                                 if s[1] == a[0]:
2373                                         return a[1](name, colour)
2374                         
2375                         sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
2376                         sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2377                         return None
2378                         
2379
2380         else:
2381                 return ExternalAgent(name, colour)
2382                         
2383
2384
2385 # The main function! It does the main stuff!
2386 def main(argv):
2387
2388         # Apparently python will silently treat things as local unless you do this
2389         # Anyone who says "You should never use a global variable" can die in a fire
2390         global game
2391         global graphics
2392         
2393         global turn_delay
2394         global agent_timeout
2395         global log_files
2396         global src_file
2397         global graphics_enabled
2398         global always_reveal_states
2399         global sleep_timeout
2400
2401         max_moves = None
2402         src_file = None
2403         
2404         style = "quantum"
2405         colour = "white"
2406
2407         # Get the important warnings out of the way
2408         if platform.system() == "Windows":
2409                 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
2410                 if platform.release() == "Vista":
2411                         sys.stderr.write(sys.argv[0] + " : God help you.\n")
2412         
2413
2414         players = []
2415         i = 0
2416         while i < len(argv)-1:
2417                 i += 1
2418                 arg = argv[i]
2419                 if arg[0] != '-':
2420                         p = make_player(arg, colour)
2421                         if not isinstance(p, Player):
2422                                 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
2423                                 return 100
2424                         players.append(p)
2425                         if colour == "white":
2426                                 colour = "black"
2427                         elif colour == "black":
2428                                 pass
2429                         else:
2430                                 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
2431                         continue
2432
2433                 # Option parsing goes here
2434                 if arg[1] == '-' and arg[2:] == "classical":
2435                         style = "classical"
2436                 elif arg[1] == '-' and arg[2:] == "quantum":
2437                         style = "quantum"
2438                 elif arg[1] == '-' and arg[2:] == "reveal":
2439                         always_reveal_states = True
2440                 elif (arg[1] == '-' and arg[2:] == "graphics"):
2441                         graphics_enabled = True
2442                 elif (arg[1] == '-' and arg[2:] == "no-graphics"):
2443                         graphics_enabled = False
2444                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
2445                         # Load game from file
2446                         if len(arg[2:].split("=")) == 1:
2447                                 src_file = sys.stdin
2448                         else:
2449                                 f = arg[2:].split("=")[1]
2450                                 if f[0:7] == "http://":
2451                                         src_file = HttpReplay(f)
2452                                 else:
2453                                         src_file = FileReplay(f.split(":")[0])
2454
2455                                         if len(f.split(":")) == 2:
2456                                                 max_moves = int(f.split(":")[1])
2457
2458                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
2459                         # Log file
2460                         if len(arg[2:].split("=")) == 1:
2461                                 log_files.append(LogFile(sys.stdout))
2462                         else:
2463                                 f = arg[2:].split("=")[1]
2464                                 if f[0] == '@':
2465                                         log_files.append(ShortLog(f[1:]))
2466                                 else:
2467                                         log_files.append(LogFile(open(f, "w", 0)))
2468                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
2469                         # Delay
2470                         if len(arg[2:].split("=")) == 1:
2471                                 turn_delay = 0
2472                         else:
2473                                 turn_delay = float(arg[2:].split("=")[1])
2474
2475                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
2476                         # Timeout
2477                         if len(arg[2:].split("=")) == 1:
2478                                 agent_timeout = -1
2479                         else:
2480                                 agent_timeout = float(arg[2:].split("=")[1])
2481                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "blackout"):
2482                         # Screen saver delay
2483                         if len(arg[2:].split("=")) == 1:
2484                                 sleep_timeout = -1
2485                         else:
2486                                 sleep_timeout = float(arg[2:].split("=")[1])
2487                                 
2488                 elif (arg[1] == '-' and arg[2:] == "help"):
2489                         # Help
2490                         os.system("less data/help.txt") # The best help function
2491                         return 0
2492
2493
2494         # Create the board
2495         
2496         # Construct a GameThread! Make it global! Damn the consequences!
2497                         
2498         if src_file != None:
2499                 # Hack to stop ReplayThread from exiting
2500                 #if len(players) == 0:
2501                 #       players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
2502
2503                 # Normally the ReplayThread exits if there are no players
2504                 # TODO: Decide which behaviour to use, and fix it
2505                 end = (len(players) == 0)
2506                 if end:
2507                         players = [Player("dummy", "white"), Player("dummy", "black")]
2508                 elif len(players) != 2:
2509                         sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2510                         if graphics_enabled:
2511                                 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
2512                         return 44
2513                 game = ReplayThread(players, src_file, end=end, max_moves=max_moves)
2514         else:
2515                 board = Board(style)
2516                 board.max_moves = max_moves
2517                 game = GameThread(board, players) 
2518
2519
2520
2521
2522         # Initialise GUI
2523         if graphics_enabled == True:
2524                 try:
2525                         graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
2526                         
2527                         graphics.sleep_timeout = sleep_timeout
2528
2529                 except Exception,e:
2530                         graphics = None
2531                         sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
2532                         graphics_enabled = False
2533
2534         # If there are no players listed, display a nice pretty menu
2535         if len(players) != 2:
2536                 if graphics != None:
2537                         players = graphics.SelectPlayers(players)
2538                 else:
2539                         sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2540                         return 44
2541
2542         # If there are still no players, quit
2543         if players == None or len(players) != 2:
2544                 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
2545                 return 45
2546
2547
2548         # Wrap NetworkSender players around original players if necessary
2549         for i in range(len(players)):
2550                 if isinstance(players[i], NetworkReceiver):
2551                         players[i].board = board # Network players need direct access to the board
2552                         for j in range(len(players)):
2553                                 if j == i:
2554                                         continue
2555                                 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
2556                                         continue
2557                                 players[j] = NetworkSender(players[j], players[i].address)
2558                                 players[j].board = board
2559
2560         # Connect the networked players
2561         for p in players:
2562                 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
2563                         if graphics != None:
2564                                 graphics.board.display_grid(graphics.window, graphics.grid_sz)
2565                                 graphics.message("Connecting to " + p.colour + " player...")
2566                         p.connect()
2567
2568         
2569         # If using windows, select won't work; use horrible TimeoutPlayer hack
2570         if agent_timeout > 0:
2571                 if platform.system() == "Windows":
2572                         for i in range(len(players)):
2573                                 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
2574                                         players[i] = TimeoutPlayer(players[i], agent_timeout)
2575
2576                 else:
2577                         warned = False
2578                         # InternalAgents get wrapped to an ExternalAgent when there is a timeout
2579                         # This is not confusing at all.
2580                         for i in range(len(players)):
2581                                 if isinstance(players[i], InternalAgent):
2582                                                 players[i] = ExternalWrapper(players[i])
2583
2584
2585                 
2586
2587
2588
2589
2590         log_init(game.board, players)
2591         
2592         
2593         if graphics != None:
2594                 game.start() # This runs in a new thread
2595                 graphics.run()
2596                 if game.is_alive():
2597                         game.join()
2598         
2599
2600                 error = game.error + graphics.error
2601         else:
2602                 game.run()
2603                 error = game.error
2604         
2605
2606         for l in log_files:
2607                 l.close()
2608
2609         if src_file != None and src_file != sys.stdin:
2610                 src_file.close()
2611
2612         sys.stdout.write(game.final_result + "\n")
2613
2614         return error
2615
2616 # This is how python does a main() function...
2617 if __name__ == "__main__":
2618         try:
2619                 sys.exit(main(sys.argv))
2620         except KeyboardInterrupt:
2621                 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
2622                 if isinstance(graphics, StoppableThread):
2623                         graphics.stop()
2624                         graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
2625
2626                 if isinstance(game, StoppableThread):
2627                         game.stop()
2628                         if game.is_alive():
2629                                 game.join()
2630
2631                 sys.exit(102)
2632
2633 # --- main.py --- #
2634 # EOF - created from make on Thu Mar 21 12:27:36 WST 2013

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