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

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