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

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