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

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