Messing with log files
[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":
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 def log(s):
1405         for l in log_files:
1406                 l.write(s)
1407                 
1408
1409 def log_init(board, players):
1410         for l in log_files:
1411                 l.setup(board, players)
1412
1413 # --- log.py --- #
1414
1415
1416
1417         
1418
1419 # A thread that runs the game
1420 class GameThread(StoppableThread):
1421         def __init__(self, board, players):
1422                 StoppableThread.__init__(self)
1423                 self.board = board
1424                 self.players = players
1425                 self.state = {"turn" : None} # The game state
1426                 self.error = 0 # Whether the thread exits with an error
1427                 self.lock = threading.RLock() #lock for access of self.state
1428                 self.cond = threading.Condition() # conditional for some reason, I forgot
1429                 self.final_result = ""
1430                 
1431                 
1432
1433         # Run the game (run in new thread with start(), run in current thread with run())
1434         def run(self):
1435                 result = ""
1436                 while not self.stopped():
1437                         
1438                         for p in self.players:
1439                                 with self.lock:
1440                                         if isinstance(p, NetworkSender):
1441                                                 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
1442                                         else:
1443                                                 self.state["turn"] = p
1444                                 #try:
1445                                 if True:
1446                                         [x,y] = p.select() # Player selects a square
1447                                         if self.stopped():
1448                                                 break
1449
1450                                         
1451                                                 
1452
1453                                         result = self.board.select(x, y, colour = p.colour)                             
1454                                         for p2 in self.players:
1455                                                 p2.update(result) # Inform players of what happened
1456
1457
1458                                         log(result)
1459
1460                                         target = self.board.grid[x][y]
1461                                         if isinstance(graphics, GraphicsThread):
1462                                                 with graphics.lock:
1463                                                         graphics.state["moves"] = self.board.possible_moves(target)
1464                                                         graphics.state["select"] = target
1465
1466                                         time.sleep(turn_delay)
1467
1468
1469                                         if len(self.board.possible_moves(target)) == 0:
1470                                                 #print "Piece cannot move"
1471                                                 target.deselect()
1472                                                 if isinstance(graphics, GraphicsThread):
1473                                                         with graphics.lock:
1474                                                                 graphics.state["moves"] = None
1475                                                                 graphics.state["select"] = None
1476                                                                 graphics.state["dest"] = None
1477                                                 continue
1478
1479                                         try:
1480                                                 [x2,y2] = p.get_move() # Player selects a destination
1481                                         except:
1482                                                 self.stop()
1483
1484                                         if self.stopped():
1485                                                 break
1486
1487                                         result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1488                                         log(result)
1489
1490                                         self.board.update_move(x, y, x2, y2)
1491                                         
1492                                         for p2 in self.players:
1493                                                 p2.update(result) # Inform players of what happened
1494
1495                                                                                 
1496
1497                                         if isinstance(graphics, GraphicsThread):
1498                                                 with graphics.lock:
1499                                                         graphics.state["moves"] = [[x2,y2]]
1500
1501                                         time.sleep(turn_delay)
1502
1503                                         if isinstance(graphics, GraphicsThread):
1504                                                 with graphics.lock:
1505                                                         graphics.state["select"] = None
1506                                                         graphics.state["dest"] = None
1507                                                         graphics.state["moves"] = None
1508
1509                         # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
1510                         #       except Exception,e:
1511                         #               result = e.message
1512                         #               #sys.stderr.write(result + "\n")
1513                         #               
1514                         #               self.stop()
1515                         #               with self.lock:
1516                         #                       self.final_result = self.state["turn"].colour + " " + e.message
1517
1518                                 end = self.board.end_condition()
1519                                 if end != None:         
1520                                         with self.lock:
1521                                                 if end == "DRAW":
1522                                                         self.final_result = self.state["turn"].colour + " " + end
1523                                                 else:
1524                                                         self.final_result = end
1525                                         self.stop()
1526                                 
1527                                 if self.stopped():
1528                                         break
1529
1530
1531                 for p2 in self.players:
1532                         p2.quit(self.final_result)
1533
1534                 log(self.final_result)
1535
1536                 if isinstance(graphics, GraphicsThread):
1537                         graphics.stop()
1538
1539         
1540 # A thread that replays a log file
1541 class ReplayThread(GameThread):
1542         def __init__(self, players, src, end=False,max_moves=None):
1543                 self.board = Board(style="empty")
1544                 self.board.max_moves = max_moves
1545                 GameThread.__init__(self, self.board, players)
1546                 self.src = src
1547                 self.end = end
1548
1549                 self.reset_board(self.src.readline())
1550
1551         def reset_board(self, line):
1552                 agent_str = ""
1553                 self_str = ""
1554                 while line != "# Start game" and line != "# EOF":
1555                         
1556                         while line == "":
1557                                 line = self.src.readline().strip(" \r\n")
1558                                 continue
1559
1560                         if line[0] == '#':
1561                                 line = self.src.readline().strip(" \r\n")
1562                                 continue
1563
1564                         self_str += line + "\n"
1565
1566                         if self.players[0].name == "dummy" and self.players[1].name == "dummy":
1567                                 line = self.src.readline().strip(" \r\n")
1568                                 continue
1569                         
1570                         tokens = line.split(" ")
1571                         types = map(lambda e : e.strip("[] ,'"), tokens[2:4])
1572                         for i in range(len(types)):
1573                                 if types[i][0] == "?":
1574                                         types[i] = "unknown"
1575
1576                         agent_str += tokens[0] + " " + tokens[1] + " " + str(types) + " ".join(tokens[4:]) + "\n"
1577                         line = self.src.readline().strip(" \r\n")
1578
1579                 for p in self.players:
1580                         p.reset_board(agent_str)
1581                 
1582                 
1583                 self.board.reset_board(self_str)
1584
1585         
1586         def run(self):
1587                 move_count = 0
1588                 last_line = ""
1589                 line = self.src.readline().strip(" \r\n")
1590                 while line != "# EOF":
1591
1592
1593                         if self.stopped():
1594                                 break
1595                         
1596                                         
1597
1598                         if line[0] == '#':
1599                                 last_line = line
1600                                 line = self.src.readline().strip(" \r\n")
1601                                 continue
1602
1603                         tokens = line.split(" ")
1604                         if tokens[0] == "white" or tokens[0] == "black":
1605                                 self.reset_board(line)
1606                                 last_line = line
1607                                 line = self.src.readline().strip(" \r\n")
1608                                 continue
1609
1610                         move = line.split(":")
1611                         move = move[len(move)-1].strip(" \r\n")
1612                         tokens = move.split(" ")
1613                         
1614                         
1615                         try:
1616                                 [x,y] = map(int, tokens[0:2])
1617                         except:
1618                                 last_line = line
1619                                 self.stop()
1620                                 break
1621
1622                         log(move)
1623
1624                         target = self.board.grid[x][y]
1625                         with self.lock:
1626                                 if target.colour == "white":
1627                                         self.state["turn"] = self.players[0]
1628                                 else:
1629                                         self.state["turn"] = self.players[1]
1630                         
1631                         move_piece = (tokens[2] == "->")
1632                         if move_piece:
1633                                 [x2,y2] = map(int, tokens[len(tokens)-2:])
1634
1635                         if isinstance(graphics, GraphicsThread):
1636                                 with graphics.lock:
1637                                         graphics.state["select"] = target
1638                                         
1639                         if not move_piece:
1640                                 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
1641                                 if isinstance(graphics, GraphicsThread):
1642                                         with graphics.lock:
1643                                                 graphics.state["moves"] = self.board.possible_moves(target)
1644                                         time.sleep(turn_delay)
1645                         else:
1646                                 self.board.update_move(x, y, x2, y2)
1647                                 if isinstance(graphics, GraphicsThread):
1648                                         with graphics.lock:
1649                                                 graphics.state["moves"] = [[x2,y2]]
1650                                         time.sleep(turn_delay)
1651                                         with graphics.lock:
1652                                                 graphics.state["select"] = None
1653                                                 graphics.state["moves"] = None
1654                                                 graphics.state["dest"] = None
1655                         
1656
1657                         
1658                         
1659                         
1660                         for p in self.players:
1661                                 p.update(move)
1662
1663                         last_line = line
1664                         line = self.src.readline().strip(" \r\n")
1665                         
1666                         
1667                         end = self.board.end_condition()
1668                         if end != None:
1669                                 self.final_result = end
1670                                 self.stop()
1671                                 break
1672                                         
1673                                                 
1674                                                 
1675
1676                         
1677                                         
1678
1679
1680                         
1681
1682                                 
1683                         
1684
1685                 
1686
1687                 if self.end and isinstance(graphics, GraphicsThread):
1688                         #graphics.stop()
1689                         pass # Let the user stop the display
1690                 elif not self.end and self.board.end_condition() == None:
1691                         global game
1692                         # Work out the last move
1693                                         
1694                         t = last_line.split(" ")
1695                         if t[len(t)-2] == "black":
1696                                 self.players.reverse()
1697                         elif t[len(t)-2] == "white":
1698                                 pass
1699                         elif self.state["turn"] != None and self.state["turn"].colour == "white":
1700                                 self.players.reverse()
1701
1702
1703                         game = GameThread(self.board, self.players)
1704                         game.run()
1705                 else:
1706                         pass
1707
1708                 
1709
1710 def opponent(colour):
1711         if colour == "white":
1712                 return "black"
1713         else:
1714                 return "white"
1715 # --- game.py --- #
1716 try:
1717         import pygame
1718 except:
1719         pass
1720 import os
1721
1722 # Dictionary that stores the unicode character representations of the different pieces
1723 # Chess was clearly the reason why unicode was invented
1724 # For some reason none of the pygame chess implementations I found used them!
1725 piece_char = {"white" : {"king" : u'\u2654',
1726                          "queen" : u'\u2655',
1727                          "rook" : u'\u2656',
1728                          "bishop" : u'\u2657',
1729                          "knight" : u'\u2658',
1730                          "pawn" : u'\u2659',
1731                          "unknown" : '?'},
1732                 "black" : {"king" : u'\u265A',
1733                          "queen" : u'\u265B',
1734                          "rook" : u'\u265C',
1735                          "bishop" : u'\u265D',
1736                          "knight" : u'\u265E',
1737                          "pawn" : u'\u265F',
1738                          "unknown" : '?'}}
1739
1740 images = {"white" : {}, "black" : {}}
1741 small_images = {"white" : {}, "black" : {}}
1742
1743 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
1744
1745         # Get the font sizes
1746         l_size = 5*(grid_sz[0] / 8)
1747         s_size = 3*(grid_sz[0] / 8)
1748
1749         for c in piece_char.keys():
1750                 
1751                 if c == "black":
1752                         for p in piece_char[c].keys():
1753                                 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
1754                                 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})         
1755                 elif c == "white":
1756                         for p in piece_char[c].keys():
1757                                 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1758                                 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1759                                 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1760                                 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1761         
1762
1763 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
1764         if not os.path.exists(image_dir):
1765                 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
1766         for c in piece_char.keys():
1767                 for p in piece_char[c].keys():
1768                         images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
1769                         small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
1770 # --- images.py --- #
1771 graphics_enabled = True
1772 try:
1773         import pygame
1774 except:
1775         graphics_enabled = False
1776         
1777
1778
1779
1780 # A thread to make things pretty
1781 class GraphicsThread(StoppableThread):
1782         def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1783                 StoppableThread.__init__(self)
1784                 
1785                 self.board = board
1786                 pygame.init()
1787                 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1788                 pygame.display.set_caption(title)
1789
1790                 #print "Initialised properly"
1791                 
1792                 self.grid_sz = grid_sz[:]
1793                 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
1794                 self.error = 0
1795                 self.lock = threading.RLock()
1796                 self.cond = threading.Condition()
1797
1798                 #print "Test font"
1799                 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
1800
1801                 #load_images()
1802                 create_images(grid_sz)
1803
1804                 """
1805                 for c in images.keys():
1806                         for p in images[c].keys():
1807                                 images[c][p] = images[c][p].convert(self.window)
1808                                 small_images[c][p] = small_images[c][p].convert(self.window)
1809                 """
1810
1811                 
1812         
1813
1814
1815         # On the run from the world
1816         def run(self):
1817                 
1818                 while not self.stopped():
1819                         
1820                         #print "Display grid"
1821                         self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
1822
1823                         #print "Display overlay"
1824                         self.overlay()
1825
1826                         #print "Display pieces"
1827                         self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board                
1828
1829                         pygame.display.flip()
1830
1831                         for event in pygame.event.get():
1832                                 if event.type == pygame.QUIT:
1833                                         if isinstance(game, GameThread):
1834                                                 with game.lock:
1835                                                         game.final_result = ""
1836                                                         if game.state["turn"] != None:
1837                                                                 game.final_result = game.state["turn"].colour + " "
1838                                                         game.final_result += "terminated"
1839                                                 game.stop()
1840                                         self.stop()
1841                                         break
1842                                 elif event.type == pygame.MOUSEBUTTONDOWN:
1843                                         self.mouse_down(event)
1844                                 elif event.type == pygame.MOUSEBUTTONUP:
1845                                         self.mouse_up(event)
1846                                         
1847
1848                                 
1849                                                                 
1850                                                 
1851                                                 
1852                 self.message("Game ends, result \""+str(game.final_result) + "\"")
1853                 time.sleep(1)
1854
1855                 # Wake up anyone who is sleeping
1856                 self.cond.acquire()
1857                 self.cond.notify()
1858                 self.cond.release()
1859
1860                 pygame.quit() # Time to say goodbye
1861
1862         # Mouse release event handler
1863         def mouse_up(self, event):
1864                 if event.button == 3:
1865                         with self.lock:
1866                                 self.state["overlay"] = None
1867                 elif event.button == 2:
1868                         with self.lock:
1869                                 self.state["coverage"] = None   
1870
1871         # Mouse click event handler
1872         def mouse_down(self, event):
1873                 if event.button == 1:
1874                         m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
1875                         if isinstance(game, GameThread):
1876                                 with game.lock:
1877                                         p = game.state["turn"]
1878                         else:
1879                                         p = None
1880                                         
1881                                         
1882                         if isinstance(p, HumanPlayer):
1883                                 with self.lock:
1884                                         s = self.board.grid[m[0]][m[1]]
1885                                         select = self.state["select"]
1886                                 if select == None:
1887                                         if s != None and s.colour != p.colour:
1888                                                 self.message("Wrong colour") # Look at all this user friendliness!
1889                                                 time.sleep(1)
1890                                                 return
1891                                         # Notify human player of move
1892                                         self.cond.acquire()
1893                                         with self.lock:
1894                                                 self.state["select"] = s
1895                                                 self.state["dest"] = None
1896                                         self.cond.notify()
1897                                         self.cond.release()
1898                                         return
1899
1900                                 if select == None:
1901                                         return
1902                                                 
1903                                         
1904                                 if self.state["moves"] == None:
1905                                         return
1906
1907                                 if not m in self.state["moves"]:
1908                                         self.message("Illegal Move") # I still think last year's mouse interface was adequate
1909                                         time.sleep(2)
1910                                         return
1911                                                 
1912                                 with self.lock:
1913                                         if self.state["dest"] == None:
1914                                                 self.cond.acquire()
1915                                                 self.state["dest"] = m
1916                                                 self.state["select"] = None
1917                                                 self.state["moves"] = None
1918                                                 self.cond.notify()
1919                                                 self.cond.release()
1920                 elif event.button == 3:
1921                         m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1922                         if isinstance(game, GameThread):
1923                                 with game.lock:
1924                                         p = game.state["turn"]
1925                         else:
1926                                 p = None
1927                                         
1928                                         
1929                         if isinstance(p, HumanPlayer):
1930                                 with self.lock:
1931                                         self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
1932
1933                 elif event.button == 2:
1934                         m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1935                         if isinstance(game, GameThread):
1936                                 with game.lock:
1937                                         p = game.state["turn"]
1938                         else:
1939                                 p = None
1940                         
1941                         
1942                         if isinstance(p, HumanPlayer):
1943                                 with self.lock:
1944                                         self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
1945                                 
1946         # Draw the overlay
1947         def overlay(self):
1948
1949                 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
1950                 # Draw square over the selected piece
1951                 with self.lock:
1952                         select = self.state["select"]
1953                 if select != None:
1954                         mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
1955                         square_img.fill(pygame.Color(0,255,0,64))
1956                         self.window.blit(square_img, mp)
1957                 # If a piece is selected, draw all reachable squares
1958                 # (This quality user interface has been patented)
1959                 with self.lock:
1960                         m = self.state["moves"]
1961                 if m != None:
1962                         square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
1963                         for move in m:
1964                                 mp = [self.grid_sz[i] * move[i] for i in range(2)]
1965                                 self.window.blit(square_img, mp)
1966                 # If a piece is overlayed, show all squares that it has a probability to reach
1967                 with self.lock:
1968                         m = self.state["overlay"]
1969                 if m != None:
1970                         for x in range(w):
1971                                 for y in range(h):
1972                                         if m[x][y] > 0.0:
1973                                                 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
1974                                                 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
1975                                                 self.window.blit(square_img, mp)
1976                                                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
1977                                                 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
1978                                                 self.window.blit(text, mp)
1979                                 
1980                 # If a square is selected, highlight all pieces that have a probability to reach it
1981                 with self.lock:                         
1982                         m = self.state["coverage"]
1983                 if m != None:
1984                         for p in m:
1985                                 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
1986                                 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
1987                                 self.window.blit(square_img, mp)
1988                                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
1989                                 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
1990                                 self.window.blit(text, mp)
1991                         # Draw a square where the mouse is
1992                 # This also serves to indicate who's turn it is
1993                 
1994                 if isinstance(game, GameThread):
1995                         with game.lock:
1996                                 turn = game.state["turn"]
1997                 else:
1998                         turn = None
1999
2000                 if isinstance(turn, HumanPlayer):
2001                         mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
2002                         square_img.fill(pygame.Color(0,0,255,128))
2003                         if turn.colour == "white":
2004                                 c = pygame.Color(255,255,255)
2005                         else:
2006                                 c = pygame.Color(0,0,0)
2007                         pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
2008                         self.window.blit(square_img, mp)
2009
2010         # Message in a bottle
2011         def message(self, string, pos = None, colour = None, font_size = 20):
2012                 #print "Drawing message..."
2013                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2014                 if colour == None:
2015                         colour = pygame.Color(0,0,0)
2016                 
2017                 text = font.render(string, 1, colour)
2018         
2019
2020                 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
2021                 s.fill(pygame.Color(128,128,128))
2022
2023                 tmp = self.window.get_size()
2024
2025                 if pos == None:
2026                         pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
2027                 else:
2028                         pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
2029                 
2030
2031                 rect = (pos[0], pos[1], text.get_width(), text.get_height())
2032         
2033                 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
2034                 self.window.blit(s, pos)
2035                 self.window.blit(text, pos)
2036
2037                 pygame.display.flip()
2038
2039         def getstr(self, prompt = None):
2040                 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
2041                 s.blit(self.window, (0,0))
2042                 result = ""
2043
2044                 while True:
2045                         #print "LOOP"
2046                         if prompt != None:
2047                                 self.message(prompt)
2048                                 self.message(result, pos = (0, 1))
2049         
2050                         pygame.event.pump()
2051                         for event in pygame.event.get():
2052                                 if event.type == pygame.QUIT:
2053                                         return None
2054                                 if event.type == pygame.KEYDOWN:
2055                                         if event.key == pygame.K_BACKSPACE:
2056                                                 result = result[0:len(result)-1]
2057                                                 self.window.blit(s, (0,0)) # Revert the display
2058                                                 continue
2059                                 
2060                                                 
2061                                         try:
2062                                                 if event.unicode == '\r':
2063                                                         return result
2064                                         
2065                                                 result += str(event.unicode)
2066                                         except:
2067                                                 continue
2068
2069
2070         # Function to pick a button
2071         def SelectButton(self, choices, prompt = None, font_size=20):
2072
2073                 #print "Select button called!"
2074                 self.board.display_grid(self.window, self.grid_sz)
2075                 if prompt != None:
2076                         self.message(prompt)
2077                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2078                 targets = []
2079                 sz = self.window.get_size()
2080
2081                 
2082                 for i in range(len(choices)):
2083                         c = choices[i]
2084                         
2085                         text = font.render(c, 1, pygame.Color(0,0,0))
2086                         p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
2087                         targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
2088
2089                 while True:
2090                         mp =pygame.mouse.get_pos()
2091                         for i in range(len(choices)):
2092                                 c = choices[i]
2093                                 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
2094                                         font_colour = pygame.Color(255,0,0)
2095                                         box_colour = pygame.Color(0,0,255,128)
2096                                 else:
2097                                         font_colour = pygame.Color(0,0,0)
2098                                         box_colour = pygame.Color(128,128,128)
2099                                 
2100                                 text = font.render(c, 1, font_colour)
2101                                 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
2102                                 s.fill(box_colour)
2103                                 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
2104                                 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
2105                                 self.window.blit(s, targets[i][0:2])
2106                                 
2107         
2108                         pygame.display.flip()
2109
2110                         for event in pygame.event.get():
2111                                 if event.type == pygame.QUIT:
2112                                         return None
2113                                 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
2114                                         for i in range(len(targets)):
2115                                                 t = targets[i]
2116                                                 if event.pos[0] > t[0] and event.pos[0] < t[2]:
2117                                                         if event.pos[1] > t[1] and event.pos[1] < t[3]:
2118                                                                 return i
2119                                                 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
2120                 
2121
2122         # Function to pick players in a nice GUI way
2123         def SelectPlayers(self, players = []):
2124
2125
2126                 #print "SelectPlayers called"
2127                 
2128                 missing = ["white", "black"]
2129                 for p in players:
2130                         missing.remove(p.colour)
2131
2132                 for colour in missing:
2133                         
2134                         
2135                         choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
2136                         if choice == 0:
2137                                 players.append(HumanPlayer("human", colour))
2138                         elif choice == 1:
2139                                 import inspect
2140                                 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2141                                 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2142                                 internal_agents.remove(('InternalAgent', InternalAgent)) 
2143                                 if len(internal_agents) > 0:
2144                                         choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
2145                                 else:
2146                                         choice2 = 1
2147
2148                                 if choice2 == 0:
2149                                         agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
2150                                         players.append(agent[1](agent[0], colour))                                      
2151                                 elif choice2 == 1:
2152                                         try:
2153                                                 import Tkinter
2154                                                 from tkFileDialog import askopenfilename
2155                                                 root = Tkinter.Tk() # Need a root to make Tkinter behave
2156                                                 root.withdraw() # Some sort of magic incantation
2157                                                 path = askopenfilename(parent=root, initialdir="../agents",title=
2158 'Choose an agent.')
2159                                                 if path == "":
2160                                                         return self.SelectPlayers()
2161                                                 players.append(make_player(path, colour))       
2162                                         except:
2163                                                 
2164                                                 p = None
2165                                                 while p == None:
2166                                                         self.board.display_grid(self.window, self.grid_sz)
2167                                                         pygame.display.flip()
2168                                                         path = self.getstr(prompt = "Enter path:")
2169                                                         if path == None:
2170                                                                 return None
2171         
2172                                                         if path == "":
2173                                                                 return self.SelectPlayers()
2174         
2175                                                         try:
2176                                                                 p = make_player(path, colour)
2177                                                         except:
2178                                                                 self.board.display_grid(self.window, self.grid_sz)
2179                                                                 pygame.display.flip()
2180                                                                 self.message("Invalid path!")
2181                                                                 time.sleep(1)
2182                                                                 p = None
2183                                                 players.append(p)
2184                         elif choice == 2:
2185                                 address = ""
2186                                 while address == "":
2187                                         self.board.display_grid(self.window, self.grid_sz)
2188                                         
2189                                         address = self.getstr(prompt = "Address? (leave blank for server)")
2190                                         if address == None:
2191                                                 return None
2192                                         if address == "":
2193                                                 address = None
2194                                                 continue
2195                                         try:
2196                                                 map(int, address.split("."))
2197                                         except:
2198                                                 self.board.display_grid(self.window, self.grid_sz)
2199                                                 self.message("Invalid IPv4 address!")
2200                                                 address = ""
2201
2202                                 players.append(NetworkReceiver(colour, address))
2203                         else:
2204                                 return None
2205                 #print str(self) + ".SelectPlayers returns " + str(players)
2206                 return players
2207                         
2208                                 
2209                         
2210 # --- graphics.py --- #
2211 #!/usr/bin/python -u
2212
2213 # Do you know what the -u does? It unbuffers stdin and stdout
2214 # I can't remember why, but last year things broke without that
2215
2216 """
2217         UCC::Progcomp 2013 Quantum Chess game
2218         @author Sam Moore [SZM] "matches"
2219         @copyright The University Computer Club, Incorporated
2220                 (ie: You can copy it for not for profit purposes)
2221 """
2222
2223 # system python modules or whatever they are called
2224 import sys
2225 import os
2226 import time
2227
2228 turn_delay = 0.5
2229 [game, graphics] = [None, None]
2230
2231 def make_player(name, colour):
2232         if name[0] == '@':
2233                 if name[1:] == "human":
2234                         return HumanPlayer(name, colour)
2235                 s = name[1:].split(":")
2236                 if s[0] == "network":
2237                         address = None
2238                         if len(s) > 1:
2239                                 address = s[1]
2240                         return NetworkReceiver(colour, address)
2241                 if s[0] == "internal":
2242
2243                         import inspect
2244                         internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2245                         internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2246                         internal_agents.remove(('InternalAgent', InternalAgent)) 
2247                         
2248                         if len(s) != 2:
2249                                 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
2250                                 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2251                                 return None
2252
2253                         for a in internal_agents:
2254                                 if s[1] == a[0]:
2255                                         return a[1](name, colour)
2256                         
2257                         sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
2258                         sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2259                         return None
2260                         
2261
2262         else:
2263                 return ExternalAgent(name, colour)
2264                         
2265
2266
2267 # The main function! It does the main stuff!
2268 def main(argv):
2269
2270         # Apparently python will silently treat things as local unless you do this
2271         # Anyone who says "You should never use a global variable" can die in a fire
2272         global game
2273         global graphics
2274         
2275         global turn_delay
2276         global agent_timeout
2277         global log_files
2278         global src_file
2279         global graphics_enabled
2280         global always_reveal_states
2281
2282         max_moves = None
2283         src_file = None
2284         
2285         style = "quantum"
2286         colour = "white"
2287
2288         # Get the important warnings out of the way
2289         if platform.system() == "Windows":
2290                 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
2291                 if platform.release() == "Vista":
2292                         sys.stderr.write(sys.argv[0] + " : God help you.\n")
2293         
2294
2295         players = []
2296         i = 0
2297         while i < len(argv)-1:
2298                 i += 1
2299                 arg = argv[i]
2300                 if arg[0] != '-':
2301                         p = make_player(arg, colour)
2302                         if not isinstance(p, Player):
2303                                 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
2304                                 return 100
2305                         players.append(p)
2306                         if colour == "white":
2307                                 colour = "black"
2308                         elif colour == "black":
2309                                 pass
2310                         else:
2311                                 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
2312                         continue
2313
2314                 # Option parsing goes here
2315                 if arg[1] == '-' and arg[2:] == "classical":
2316                         style = "classical"
2317                 elif arg[1] == '-' and arg[2:] == "quantum":
2318                         style = "quantum"
2319                 elif arg[1] == '-' and arg[2:] == "reveal":
2320                         always_reveal_states = True
2321                 elif (arg[1] == '-' and arg[2:] == "graphics"):
2322                         graphics_enabled = not graphics_enabled
2323                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
2324                         # Load game from file
2325                         if len(arg[2:].split("=")) == 1:
2326                                 src_file = sys.stdin
2327                         else:
2328                                 f = arg[2:].split("=")[1]
2329                                 if f[0:7] == "http://":
2330                                         src_file = HttpReplay(f)
2331                                 else:
2332                                         src_file = open(f.split(":")[0], "r", 0)
2333
2334                                         if len(f.split(":")) == 2:
2335                                                 max_moves = int(f.split(":")[1])
2336
2337                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
2338                         # Log file
2339                         if len(arg[2:].split("=")) == 1:
2340                                 log_files.append(LogFile(sys.stdout))
2341                         else:
2342                                 f = arg[2:].split("=")[1]
2343                                 if f[0] == '@':
2344                                         log_files.append(ShortLog(f[1:]))
2345                                 else:
2346                                         log_files.append(LogFile(open(f, "w", 0)))
2347                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
2348                         # Delay
2349                         if len(arg[2:].split("=")) == 1:
2350                                 turn_delay = 0
2351                         else:
2352                                 turn_delay = float(arg[2:].split("=")[1])
2353
2354                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
2355                         # Timeout
2356                         if len(arg[2:].split("=")) == 1:
2357                                 agent_timeout = -1
2358                         else:
2359                                 agent_timeout = float(arg[2:].split("=")[1])
2360                                 
2361                 elif (arg[1] == '-' and arg[2:] == "help"):
2362                         # Help
2363                         os.system("less data/help.txt") # The best help function
2364                         return 0
2365
2366
2367         # Create the board
2368         
2369         # Construct a GameThread! Make it global! Damn the consequences!
2370                         
2371         if src_file != None:
2372                 # Hack to stop ReplayThread from exiting
2373                 #if len(players) == 0:
2374                 #       players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
2375
2376                 # Normally the ReplayThread exits if there are no players
2377                 # TODO: Decide which behaviour to use, and fix it
2378                 end = (len(players) == 0)
2379                 if end:
2380                         players = [Player("dummy", "white"), Player("dummy", "black")]
2381                 elif len(players) != 2:
2382                         sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2383                         if graphics_enabled:
2384                                 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
2385                         return 44
2386                 game = ReplayThread(players, src_file, end=end, max_moves=max_moves)
2387         else:
2388                 board = Board(style)
2389                 board.max_moves = max_moves
2390                 game = GameThread(board, players) 
2391
2392
2393
2394
2395         # Initialise GUI
2396         if graphics_enabled == True:
2397                 try:
2398                         graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
2399
2400                 except Exception,e:
2401                         graphics = None
2402                         sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
2403                         graphics_enabled = False
2404
2405         # If there are no players listed, display a nice pretty menu
2406         if len(players) != 2:
2407                 if graphics != None:
2408                         players = graphics.SelectPlayers(players)
2409                 else:
2410                         sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2411                         return 44
2412
2413         # If there are still no players, quit
2414         if players == None or len(players) != 2:
2415                 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
2416                 return 45
2417
2418
2419         # Wrap NetworkSender players around original players if necessary
2420         for i in range(len(players)):
2421                 if isinstance(players[i], NetworkReceiver):
2422                         players[i].board = board # Network players need direct access to the board
2423                         for j in range(len(players)):
2424                                 if j == i:
2425                                         continue
2426                                 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
2427                                         continue
2428                                 players[j] = NetworkSender(players[j], players[i].address)
2429                                 players[j].board = board
2430
2431         # Connect the networked players
2432         for p in players:
2433                 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
2434                         if graphics != None:
2435                                 graphics.board.display_grid(graphics.window, graphics.grid_sz)
2436                                 graphics.message("Connecting to " + p.colour + " player...")
2437                         p.connect()
2438
2439         
2440         # If using windows, select won't work; use horrible TimeoutPlayer hack
2441         if agent_timeout > 0:
2442                 if platform.system() == "Windows":
2443                         for i in range(len(players)):
2444                                 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
2445                                         players[i] = TimeoutPlayer(players[i], agent_timeout)
2446
2447                 else:
2448                         warned = False
2449                         # InternalAgents get wrapped to an ExternalAgent when there is a timeout
2450                         # This is not confusing at all.
2451                         for i in range(len(players)):
2452                                 if isinstance(players[i], InternalAgent):
2453                                                 players[i] = ExternalWrapper(players[i])
2454
2455
2456                 
2457
2458
2459
2460
2461         log_init(game.board, players)
2462         
2463         
2464         if graphics != None:
2465                 game.start() # This runs in a new thread
2466                 graphics.run()
2467                 if game.is_alive():
2468                         game.join()
2469         
2470
2471                 error = game.error + graphics.error
2472         else:
2473                 game.run()
2474                 error = game.error
2475         
2476
2477         for l in log_files:
2478                 l.close()
2479
2480         if src_file != None and src_file != sys.stdin:
2481                 src_file.close()
2482
2483         return error
2484
2485 # This is how python does a main() function...
2486 if __name__ == "__main__":
2487         try:
2488                 sys.exit(main(sys.argv))
2489         except KeyboardInterrupt:
2490                 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
2491                 if isinstance(graphics, StoppableThread):
2492                         graphics.stop()
2493                         graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
2494
2495                 if isinstance(game, StoppableThread):
2496                         game.stop()
2497                         if game.is_alive():
2498                                 game.join()
2499
2500                 sys.exit(102)
2501
2502 # --- main.py --- #
2503 # EOF - created from make on Thu Jan 31 13:37:15 WST 2013

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