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