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

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