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