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

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