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

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