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

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