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

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