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

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