Feature creep in log files
[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                 self.types_revealed = [True, False] # Whether the types are known (by default the first type is always known at game start)
18                 
19
20                 # 
21                 self.last_state = None
22                 self.move_pattern = None
23
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                 self.types_revealed = c.types_revealed[:]
34
35                 self.last_state = None
36                 self.move_pattern = None
37
38         
39
40         # Make a string for the piece (used for debug)
41         def __str__(self):
42                 return str(self.colour) + " " + str(self.current_type) + " " + str(self.types) + " at " + str(self.x) + ","+str(self.y)  
43
44         # Draw the piece in a pygame surface
45         def draw(self, window, grid_sz = [80,80], style="quantum"):
46
47                 # First draw the image corresponding to self.current_type
48                 img = images[self.colour][self.current_type]
49                 rect = img.get_rect()
50                 if style == "classical":
51                         offset = [-rect.width/2, -rect.height/2]
52                 else:
53                         offset = [-rect.width/2,-3*rect.height/4] 
54                 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]))
55                 
56                 
57                 if style == "classical":
58                         return
59
60                 # Draw the two possible types underneath the current_type image
61                 for i in range(len(self.types)):
62                         if always_reveal_states == True or self.types_revealed[i] == True:
63                                 img = small_images[self.colour][self.types[i]]
64                         else:
65                                 img = small_images[self.colour]["unknown"] # If the type hasn't been revealed, show a placeholder
66
67                         
68                         rect = img.get_rect()
69                         offset = [-rect.width/2,-rect.height/2] 
70                         
71                         if i == 0:
72                                 target = (self.x * grid_sz[0] + grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])                             
73                         else:
74                                 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])                           
75                                 
76                         window.blit(img, target) # Blit shit
77         
78         # Collapses the wave function!          
79         def select(self):
80                 if self.current_type == "unknown":
81                         self.choice = random.randint(0,1)
82                         self.current_type = self.types[self.choice]
83                         self.types_revealed[self.choice] = True
84                 return self.choice
85
86         # Uncollapses (?) the wave function!
87         def deselect(self):
88                 #print "Deselect called"
89                 if (self.x + self.y) % 2 != 0:
90                         if (self.types[0] != self.types[1]) or (self.types_revealed[0] == False or self.types_revealed[1] == False):
91                                 self.current_type = "unknown"
92                                 self.choice = -1
93                         else:
94                                 self.choice = 0 # Both the two types are the same
95
96         # The sad moment when you realise that you do not understand anything about a subject you studied for 4 years...
97 # --- piece.py --- #
98 [w,h] = [8,8] # Width and height of board(s)
99
100 always_reveal_states = False
101
102 # Class to represent a quantum chess board
103 class Board():
104         # Initialise; if master=True then the secondary piece types are assigned
105         #       Otherwise, they are left as unknown
106         #       So you can use this class in Agent programs, and fill in the types as they are revealed
107         def __init__(self, style="agent"):
108                 self.style = style
109                 self.pieces = {"white" : [], "black" : []}
110                 self.grid = [[None] * w for _ in range(h)] # 2D List (you can get arrays in python, somehow, but they scare me)
111                 self.unrevealed_types = {"white" : piece_types.copy(), "black" : piece_types.copy()}
112                 self.king = {"white" : None, "black" : None} # We need to keep track of the king, because he is important
113                 for c in ["black", "white"]:
114                         del self.unrevealed_types[c]["unknown"]
115
116                 if style == "empty":
117                         return
118
119                 # Add all the pieces with known primary types
120                 for i in range(0, 2):
121                         
122                         s = ["black", "white"][i]
123                         c = self.pieces[s]
124                         y = [0, h-1][i]
125
126                         c.append(Piece(s, 0, y, ["rook"]))
127                         c.append(Piece(s, 1, y, ["knight"]))
128                         c.append(Piece(s, 2, y, ["bishop"]))
129                         k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
130                         k.types_revealed[1] = True
131                         k.current_type = "king"
132                         self.king[s] = k
133                         c.append(k)
134                         c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
135                         c.append(Piece(s, 5, y, ["bishop"]))
136                         c.append(Piece(s, 6, y, ["knight"]))
137                         c.append(Piece(s, 7, y, ["rook"]))
138                         
139                         if y == 0: 
140                                 y += 1 
141                         else: 
142                                 y -= 1
143                         
144                         # Lots of pawn
145                         for x in range(0, w):
146                                 c.append(Piece(s, x, y, ["pawn"]))
147
148                         types_left = {}
149                         types_left.update(piece_types)
150                         del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
151                         del types_left["unknown"] # We certainly don't want these!
152                         for piece in c:
153                                 # Add to grid
154                                 self.grid[piece.x][piece.y] = piece 
155
156                                 if len(piece.types) > 1:
157                                         continue                                
158                                 if style == "agent": # Assign placeholder "unknown" secondary type
159                                         piece.types.append("unknown")
160                                         continue
161
162                                 elif style == "quantum":
163                                         # The master allocates the secondary types
164                                         choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
165                                         types_left[choice] -= 1
166                                         if types_left[choice] <= 0:
167                                                 del types_left[choice]
168                                         piece.types.append(choice)
169                                 elif style == "classical":
170                                         piece.types.append(piece.types[0])
171                                         piece.current_type = piece.types[0]
172                                         piece.types_revealed[1] = True
173                                         piece.choice = 0
174
175         def clone(self):
176                 newboard = Board(master = False)
177                 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
178                 mypieces = self.pieces["white"] + self.pieces["black"]
179
180                 for i in range(len(mypieces)):
181                         newpieces[i].init_from_copy(mypieces[i])
182                         
183
184         def display_grid(self, window = None, grid_sz = [80,80]):
185                 if window == None:
186                         return # I was considering implementing a text only display, then I thought "Fuck that"
187
188                 # The indentation is getting seriously out of hand...
189                 for x in range(0, w):
190                         for y in range(0, h):
191                                 if (x + y) % 2 == 0:
192                                         c = pygame.Color(200,200,200)
193                                 else:
194                                         c = pygame.Color(64,64,64)
195                                 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
196
197         def display_pieces(self, window = None, grid_sz = [80,80]):
198                 if window == None:
199                         return
200                 for p in self.pieces["white"] + self.pieces["black"]:
201                         p.draw(window, grid_sz, self.style)
202
203         # Draw the board in a pygame window
204         def display(self, window = None):
205                 self.display_grid(window)
206                 self.display_pieces(window)
207                 
208
209                 
210
211         def verify(self):
212                 for x in range(w):
213                         for y in range(h):
214                                 if self.grid[x][y] == None:
215                                         continue
216                                 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
217                                         raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
218
219         # Select a piece on the board (colour is the colour of whoever is doing the selecting)
220         def select(self, x,y, colour=None):
221                 if not self.on_board(x, y): # Get on board everyone!
222                         raise Exception("BOUNDS")
223
224                 piece = self.grid[x][y]
225                 if piece == None:
226                         raise Exception("EMPTY")
227
228                 if colour != None and piece.colour != colour:
229                         raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
230
231                 # I'm not quite sure why I made this return a string, but screw logical design
232                 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
233
234
235         # Update the board when a piece has been selected
236         # "type" is apparently reserved, so I'll use "state"
237         def update_select(self, x, y, type_index, state):
238                 piece = self.grid[x][y]
239                 if piece.types[type_index] == "unknown":
240                         if not state in self.unrevealed_types[piece.colour].keys():
241                                 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
242                         self.unrevealed_types[piece.colour][state] -= 1
243                         if self.unrevealed_types[piece.colour][state] <= 0:
244                                 del self.unrevealed_types[piece.colour][state]
245
246                 piece.types[type_index] = state
247                 piece.types_revealed[type_index] = True
248                 piece.current_type = state
249
250                 if len(self.possible_moves(piece)) <= 0:
251                         piece.deselect() # Piece can't move; deselect it
252                 
253         # Update the board when a piece has been moved
254         def update_move(self, x, y, x2, y2):
255                 piece = self.grid[x][y]
256                 self.grid[x][y] = None
257                 taken = self.grid[x2][y2]
258                 if taken != None:
259                         if taken.current_type == "king":
260                                 self.king[taken.colour] = None
261                         self.pieces[taken.colour].remove(taken)
262                 self.grid[x2][y2] = piece
263                 piece.x = x2
264                 piece.y = y2
265
266                 # If the piece is a pawn, and it reaches the final row, it becomes a queen
267                 # I know you are supposed to get a choice
268                 # But that would be effort
269                 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
270                         if self.style == "classical":
271                                 piece.types[0] = "queen"
272                                 piece.types[1] = "queen"
273                         else:
274                                 piece.types[piece.choice] = "queen"
275                         piece.current_type = "queen"
276
277                 piece.deselect() # Uncollapse (?) the wavefunction!
278                 self.verify()   
279
280         # Update the board from a string
281         # Guesses what to do based on the format of the string
282         def update(self, result):
283                 #print "Update called with \"" + str(result) + "\""
284                 # String always starts with 'x y'
285                 try:
286                         s = result.split(" ")
287                         [x,y] = map(int, s[0:2])        
288                 except:
289                         raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
290
291                 piece = self.grid[x][y]
292                 if piece == None:
293                         raise Exception("EMPTY")
294
295                 # If a piece is being moved, the third token is '->'
296                 # We could get away with just using four integers, but that wouldn't look as cool
297                 if "->" in s:
298                         # Last two tokens are the destination
299                         try:
300                                 [x2,y2] = map(int, s[3:])
301                         except:
302                                 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
303
304                         # Move the piece (take opponent if possible)
305                         self.update_move(x, y, x2, y2)
306                         
307                 else:
308                         # Otherwise we will just assume a piece has been selected
309                         try:
310                                 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
311                                 state = s[3] # The last token is a string identifying the type
312                         except:
313                                 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
314
315                         # Select the piece
316                         self.update_select(x, y, type_index, state)
317
318                 return result
319
320         # Gets each piece that could reach the given square and the probability that it could reach that square 
321         # Will include allied pieces that defend the attacker
322         def coverage(self, x, y, colour = None, reject_allied = True):
323                 result = {}
324                 
325                 if colour == None:
326                         pieces = self.pieces["white"] + self.pieces["black"]
327                 else:
328                         pieces = self.pieces[colour]
329
330                 for p in pieces:
331                         prob = self.probability_grid(p, reject_allied)[x][y]
332                         if prob > 0:
333                                 result.update({p : prob})
334                 
335                 self.verify()
336                 return result
337
338
339                 
340
341
342         # Associates each square with a probability that the piece could move into it
343         # Look, I'm doing all the hard work for you here...
344         def probability_grid(self, p, reject_allied = True):
345                 
346                 result = [[0.0] * w for _ in range(h)]
347                 if not isinstance(p, Piece):
348                         return result
349
350                 if p.current_type != "unknown":
351                         #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
352                         for point in self.possible_moves(p, reject_allied):
353                                 result[point[0]][point[1]] = 1.0
354                         return result
355                 
356                 
357                 for i in range(len(p.types)):
358                         t = p.types[i]
359                         prob = 0.5
360                         if t == "unknown" or p.types_revealed[i] == False:
361                                 total_types = 0
362                                 for t2 in self.unrevealed_types[p.colour].keys():
363                                         total_types += self.unrevealed_types[p.colour][t2]
364                                 
365                                 for t2 in self.unrevealed_types[p.colour].keys():
366                                         prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
367                                         p.current_type = t2
368                                         for point in self.possible_moves(p, reject_allied):
369                                                 result[point[0]][point[1]] += prob2 * prob
370                                 
371                         else:
372                                 p.current_type = t
373                                 for point in self.possible_moves(p, reject_allied):
374                                         result[point[0]][point[1]] += prob
375                 
376                 self.verify()
377                 p.current_type = "unknown"
378                 return result
379
380         def prob_is_type(self, p, state):
381                 prob = 0.5
382                 result = 0
383                 for i in range(len(p.types)):
384                         t = p.types[i]
385                         if t == state:
386                                 result += prob
387                                 continue        
388                         if t == "unknown" or p.types_revealed[i] == False:
389                                 total_prob = 0
390                                 for t2 in self.unrevealed_types[p.colour].keys():
391                                         total_prob += self.unrevealed_types[p.colour][t2]
392                                 for t2 in self.unrevealed_types[p.colour].keys():
393                                         if t2 == state:
394                                                 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
395                                 
396
397
398         # Get all squares that the piece could move into
399         # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
400         # reject_allied indicates whether squares occupied by allied pieces will be removed
401         # (set to false to check for defense)
402         def possible_moves(self, p, reject_allied = True):
403                 result = []
404                 if p == None:
405                         return result
406
407                 
408                 if p.current_type == "unknown":
409                         raise Exception("SANITY: Piece state unknown")
410                         # The below commented out code causes things to break badly
411                         #for t in p.types:
412                         #       if t == "unknown":
413                         #               continue
414                         #       p.current_type = t
415                         #       result += self.possible_moves(p)                                                
416                         #p.current_type = "unknown"
417                         #return result
418
419                 if p.current_type == "king":
420                         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]]
421                 elif p.current_type == "queen":
422                         for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
423                                 result += self.scan(p.x, p.y, d[0], d[1])
424                 elif p.current_type == "bishop":
425                         for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
426                                 result += self.scan(p.x, p.y, d[0], d[1])
427                 elif p.current_type == "rook":
428                         for d in [[-1,0],[1,0],[0,-1],[0,1]]:
429                                 result += self.scan(p.x, p.y, d[0], d[1])
430                 elif p.current_type == "knight":
431                         # I would use two lines, but I'm not sure how python likes that
432                         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]]
433                 elif p.current_type == "pawn":
434                         if p.colour == "white":
435                                 
436                                 # Pawn can't move forward into occupied square
437                                 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
438                                         result = [[p.x,p.y-1]]
439                                 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
440                                         if not self.on_board(f[0], f[1]):
441                                                 continue
442                                         if self.grid[f[0]][f[1]] != None:  # Pawn can take diagonally
443                                                 result.append(f)
444                                 if p.y == h-2:
445                                         # Slightly embarrassing if the pawn jumps over someone on its first move...
446                                         if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
447                                                 result.append([p.x, p.y-2])
448                         else:
449                                 # Vice versa for the black pawn
450                                 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
451                                         result = [[p.x,p.y+1]]
452
453                                 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
454                                         if not self.on_board(f[0], f[1]):
455                                                 continue
456                                         if self.grid[f[0]][f[1]] != None:
457                                                 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
458                                                 result.append(f)
459                                 if p.y == 1:
460                                         if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
461                                                 result.append([p.x, p.y+2])
462
463                         #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
464
465                 # Remove illegal moves
466                 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
467                 for point in result[:]: 
468
469                         if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
470                                 result.remove(point) # Remove locations outside the board
471                                 continue
472                         g = self.grid[point[0]][point[1]]
473                         
474                         if g != None and (g.colour == p.colour and reject_allied == True):
475                                 result.remove(point) # Remove allied pieces
476                 
477                 self.verify()
478                 return result
479
480
481         # Scans in a direction until it hits a piece, returns all squares in the line
482         # (includes the final square (which contains a piece), but not the original square)
483         def scan(self, x, y, vx, vy):
484                 p = []
485                         
486                 xx = x
487                 yy = y
488                 while True:
489                         xx += vx
490                         yy += vy
491                         if not self.on_board(xx, yy):
492                                 break
493                         if not [xx,yy] in p:
494                                 p.append([xx, yy])
495                         g = self.grid[xx][yy]
496                         if g != None:
497                                 return p        
498                                         
499                 return p
500
501
502
503         # I typed the full statement about 30 times before writing this function...
504         def on_board(self, x, y):
505                 return (x >= 0 and x < w) and (y >= 0 and y < h)
506 # --- board.py --- #
507 import subprocess
508 import select
509 import platform
510
511
512 agent_timeout = -1.0 # Timeout in seconds for AI players to make moves
513                         # WARNING: Won't work for windows based operating systems
514
515 if platform.system() == "Windows":
516         agent_timeout = -1 # Hence this
517
518 # A player who can't play
519 class Player():
520         def __init__(self, name, colour):
521                 self.name = name
522                 self.colour = colour
523
524         def update(self, result):
525                 pass
526
527 # Player that runs from another process
528 class ExternalAgent(Player):
529
530
531         def __init__(self, name, colour):
532                 Player.__init__(self, name, colour)
533                 self.p = subprocess.Popen(name,bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,universal_newlines=True)
534                 
535                 self.send_message(colour)
536
537         def send_message(self, s):
538                 if agent_timeout > 0.0:
539                         ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
540                 else:
541                         ready = [self.p.stdin]
542                 if self.p.stdin in ready:
543                         #sys.stderr.write("Writing \'" + s + "\' to " + str(self.p) + "\n")
544                         try:
545                                 self.p.stdin.write(s + "\n")
546                         except:
547                                 raise Exception("UNRESPONSIVE")
548                 else:
549                         raise Exception("TIMEOUT")
550
551         def get_response(self):
552                 if agent_timeout > 0.0:
553                         ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
554                 else:
555                         ready = [self.p.stdout]
556                 if self.p.stdout in ready:
557                         #sys.stderr.write("Reading from " + str(self.p) + " 's stdout...\n")
558                         try:
559                                 result = self.p.stdout.readline().strip("\r\n")
560                                 #sys.stderr.write("Read \'" + result + "\' from " + str(self.p) + "\n")
561                                 return result
562                         except: # Exception, e:
563                                 raise Exception("UNRESPONSIVE")
564                 else:
565                         raise Exception("TIMEOUT")
566
567         def select(self):
568
569                 self.send_message("SELECTION?")
570                 line = self.get_response()
571                 
572                 try:
573                         result = map(int, line.split(" "))
574                 except:
575                         raise Exception("GIBBERISH \"" + str(line) + "\"")
576                 return result
577
578         def update(self, result):
579                 #print "Update " + str(result) + " called for AgentPlayer"
580                 self.send_message(result)
581
582
583         def get_move(self):
584                 
585                 self.send_message("MOVE?")
586                 line = self.get_response()
587                 
588                 try:
589                         result = map(int, line.split(" "))
590                 except:
591                         raise Exception("GIBBERISH \"" + str(line) + "\"")
592                 return result
593
594         def quit(self, final_result):
595                 try:
596                         self.send_message("QUIT " + final_result)
597                 except:
598                         self.p.kill()
599
600 # So you want to be a player here?
601 class HumanPlayer(Player):
602         def __init__(self, name, colour):
603                 Player.__init__(self, name, colour)
604                 
605         # Select your preferred account
606         def select(self):
607                 if isinstance(graphics, GraphicsThread):
608                         # Basically, we let the graphics thread do some shit and then return that information to the game thread
609                         graphics.cond.acquire()
610                         # We wait for the graphics thread to select a piece
611                         while graphics.stopped() == False and graphics.state["select"] == None:
612                                 graphics.cond.wait() # The difference between humans and machines is that humans sleep
613                         select = graphics.state["select"]
614                         
615                         
616                         graphics.cond.release()
617                         if graphics.stopped():
618                                 return [-1,-1]
619                         return [select.x, select.y]
620                 else:
621                         # Since I don't display the board in this case, I'm not sure why I filled it in...
622                         while True:
623                                 sys.stdout.write("SELECTION?\n")
624                                 try:
625                                         p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
626                                 except:
627                                         sys.stderr.write("ILLEGAL GIBBERISH\n")
628                                         continue
629         # It's your move captain
630         def get_move(self):
631                 if isinstance(graphics, GraphicsThread):
632                         graphics.cond.acquire()
633                         while graphics.stopped() == False and graphics.state["dest"] == None:
634                                 graphics.cond.wait()
635                         graphics.cond.release()
636                         
637                         return graphics.state["dest"]
638                 else:
639
640                         while True:
641                                 sys.stdout.write("MOVE?\n")
642                                 try:
643                                         p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
644                                 except:
645                                         sys.stderr.write("ILLEGAL GIBBERISH\n")
646                                         continue
647
648         # Are you sure you want to quit?
649         def quit(self, final_result):
650                 if graphics == None:            
651                         sys.stdout.write("QUIT " + final_result + "\n")
652
653         # Completely useless function
654         def update(self, result):
655                 if isinstance(graphics, GraphicsThread):
656                         pass
657                 else:
658                         sys.stdout.write(result + "\n") 
659
660
661 # Default internal player (makes random moves)
662 class InternalAgent(Player):
663         def __init__(self, name, colour):
664                 Player.__init__(self, name, colour)
665                 self.choice = None
666
667                 self.board = Board(style = "agent")
668
669
670
671         def update(self, result):
672                 
673                 self.board.update(result)
674                 self.board.verify()
675
676         def quit(self, final_result):
677                 pass
678
679 class AgentRandom(InternalAgent):
680         def __init__(self, name, colour):
681                 InternalAgent.__init__(self, name, colour)
682
683         def select(self):
684                 while True:
685                         self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
686                         all_moves = []
687                         # Check that the piece has some possibility to move
688                         tmp = self.choice.current_type
689                         if tmp == "unknown": # For unknown pieces, try both types
690                                 for t in self.choice.types:
691                                         if t == "unknown":
692                                                 continue
693                                         self.choice.current_type = t
694                                         all_moves += self.board.possible_moves(self.choice)
695                         else:
696                                 all_moves = self.board.possible_moves(self.choice)
697                         self.choice.current_type = tmp
698                         if len(all_moves) > 0:
699                                 break
700                 return [self.choice.x, self.choice.y]
701
702         def get_move(self):
703                 moves = self.board.possible_moves(self.choice)
704                 move = moves[random.randint(0, len(moves)-1)]
705                 return move
706
707
708 # Terrible, terrible hacks
709
710 def run_agent(agent):
711         #sys.stderr.write(sys.argv[0] + " : Running agent " + str(agent) + "\n")
712         while True:
713                 line = sys.stdin.readline().strip(" \r\n")
714                 if line == "SELECTION?":
715                         #sys.stderr.write(sys.argv[0] + " : Make selection\n")
716                         [x,y] = agent.select() # Gets your agent's selection
717                         #sys.stderr.write(sys.argv[0] + " : Selection was " + str(agent.choice) + "\n")
718                         sys.stdout.write(str(x) + " " + str(y) + "\n")                          
719                 elif line == "MOVE?":
720                         #sys.stderr.write(sys.argv[0] + " : Make move\n")
721                         [x,y] = agent.get_move() # Gets your agent's move
722                         sys.stdout.write(str(x) + " " + str(y) + "\n")
723                 elif line.split(" ")[0] == "QUIT":
724                         #sys.stderr.write(sys.argv[0] + " : Quitting\n")
725                         agent.quit(" ".join(line.split(" ")[1:])) # Quits the game
726                         break
727                 else:
728                         agent.update(line) # Updates agent.board
729         return 0
730
731
732 # Sort of works?
733
734 class ExternalWrapper(ExternalAgent):
735         def __init__(self, agent):
736                 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))\""
737                 # str(run)
738                 ExternalAgent.__init__(self, run, agent.colour)
739
740         
741
742 # --- player.py --- #
743 # A sample agent
744
745
746 class AgentBishop(InternalAgent): # Inherits from InternalAgent (in qchess)
747         def __init__(self, name, colour):
748                 InternalAgent.__init__(self, name, colour)
749                 self.value = {"pawn" : 1, "bishop" : 3, "knight" : 3, "rook" : 5, "queen" : 9, "king" : 100, "unknown" : 4}
750
751                 self.aggression = 2.0 # Multiplier for scoring due to aggressive actions
752                 self.defence = 1.0 # Multiplier for scoring due to defensive actions
753                 
754                 self.depth = 0 # Current depth
755                 self.max_depth = 2 # Recurse this many times (for some reason, makes more mistakes when this is increased???)
756                 self.recurse_for = -1 # Recurse for the best few moves each times (less than 0 = all moves)
757
758                 for p in self.board.pieces["white"] + self.board.pieces["black"]:
759                         p.last_moves = None
760                         p.selected_moves = None
761
762                 
763
764         def get_value(self, piece):
765                 if piece == None:
766                         return 0.0
767                 return float(self.value[piece.types[0]] + self.value[piece.types[1]]) / 2.0
768                 
769         # Score possible moves for the piece
770         
771         def prioritise_moves(self, piece):
772
773                 #sys.stderr.write(sys.argv[0] + " : " + str(self) + " prioritise called for " + str(piece) + "\n")
774
775                 
776                 
777                 grid = self.board.probability_grid(piece)
778                 #sys.stderr.write("\t Probability grid " + str(grid) + "\n")
779                 moves = []
780                 for x in range(w):
781                         for y in range(h):
782                                 if grid[x][y] < 0.3: # Throw out moves with < 30% probability
783                                         #sys.stderr.write("\tReject " + str(x) + "," + str(y) + " (" + str(grid[x][y]) + ")\n")
784                                         continue
785
786                                 target = self.board.grid[x][y]
787                         
788                                 
789                                 
790                                 
791                                 # Get total probability that the move is protected
792                                 [xx,yy] = [piece.x, piece.y]
793                                 [piece.x, piece.y] = [x, y]
794                                 self.board.grid[x][y] = piece
795                                 self.board.grid[xx][yy] = None
796                                 
797                                 defenders = self.board.coverage(x, y, piece.colour, reject_allied = False)
798                                 d_prob = 0.0
799                                 for d in defenders.keys():
800                                         d_prob += defenders[d]
801                                 if len(defenders.keys()) > 0:
802                                         d_prob /= float(len(defenders.keys()))
803
804                                 if (d_prob > 1.0):
805                                         d_prob = 1.0
806
807                                 # Get total probability that the move is threatened
808                                 attackers = self.board.coverage(x, y, opponent(piece.colour), reject_allied = False)
809                                 a_prob = 0.0
810                                 for a in attackers.keys():
811                                         a_prob += attackers[a]
812                                 if len(attackers.keys()) > 0:
813                                         a_prob /= float(len(attackers.keys()))
814
815                                 if (a_prob > 1.0):
816                                         a_prob = 1.0
817
818                                 self.board.grid[x][y] = target
819                                 self.board.grid[xx][yy] = piece
820                                 [piece.x, piece.y] = [xx, yy]
821
822                                 
823                                 # Score of the move
824                                 value = self.aggression * (1.0 + d_prob) * self.get_value(target) - self.defence * (1.0 - d_prob) * a_prob * self.get_value(piece)
825
826                                 # Adjust score based on movement of piece out of danger
827                                 attackers = self.board.coverage(piece.x, piece.y, opponent(piece.colour))
828                                 s_prob = 0.0
829                                 for a in attackers.keys():
830                                         s_prob += attackers[a]
831                                 if len(attackers.keys()) > 0:
832                                         s_prob /= float(len(attackers.keys()))
833
834                                 if (s_prob > 1.0):
835                                         s_prob = 1.0
836                                 value += self.defence * s_prob * self.get_value(piece)
837                                 
838                                 # Adjust score based on probability that the move is actually possible
839                                 moves.append([[x, y], grid[x][y] * value])
840
841                 moves.sort(key = lambda e : e[1], reverse = True)
842                 #sys.stderr.write(sys.argv[0] + ": Moves for " + str(piece) + " are " + str(moves) + "\n")
843
844                 piece.last_moves = moves
845                 piece.selected_moves = None
846
847                 
848
849                 
850                 return moves
851
852         def select_best(self, colour):
853
854                 self.depth += 1
855                 all_moves = {}
856                 for p in self.board.pieces[colour]:
857                         self.choice = p # Temporarily pick that piece
858                         m = self.prioritise_moves(p)
859                         if len(m) > 0:
860                                 all_moves.update({p : m[0]})
861
862                 if len(all_moves.items()) <= 0:
863                         return None
864                 
865                 
866                 opts = all_moves.items()
867                 opts.sort(key = lambda e : e[1][1], reverse = True)
868
869                 if self.depth >= self.max_depth:
870                         self.depth -= 1
871                         return list(opts[0])
872
873                 if self.recurse_for >= 0:
874                         opts = opts[0:self.recurse_for]
875                 #sys.stderr.write(sys.argv[0] + " : Before recurse, options are " + str(opts) + "\n")
876
877                 # Take the best few moves, and recurse
878                 for choice in opts[0:self.recurse_for]:
879                         [xx,yy] = [choice[0].x, choice[0].y] # Remember position
880                         [nx,ny] = choice[1][0] # Target
881                         [choice[0].x, choice[0].y] = [nx, ny] # Set position
882                         target = self.board.grid[nx][ny] # Remember piece in spot
883                         self.board.grid[xx][yy] = None # Remove piece
884                         self.board.grid[nx][ny] = choice[0] # Replace with moving piece
885                         
886                         # Recurse
887                         best_enemy_move = self.select_best(opponent(choice[0].colour))
888                         choice[1][1] -= best_enemy_move[1][1] / float(self.depth + 1.0)
889                         
890                         [choice[0].x, choice[0].y] = [xx, yy] # Restore position
891                         self.board.grid[nx][ny] = target # Restore taken piece
892                         self.board.grid[xx][yy] = choice[0] # Restore moved piece
893                         
894                 
895
896                 opts.sort(key = lambda e : e[1][1], reverse = True)
897                 #sys.stderr.write(sys.argv[0] + " : After recurse, options are " + str(opts) + "\n")
898
899                 self.depth -= 1
900                 return list(opts[0])
901
902                 
903
904         # Returns [x,y] of selected piece
905         def select(self):
906                 #sys.stderr.write("Getting choice...")
907                 self.choice = self.select_best(self.colour)[0]
908                 #sys.stderr.write(" Done " + str(self.choice)+"\n")
909                 return [self.choice.x, self.choice.y]
910         
911         # Returns [x,y] of square to move selected piece into
912         def get_move(self):
913                 #sys.stderr.write("Choice is " + str(self.choice) + "\n")
914                 self.choice.selected_moves = self.choice.last_moves
915                 moves = self.prioritise_moves(self.choice)
916                 if len(moves) > 0:
917                         return moves[0][0]
918                 else:
919                         return InternalAgent.get_move(self)
920
921 # --- agent_bishop.py --- #
922 import multiprocessing
923
924 # Hacky alternative to using select for timing out players
925
926 # WARNING: Do not wrap around HumanPlayer or things breakify
927 # WARNING: Do not use in general or things breakify
928
929 class Sleeper(multiprocessing.Process):
930         def __init__(self, timeout):
931                 multiprocessing.Process.__init__(self)
932                 self.timeout = timeout
933
934         def run(self):
935                 time.sleep(self.timeout)
936
937
938 class Worker(multiprocessing.Process):
939         def __init__(self, function, args, q):
940                 multiprocessing.Process.__init__(self)
941                 self.function = function
942                 self.args = args
943                 self.q = q
944
945         def run(self):
946                 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args) 
947                 self.q.put(self.function(*self.args))
948                 
949                 
950
951 def TimeoutFunction(function, args, timeout):
952         q = multiprocessing.Queue()
953         w = Worker(function, args, q)
954         s = Sleeper(timeout)
955         w.start()
956         s.start()
957         while True: # Busy loop of crappyness
958                 if not w.is_alive():
959                         s.terminate()
960                         result = q.get()
961                         w.join()
962                         #print "TimeoutFunction gets " + str(result)
963                         return result
964                 elif not s.is_alive():
965                         w.terminate()
966                         s.join()
967                         raise Exception("TIMEOUT")
968
969         
970                 
971
972 # A player that wraps another player and times out its moves
973 # Uses threads
974 # A (crappy) alternative to the use of select()
975 class TimeoutPlayer(Player):
976         def __init__(self, base_player, timeout):
977                 Player.__init__(self, base_player.name, base_player.colour)
978                 self.base_player = base_player
979                 self.timeout = timeout
980                 
981         def select(self):
982                 return TimeoutFunction(self.base_player.select, [], self.timeout)
983                 
984         
985         def get_move(self):
986                 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
987
988         def update(self, result):
989                 return TimeoutFunction(self.base_player.update, [result], self.timeout)
990
991         def quit(self, final_result):
992                 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
993 # --- timeout_player.py --- #
994 import socket
995 import select
996
997 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
998 network_timeout_delay = 1.0 # Maximum time between two characters being received
999
1000 class Network():
1001         def __init__(self, colour, address = None):
1002                 self.socket = socket.socket()
1003                 #self.socket.setblocking(0)
1004
1005                 if colour == "white":
1006                         self.port = 4562
1007                 else:
1008                         self.port = 4563
1009
1010                 self.src = None
1011
1012         #       print str(self) + " listens on port " + str(self.port)
1013
1014                 if address == None:
1015                         self.host = socket.gethostname()
1016                         self.socket.bind((self.host, self.port))
1017                         self.socket.listen(5)   
1018
1019                         self.src, self.address = self.socket.accept()
1020                         self.src.send("ok\n")
1021                         if self.get_response() == "QUIT":
1022                                 self.src.close()
1023                 else:
1024                         self.host = address
1025                         self.socket.connect((address, self.port))
1026                         self.src = self.socket
1027                         self.src.send("ok\n")
1028                         if self.get_response() == "QUIT":
1029                                 self.src.close()
1030
1031         def get_response(self):
1032                 # Timeout the start of the message (first character)
1033                 if network_timeout_start > 0.0:
1034                         ready = select.select([self.src], [], [], network_timeout_start)[0]
1035                 else:
1036                         ready = [self.src]
1037                 if self.src in ready:
1038                         s = self.src.recv(1)
1039                 else:
1040                         raise Exception("UNRESPONSIVE")
1041
1042
1043                 while s[len(s)-1] != '\n':
1044                         # Timeout on each character in the message
1045                         if network_timeout_delay > 0.0:
1046                                 ready = select.select([self.src], [], [], network_timeout_delay)[0]
1047                         else:
1048                                 ready = [self.src]
1049                         if self.src in ready:
1050                                 s += self.src.recv(1) 
1051                         else:
1052                                 raise Exception("UNRESPONSIVE")
1053
1054                 return s.strip(" \r\n")
1055
1056         def send_message(self,s):
1057                 if network_timeout_start > 0.0:
1058                         ready = select.select([], [self.src], [], network_timeout_start)[1]
1059                 else:
1060                         ready = [self.src]
1061
1062                 if self.src in ready:
1063                         self.src.send(s + "\n")
1064                 else:
1065                         raise Exception("UNRESPONSIVE")
1066
1067         def check_quit(self, s):
1068                 s = s.split(" ")
1069                 if s[0] == "QUIT":
1070                         with game.lock:
1071                                 game.final_result = " ".join(s[1:]) + " " + str(opponent(self.colour))
1072                         game.stop()
1073                         return True
1074
1075                 
1076
1077 class NetworkSender(Player,Network):
1078         def __init__(self, base_player, address = None):
1079                 self.base_player = base_player
1080                 Player.__init__(self, base_player.name, base_player.colour)
1081
1082                 self.address = address
1083
1084         def connect(self):
1085                 Network.__init__(self, self.base_player.colour, self.address)
1086
1087
1088
1089         def select(self):
1090                 [x,y] = self.base_player.select()
1091                 choice = self.board.grid[x][y]
1092                 s = str(x) + " " + str(y)
1093                 #print str(self) + ".select sends " + s
1094                 self.send_message(s)
1095                 return [x,y]
1096
1097         def get_move(self):
1098                 [x,y] = self.base_player.get_move()
1099                 s = str(x) + " " + str(y)
1100                 #print str(self) + ".get_move sends " + s
1101                 self.send_message(s)
1102                 return [x,y]
1103
1104         def update(self, s):
1105                 self.base_player.update(s)
1106                 s = s.split(" ")
1107                 [x,y] = map(int, s[0:2])
1108                 selected = self.board.grid[x][y]
1109                 if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
1110                         s = " ".join(s[0:3])
1111                         for i in range(2):
1112                                 if selected.types_revealed[i] == True:
1113                                         s += " " + str(selected.types[i])
1114                                 else:
1115                                         s += " unknown"
1116                         #print str(self) + ".update sends " + s
1117                         self.send_message(s)
1118                                 
1119
1120         def quit(self, final_result):
1121                 self.base_player.quit(final_result)
1122                 #self.src.send("QUIT " + str(final_result) + "\n")
1123                 self.src.close()
1124
1125 class NetworkReceiver(Player,Network):
1126         def __init__(self, colour, address=None):
1127                 
1128                 Player.__init__(self, address, colour)
1129
1130                 self.address = address
1131
1132                 self.board = None
1133
1134         def connect(self):
1135                 Network.__init__(self, self.colour, self.address)
1136                         
1137
1138         def select(self):
1139                 
1140                 s = self.get_response()
1141                 #print str(self) + ".select gets " + s
1142                 [x,y] = map(int,s.split(" "))
1143                 if x == -1 and y == -1:
1144                         #print str(self) + ".select quits the game"
1145                         with game.lock:
1146                                 game.final_state = "network terminated " + self.colour
1147                         game.stop()
1148                 return [x,y]
1149         def get_move(self):
1150                 s = self.get_response()
1151                 #print str(self) + ".get_move gets " + s
1152                 [x,y] = map(int,s.split(" "))
1153                 if x == -1 and y == -1:
1154                         #print str(self) + ".get_move quits the game"
1155                         with game.lock:
1156                                 game.final_state = "network terminated " + self.colour
1157                         game.stop()
1158                 return [x,y]
1159
1160         def update(self, result):
1161                 
1162                 result = result.split(" ")
1163                 [x,y] = map(int, result[0:2])
1164                 selected = self.board.grid[x][y]
1165                 if selected != None and selected.colour == self.colour and len(result) > 2 and not "->" in result:
1166                         s = self.get_response()
1167                         #print str(self) + ".update - receives " + str(s)
1168                         s = s.split(" ")
1169                         selected.choice = int(s[2])
1170                         for i in range(2):
1171                                 selected.types[i] = str(s[3+i])
1172                                 if s[3+i] == "unknown":
1173                                         selected.types_revealed[i] = False
1174                                 else:
1175                                         selected.types_revealed[i] = True
1176                         selected.current_type = selected.types[selected.choice] 
1177                 else:
1178                         pass
1179                         #print str(self) + ".update - ignore result " + str(result)                     
1180                 
1181
1182         def quit(self, final_result):
1183                 self.src.close()
1184         
1185 # --- network.py --- #
1186 import threading
1187
1188 # A thread that can be stopped!
1189 # Except it can only be stopped if it checks self.stopped() periodically
1190 # So it can sort of be stopped
1191 class StoppableThread(threading.Thread):
1192         def __init__(self):
1193                 threading.Thread.__init__(self)
1194                 self._stop = threading.Event()
1195
1196         def stop(self):
1197                 self._stop.set()
1198
1199         def stopped(self):
1200                 return self._stop.isSet()
1201 # --- thread_util.py --- #
1202 log_file = None
1203 import datetime
1204 import urllib2
1205
1206 class LogFile():
1207         def __init__(self, file_name):  
1208                 
1209                 self.log = open(file_name, "w", 0)
1210
1211         def write(self, s):
1212                 self.log.write(str(datetime.datetime.now()) + " : " + s + "\n")
1213
1214         def setup(self, board, players):
1215                 self.log.write("# Log starts " + str(datetime.datetime.now()) + "\n")
1216                 for p in players:
1217                         self.log.write("# " + p.colour + " : " + p.name + "\n")
1218                 
1219                 self.log.write("# Initial board\n")
1220                 for x in range(0, w):
1221                         for y in range(0, h):
1222                                 if board.grid[x][y] != None:
1223                                         self.log.write(str(board.grid[x][y]) + "\n")
1224
1225                 self.log.write("# Start game\n")
1226
1227 class HttpLog(LogFile):
1228         def __init__(self, file_name):
1229                 LogFile.__init__(self, file_name)
1230                 self.file_name = file_name
1231
1232         def write(self, s):
1233                 self.log.close()
1234                 self.log = open(self.file_name, "w", 0)
1235
1236                 LogFile.setup(self, game.board, game.players)
1237
1238                 LogFile.write(self, s)
1239                 
1240
1241 class HeadRequest(urllib2.Request):
1242         def get_method(self):
1243                 return "HEAD"
1244                 
1245 class HttpReplay():
1246         def __init__(self, address):
1247                 self.read_setup = False
1248                 self.log = urllib2.urlopen(address)
1249                 self.address = address
1250
1251         def readline(self):
1252                 
1253                 line = self.log.readline()
1254                 sys.stderr.write(sys.argv[0] + " : " + str(self) + " read \""+str(line) + "\" from address " + str(self.address) + "\n")
1255                 if line == "":
1256                         sys.stderr.write(sys.argv[0] + " : " + str(self) + " retrieving from address " + str(self.address) + "\n")
1257                         date_mod = datetime.datetime.strptime(self.log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1258                         self.log.close()
1259
1260                         next_log = urllib2.urlopen(HeadRequest(self.address))
1261                         date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1262                         while date_new <= date_mod:
1263                                 next_log = urllib2.urlopen(HeadRequest(self.address))
1264                                 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1265
1266                         self.log = urllib2.urlopen(address)
1267                         game.setup()
1268                         line = self.log.readline()
1269
1270
1271                 return line
1272                         
1273                                                 
1274 def log(s):
1275         if log_file != None:
1276                 log_file.write(s)
1277                 
1278
1279 def log_init(board, players):
1280         if log_file != None:
1281                 log_file.setup(board, players)
1282
1283 # --- log.py --- #
1284
1285
1286
1287         
1288
1289 # A thread that runs the game
1290 class GameThread(StoppableThread):
1291         def __init__(self, board, players):
1292                 StoppableThread.__init__(self)
1293                 self.board = board
1294                 self.players = players
1295                 self.state = {"turn" : None} # The game state
1296                 self.error = 0 # Whether the thread exits with an error
1297                 self.lock = threading.RLock() #lock for access of self.state
1298                 self.cond = threading.Condition() # conditional for some reason, I forgot
1299                 self.final_result = ""
1300                 
1301                 
1302
1303         # Run the game (run in new thread with start(), run in current thread with run())
1304         def run(self):
1305                 result = ""
1306                 while not self.stopped():
1307                         
1308                         for p in self.players:
1309                                 with self.lock:
1310                                         if isinstance(p, NetworkSender):
1311                                                 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
1312                                         else:
1313                                                 self.state["turn"] = p
1314                                 #try:
1315                                 if True:
1316                                         [x,y] = p.select() # Player selects a square
1317                                         if self.stopped():
1318                                                 break
1319
1320                                         
1321                                                 
1322
1323                                         result = self.board.select(x, y, colour = p.colour)                             
1324                                         for p2 in self.players:
1325                                                 p2.update(result) # Inform players of what happened
1326
1327
1328                                         log(result)
1329
1330                                         target = self.board.grid[x][y]
1331                                         if isinstance(graphics, GraphicsThread):
1332                                                 with graphics.lock:
1333                                                         graphics.state["moves"] = self.board.possible_moves(target)
1334                                                         graphics.state["select"] = target
1335
1336                                         time.sleep(turn_delay)
1337
1338
1339                                         if len(self.board.possible_moves(target)) == 0:
1340                                                 #print "Piece cannot move"
1341                                                 target.deselect()
1342                                                 if isinstance(graphics, GraphicsThread):
1343                                                         with graphics.lock:
1344                                                                 graphics.state["moves"] = None
1345                                                                 graphics.state["select"] = None
1346                                                                 graphics.state["dest"] = None
1347                                                 continue
1348
1349                                         try:
1350                                                 [x2,y2] = p.get_move() # Player selects a destination
1351                                         except:
1352                                                 self.stop()
1353
1354                                         if self.stopped():
1355                                                 break
1356
1357                                         self.board.update_move(x, y, x2, y2)
1358                                         result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1359                                         for p2 in self.players:
1360                                                 p2.update(result) # Inform players of what happened
1361
1362                                         log(result)
1363
1364                                         if isinstance(graphics, GraphicsThread):
1365                                                 with graphics.lock:
1366                                                         graphics.state["moves"] = [[x2,y2]]
1367
1368                                         time.sleep(turn_delay)
1369
1370                                         if isinstance(graphics, GraphicsThread):
1371                                                 with graphics.lock:
1372                                                         graphics.state["select"] = None
1373                                                         graphics.state["dest"] = None
1374                                                         graphics.state["moves"] = None
1375
1376                         # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
1377                         #       except Exception,e:
1378                         #               result = e.message
1379                         #               #sys.stderr.write(result + "\n")
1380                         #               
1381                         #               self.stop()
1382                         #               with self.lock:
1383                         #                       self.final_result = self.state["turn"].colour + " " + e.message
1384
1385                                 if self.board.king["black"] == None:
1386                                         if self.board.king["white"] == None:
1387                                                 with self.lock:
1388                                                         self.final_result = self.state["turn"].colour + " DRAW"
1389                                         else:
1390                                                 with self.lock:
1391                                                         self.final_result = "white"
1392                                         self.stop()
1393                                 elif self.board.king["white"] == None:
1394                                         with self.lock:
1395                                                 self.final_result = "black"
1396                                         self.stop()
1397                                                 
1398
1399                                 if self.stopped():
1400                                         break
1401
1402
1403                 for p2 in self.players:
1404                         p2.quit(self.final_result)
1405
1406                 log(self.final_result)
1407
1408                 graphics.stop()
1409
1410         
1411 # A thread that replays a log file
1412 class ReplayThread(GameThread):
1413         def __init__(self, players, src, end=False,max_lines=None):
1414                 self.board = Board(style="empty")
1415                 GameThread.__init__(self, self.board, players)
1416                 self.src = src
1417                 self.max_lines = max_lines
1418                 self.line_number = 0
1419                 self.end = end
1420
1421                 self.setup()
1422
1423         def setup(self):
1424                 if True:
1425                         while self.src.readline().strip(" \r\n") != "# Initial board":
1426                                 self.line_number += 1
1427                 
1428                         line = self.src.readline().strip(" \r\n")
1429                         
1430                         while line != "# Start game":
1431                                 #print "Reading line " + str(line)
1432                                 self.line_number += 1
1433                                 [x,y] = map(int, line.split("at")[1].strip(" \r\n").split(","))
1434                                 colour = line.split(" ")[0]
1435                                 current_type = line.split(" ")[1]
1436                                 types = map(lambda e : e.strip(" [],'"), line.split(" ")[2:4])
1437                                 p = Piece(colour, x, y, types)
1438                                 if current_type != "unknown":
1439                                         p.current_type = current_type
1440                                         p.choice = types.index(current_type)
1441
1442                                 self.board.pieces[colour].append(p)
1443                                 self.board.grid[x][y] = p
1444                                 if current_type == "king":
1445                                         self.board.king[colour] = p
1446
1447                                 line = self.src.readline().strip(" \r\n")
1448                                 
1449                 #except Exception, e:
1450                 #       raise Exception("FILE line: " + str(self.line_number) + " \""+str(line)+"\"") #\n" + e.message)
1451         
1452         def run(self):
1453                 i = 0
1454                 phase = 0
1455                 count = 0
1456                 line = self.src.readline().strip(" \r\n")
1457                 while line != "# EOF":
1458                         count += 1
1459                         if self.max_lines != None and count > self.max_lines:
1460                                 self.stop()
1461
1462                         if self.stopped():
1463                                 break
1464
1465                         with self.lock:
1466                                 self.state["turn"] = self.players[i]
1467
1468                         line = line.split(":")
1469                         result = line[len(line)-1].strip(" \r\n")
1470                         log(result)
1471
1472                         try:
1473                                 self.board.update(result)
1474                         except:
1475                                 self.final_result = result
1476                                 self.stop()
1477                                 break
1478
1479                         [x,y] = map(int, result.split(" ")[0:2])
1480                         target = self.board.grid[x][y]
1481
1482                         if isinstance(graphics, GraphicsThread):
1483                                 if phase == 0:
1484                                         with graphics.lock:
1485                                                 graphics.state["moves"] = self.board.possible_moves(target)
1486                                                 graphics.state["select"] = target
1487
1488                                         if self.end:
1489                                                 time.sleep(turn_delay)
1490
1491                                 elif phase == 1:
1492                                         [x2,y2] = map(int, result.split(" ")[3:5])
1493                                         with graphics.lock:
1494                                                 graphics.state["moves"] = [[x2,y2]]
1495
1496                                         if self.end:
1497                                                 time.sleep(turn_delay)
1498
1499                                         with graphics.lock:
1500                                                 graphics.state["select"] = None
1501                                                 graphics.state["dest"] = None
1502                                                 graphics.state["moves"] = None
1503                                                 
1504
1505
1506                         
1507
1508                         for p in self.players:
1509                                 p.update(result)
1510                         
1511                         phase = (phase + 1) % 2
1512                         if phase == 0:
1513                                 i = (i + 1) % 2
1514
1515                         line = self.src.readline().strip(" \r\n")
1516
1517                 if self.max_lines != None and self.max_lines > count:
1518                         sys.stderr.write(sys.argv[0] + " : Replaying from file; stopping at last line (" + str(count) + ")\n")
1519                         sys.stderr.write(sys.argv[0] + " : (You requested line " + str(self.max_lines) + ")\n")
1520
1521                 if self.end and isinstance(graphics, GraphicsThread):
1522                         #graphics.stop()
1523                         pass # Let the user stop the display
1524                 elif not self.end:
1525                         global game
1526                         game = GameThread(self.board, self.players)
1527                         game.run()
1528                 
1529
1530                 
1531
1532 def opponent(colour):
1533         if colour == "white":
1534                 return "black"
1535         else:
1536                 return "white"
1537 # --- game.py --- #
1538 try:
1539         import pygame
1540 except:
1541         pass
1542 import os
1543
1544 # Dictionary that stores the unicode character representations of the different pieces
1545 # Chess was clearly the reason why unicode was invented
1546 # For some reason none of the pygame chess implementations I found used them!
1547 piece_char = {"white" : {"king" : u'\u2654',
1548                          "queen" : u'\u2655',
1549                          "rook" : u'\u2656',
1550                          "bishop" : u'\u2657',
1551                          "knight" : u'\u2658',
1552                          "pawn" : u'\u2659',
1553                          "unknown" : '?'},
1554                 "black" : {"king" : u'\u265A',
1555                          "queen" : u'\u265B',
1556                          "rook" : u'\u265C',
1557                          "bishop" : u'\u265D',
1558                          "knight" : u'\u265E',
1559                          "pawn" : u'\u265F',
1560                          "unknown" : '?'}}
1561
1562 images = {"white" : {}, "black" : {}}
1563 small_images = {"white" : {}, "black" : {}}
1564
1565 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
1566
1567         # Get the font sizes
1568         l_size = 5*(grid_sz[0] / 8)
1569         s_size = 3*(grid_sz[0] / 8)
1570
1571         for c in piece_char.keys():
1572                 
1573                 if c == "black":
1574                         for p in piece_char[c].keys():
1575                                 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
1576                                 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})         
1577                 elif c == "white":
1578                         for p in piece_char[c].keys():
1579                                 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1580                                 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1581                                 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1582                                 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1583         
1584
1585 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
1586         if not os.path.exists(image_dir):
1587                 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
1588         for c in piece_char.keys():
1589                 for p in piece_char[c].keys():
1590                         images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
1591                         small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
1592 # --- images.py --- #
1593 graphics_enabled = True
1594 try:
1595         import pygame
1596 except:
1597         graphics_enabled = False
1598         
1599
1600
1601
1602 # A thread to make things pretty
1603 class GraphicsThread(StoppableThread):
1604         def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1605                 StoppableThread.__init__(self)
1606                 
1607                 self.board = board
1608                 pygame.init()
1609                 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1610                 pygame.display.set_caption(title)
1611
1612                 #print "Initialised properly"
1613                 
1614                 self.grid_sz = grid_sz[:]
1615                 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
1616                 self.error = 0
1617                 self.lock = threading.RLock()
1618                 self.cond = threading.Condition()
1619
1620                 #print "Test font"
1621                 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
1622
1623                 #load_images()
1624                 create_images(grid_sz)
1625
1626                 """
1627                 for c in images.keys():
1628                         for p in images[c].keys():
1629                                 images[c][p] = images[c][p].convert(self.window)
1630                                 small_images[c][p] = small_images[c][p].convert(self.window)
1631                 """
1632
1633                 
1634         
1635
1636
1637         # On the run from the world
1638         def run(self):
1639                 
1640                 while not self.stopped():
1641                         
1642                         #print "Display grid"
1643                         self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
1644
1645                         #print "Display overlay"
1646                         self.overlay()
1647
1648                         #print "Display pieces"
1649                         self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board                
1650
1651                         pygame.display.flip()
1652
1653                         for event in pygame.event.get():
1654                                 if event.type == pygame.QUIT:
1655                                         if isinstance(game, GameThread):
1656                                                 with game.lock:
1657                                                         game.final_result = ""
1658                                                         if game.state["turn"] != None:
1659                                                                 game.final_result = game.state["turn"].colour + " "
1660                                                         game.final_result += "terminated"
1661                                                 game.stop()
1662                                         self.stop()
1663                                         break
1664                                 elif event.type == pygame.MOUSEBUTTONDOWN:
1665                                         self.mouse_down(event)
1666                                 elif event.type == pygame.MOUSEBUTTONUP:
1667                                         self.mouse_up(event)
1668                                         
1669
1670                                 
1671                                                                 
1672                                                 
1673                                                 
1674                 self.message("Game ends, result \""+str(game.final_result) + "\"")
1675                 time.sleep(1)
1676
1677                 # Wake up anyone who is sleeping
1678                 self.cond.acquire()
1679                 self.cond.notify()
1680                 self.cond.release()
1681
1682                 pygame.quit() # Time to say goodbye
1683
1684         # Mouse release event handler
1685         def mouse_up(self, event):
1686                 if event.button == 3:
1687                         with self.lock:
1688                                 self.state["overlay"] = None
1689                 elif event.button == 2:
1690                         with self.lock:
1691                                 self.state["coverage"] = None   
1692
1693         # Mouse click event handler
1694         def mouse_down(self, event):
1695                 if event.button == 1:
1696                         m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
1697                         if isinstance(game, GameThread):
1698                                 with game.lock:
1699                                         p = game.state["turn"]
1700                         else:
1701                                         p = None
1702                                         
1703                                         
1704                         if isinstance(p, HumanPlayer):
1705                                 with self.lock:
1706                                         s = self.board.grid[m[0]][m[1]]
1707                                         select = self.state["select"]
1708                                 if select == None:
1709                                         if s != None and s.colour != p.colour:
1710                                                 self.message("Wrong colour") # Look at all this user friendliness!
1711                                                 time.sleep(1)
1712                                                 return
1713                                         # Notify human player of move
1714                                         self.cond.acquire()
1715                                         with self.lock:
1716                                                 self.state["select"] = s
1717                                                 self.state["dest"] = None
1718                                         self.cond.notify()
1719                                         self.cond.release()
1720                                         return
1721
1722                                 if select == None:
1723                                         return
1724                                                 
1725                                         
1726                                 if self.state["moves"] == None:
1727                                         return
1728
1729                                 if not m in self.state["moves"]:
1730                                         self.message("Illegal Move") # I still think last year's mouse interface was adequate
1731                                         time.sleep(2)
1732                                         return
1733                                                 
1734                                 with self.lock:
1735                                         if self.state["dest"] == None:
1736                                                 self.cond.acquire()
1737                                                 self.state["dest"] = m
1738                                                 self.state["select"] = None
1739                                                 self.state["moves"] = None
1740                                                 self.cond.notify()
1741                                                 self.cond.release()
1742                 elif event.button == 3:
1743                         m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1744                         if isinstance(game, GameThread):
1745                                 with game.lock:
1746                                         p = game.state["turn"]
1747                         else:
1748                                 p = None
1749                                         
1750                                         
1751                         if isinstance(p, HumanPlayer):
1752                                 with self.lock:
1753                                         self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
1754
1755                 elif event.button == 2:
1756                         m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1757                         if isinstance(game, GameThread):
1758                                 with game.lock:
1759                                         p = game.state["turn"]
1760                         else:
1761                                 p = None
1762                         
1763                         
1764                         if isinstance(p, HumanPlayer):
1765                                 with self.lock:
1766                                         self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
1767                                 
1768         # Draw the overlay
1769         def overlay(self):
1770
1771                 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
1772                 # Draw square over the selected piece
1773                 with self.lock:
1774                         select = self.state["select"]
1775                 if select != None:
1776                         mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
1777                         square_img.fill(pygame.Color(0,255,0,64))
1778                         self.window.blit(square_img, mp)
1779                 # If a piece is selected, draw all reachable squares
1780                 # (This quality user interface has been patented)
1781                 with self.lock:
1782                         m = self.state["moves"]
1783                 if m != None:
1784                         square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
1785                         for move in m:
1786                                 mp = [self.grid_sz[i] * move[i] for i in range(2)]
1787                                 self.window.blit(square_img, mp)
1788                 # If a piece is overlayed, show all squares that it has a probability to reach
1789                 with self.lock:
1790                         m = self.state["overlay"]
1791                 if m != None:
1792                         for x in range(w):
1793                                 for y in range(h):
1794                                         if m[x][y] > 0.0:
1795                                                 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
1796                                                 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
1797                                                 self.window.blit(square_img, mp)
1798                                                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
1799                                                 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
1800                                                 self.window.blit(text, mp)
1801                                 
1802                 # If a square is selected, highlight all pieces that have a probability to reach it
1803                 with self.lock:                         
1804                         m = self.state["coverage"]
1805                 if m != None:
1806                         for p in m:
1807                                 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
1808                                 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
1809                                 self.window.blit(square_img, mp)
1810                                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
1811                                 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
1812                                 self.window.blit(text, mp)
1813                         # Draw a square where the mouse is
1814                 # This also serves to indicate who's turn it is
1815                 
1816                 if isinstance(game, GameThread):
1817                         with game.lock:
1818                                 turn = game.state["turn"]
1819                 else:
1820                         turn = None
1821
1822                 if isinstance(turn, HumanPlayer):
1823                         mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
1824                         square_img.fill(pygame.Color(0,0,255,128))
1825                         if turn.colour == "white":
1826                                 c = pygame.Color(255,255,255)
1827                         else:
1828                                 c = pygame.Color(0,0,0)
1829                         pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
1830                         self.window.blit(square_img, mp)
1831
1832         # Message in a bottle
1833         def message(self, string, pos = None, colour = None, font_size = 20):
1834                 #print "Drawing message..."
1835                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
1836                 if colour == None:
1837                         colour = pygame.Color(0,0,0)
1838                 
1839                 text = font.render(string, 1, colour)
1840         
1841
1842                 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
1843                 s.fill(pygame.Color(128,128,128))
1844
1845                 tmp = self.window.get_size()
1846
1847                 if pos == None:
1848                         pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
1849                 else:
1850                         pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
1851                 
1852
1853                 rect = (pos[0], pos[1], text.get_width(), text.get_height())
1854         
1855                 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
1856                 self.window.blit(s, pos)
1857                 self.window.blit(text, pos)
1858
1859                 pygame.display.flip()
1860
1861         def getstr(self, prompt = None):
1862                 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
1863                 s.blit(self.window, (0,0))
1864                 result = ""
1865
1866                 while True:
1867                         #print "LOOP"
1868                         if prompt != None:
1869                                 self.message(prompt)
1870                                 self.message(result, pos = (0, 1))
1871         
1872                         pygame.event.pump()
1873                         for event in pygame.event.get():
1874                                 if event.type == pygame.QUIT:
1875                                         return None
1876                                 if event.type == pygame.KEYDOWN:
1877                                         if event.key == pygame.K_BACKSPACE:
1878                                                 result = result[0:len(result)-1]
1879                                                 self.window.blit(s, (0,0)) # Revert the display
1880                                                 continue
1881                                 
1882                                                 
1883                                         try:
1884                                                 if event.unicode == '\r':
1885                                                         return result
1886                                         
1887                                                 result += str(event.unicode)
1888                                         except:
1889                                                 continue
1890
1891
1892         # Function to pick a button
1893         def SelectButton(self, choices, prompt = None, font_size=20):
1894
1895                 #print "Select button called!"
1896                 self.board.display_grid(self.window, self.grid_sz)
1897                 if prompt != None:
1898                         self.message(prompt)
1899                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
1900                 targets = []
1901                 sz = self.window.get_size()
1902
1903                 
1904                 for i in range(len(choices)):
1905                         c = choices[i]
1906                         
1907                         text = font.render(c, 1, pygame.Color(0,0,0))
1908                         p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
1909                         targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
1910
1911                 while True:
1912                         mp =pygame.mouse.get_pos()
1913                         for i in range(len(choices)):
1914                                 c = choices[i]
1915                                 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
1916                                         font_colour = pygame.Color(255,0,0)
1917                                         box_colour = pygame.Color(0,0,255,128)
1918                                 else:
1919                                         font_colour = pygame.Color(0,0,0)
1920                                         box_colour = pygame.Color(128,128,128)
1921                                 
1922                                 text = font.render(c, 1, font_colour)
1923                                 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
1924                                 s.fill(box_colour)
1925                                 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
1926                                 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
1927                                 self.window.blit(s, targets[i][0:2])
1928                                 
1929         
1930                         pygame.display.flip()
1931
1932                         for event in pygame.event.get():
1933                                 if event.type == pygame.QUIT:
1934                                         return None
1935                                 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
1936                                         for i in range(len(targets)):
1937                                                 t = targets[i]
1938                                                 if event.pos[0] > t[0] and event.pos[0] < t[2]:
1939                                                         if event.pos[1] > t[1] and event.pos[1] < t[3]:
1940                                                                 return i
1941                                                 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
1942                 
1943
1944         # Function to pick players in a nice GUI way
1945         def SelectPlayers(self, players = []):
1946
1947
1948                 #print "SelectPlayers called"
1949                 
1950                 missing = ["white", "black"]
1951                 for p in players:
1952                         missing.remove(p.colour)
1953
1954                 for colour in missing:
1955                         
1956                         
1957                         choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
1958                         if choice == 0:
1959                                 players.append(HumanPlayer("human", colour))
1960                         elif choice == 1:
1961                                 import inspect
1962                                 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
1963                                 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
1964                                 internal_agents.remove(('InternalAgent', InternalAgent)) 
1965                                 if len(internal_agents) > 0:
1966                                         choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
1967                                 else:
1968                                         choice2 = 1
1969
1970                                 if choice2 == 0:
1971                                         agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
1972                                         players.append(agent[1](agent[0], colour))                                      
1973                                 elif choice2 == 1:
1974                                         try:
1975                                                 import Tkinter
1976                                                 from tkFileDialog import askopenfilename
1977                                                 root = Tkinter.Tk() # Need a root to make Tkinter behave
1978                                                 root.withdraw() # Some sort of magic incantation
1979                                                 path = askopenfilename(parent=root, initialdir="../agents",title=
1980 'Choose an agent.')
1981                                                 if path == "":
1982                                                         return self.SelectPlayers()
1983                                                 players.append(make_player(path, colour))       
1984                                         except:
1985                                                 
1986                                                 p = None
1987                                                 while p == None:
1988                                                         self.board.display_grid(self.window, self.grid_sz)
1989                                                         pygame.display.flip()
1990                                                         path = self.getstr(prompt = "Enter path:")
1991                                                         if path == None:
1992                                                                 return None
1993         
1994                                                         if path == "":
1995                                                                 return self.SelectPlayers()
1996         
1997                                                         try:
1998                                                                 p = make_player(path, colour)
1999                                                         except:
2000                                                                 self.board.display_grid(self.window, self.grid_sz)
2001                                                                 pygame.display.flip()
2002                                                                 self.message("Invalid path!")
2003                                                                 time.sleep(1)
2004                                                                 p = None
2005                                                 players.append(p)
2006                         elif choice == 2:
2007                                 address = ""
2008                                 while address == "":
2009                                         self.board.display_grid(self.window, self.grid_sz)
2010                                         
2011                                         address = self.getstr(prompt = "Address? (leave blank for server)")
2012                                         if address == None:
2013                                                 return None
2014                                         if address == "":
2015                                                 address = None
2016                                                 continue
2017                                         try:
2018                                                 map(int, address.split("."))
2019                                         except:
2020                                                 self.board.display_grid(self.window, self.grid_sz)
2021                                                 self.message("Invalid IPv4 address!")
2022                                                 address = ""
2023
2024                                 players.append(NetworkReceiver(colour, address))
2025                         else:
2026                                 return None
2027                 #print str(self) + ".SelectPlayers returns " + str(players)
2028                 return players
2029                         
2030                                 
2031                         
2032 # --- graphics.py --- #
2033 #!/usr/bin/python -u
2034
2035 # Do you know what the -u does? It unbuffers stdin and stdout
2036 # I can't remember why, but last year things broke without that
2037
2038 """
2039         UCC::Progcomp 2013 Quantum Chess game
2040         @author Sam Moore [SZM] "matches"
2041         @copyright The University Computer Club, Incorporated
2042                 (ie: You can copy it for not for profit purposes)
2043 """
2044
2045 # system python modules or whatever they are called
2046 import sys
2047 import os
2048 import time
2049
2050 turn_delay = 0.5
2051 [game, graphics] = [None, None]
2052
2053 def make_player(name, colour):
2054         if name[0] == '@':
2055                 if name[1:] == "human":
2056                         return HumanPlayer(name, colour)
2057                 s = name[1:].split(":")
2058                 if s[0] == "network":
2059                         address = None
2060                         if len(s) > 1:
2061                                 address = s[1]
2062                         return NetworkReceiver(colour, address)
2063                 if s[0] == "internal":
2064
2065                         import inspect
2066                         internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2067                         internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2068                         internal_agents.remove(('InternalAgent', InternalAgent)) 
2069                         
2070                         if len(s) != 2:
2071                                 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
2072                                 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2073                                 return None
2074
2075                         for a in internal_agents:
2076                                 if s[1] == a[0]:
2077                                         return a[1](name, colour)
2078                         
2079                         sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
2080                         sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2081                         return None
2082                         
2083
2084         else:
2085                 return ExternalAgent(name, colour)
2086                         
2087
2088
2089 # The main function! It does the main stuff!
2090 def main(argv):
2091
2092         # Apparently python will silently treat things as local unless you do this
2093         # Anyone who says "You should never use a global variable" can die in a fire
2094         global game
2095         global graphics
2096         
2097         global turn_delay
2098         global agent_timeout
2099         global log_file
2100         global src_file
2101         global graphics_enabled
2102         global always_reveal_states
2103
2104         max_lines = None
2105         src_file = None
2106         
2107         style = "quantum"
2108         colour = "white"
2109
2110         # Get the important warnings out of the way
2111         if platform.system() == "Windows":
2112                 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
2113                 if platform.release() == "Vista":
2114                         sys.stderr.write(sys.argv[0] + " : God help you.\n")
2115         
2116
2117         players = []
2118         i = 0
2119         while i < len(argv)-1:
2120                 i += 1
2121                 arg = argv[i]
2122                 if arg[0] != '-':
2123                         p = make_player(arg, colour)
2124                         if not isinstance(p, Player):
2125                                 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
2126                                 return 100
2127                         players.append(p)
2128                         if colour == "white":
2129                                 colour = "black"
2130                         elif colour == "black":
2131                                 pass
2132                         else:
2133                                 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
2134                         continue
2135
2136                 # Option parsing goes here
2137                 if arg[1] == '-' and arg[2:] == "classical":
2138                         style = "classical"
2139                 elif arg[1] == '-' and arg[2:] == "quantum":
2140                         style = "quantum"
2141                 elif arg[1] == '-' and arg[2:] == "reveal":
2142                         always_reveal_states = True
2143                 elif (arg[1] == '-' and arg[2:] == "graphics"):
2144                         graphics_enabled = not graphics_enabled
2145                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
2146                         # Load game from file
2147                         if len(arg[2:].split("=")) == 1:
2148                                 src_file = sys.stdin
2149                         else:
2150                                 f = arg[2:].split("=")[1]
2151                                 if f[0] == '@':
2152                                         src_file = HttpReplay("http://" + f.split(":")[0][1:])
2153                                 else:
2154                                         src_file = open(f.split(":")[0], "r", 0)
2155
2156                                 if len(f.split(":")) == 2:
2157                                         max_lines = int(f.split(":")[1])
2158
2159                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
2160                         # Log file
2161                         if len(arg[2:].split("=")) == 1:
2162                                 log_file = sys.stdout
2163                         else:
2164                                 f = arg[2:].split("=")[1]
2165                                 if f[0] == '@':
2166                                         log_file = HttpLog(f[1:])
2167                                 else:
2168                                         log_file = LogFile(f)
2169                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
2170                         # Delay
2171                         if len(arg[2:].split("=")) == 1:
2172                                 turn_delay = 0
2173                         else:
2174                                 turn_delay = float(arg[2:].split("=")[1])
2175
2176                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
2177                         # Timeout
2178                         if len(arg[2:].split("=")) == 1:
2179                                 agent_timeout = -1
2180                         else:
2181                                 agent_timeout = float(arg[2:].split("=")[1])
2182                                 
2183                 elif (arg[1] == '-' and arg[2:] == "help"):
2184                         # Help
2185                         os.system("less data/help.txt") # The best help function
2186                         return 0
2187
2188
2189         # Create the board
2190         
2191         # Construct a GameThread! Make it global! Damn the consequences!
2192                         
2193         if src_file != None:
2194                 # Hack to stop ReplayThread from exiting
2195                 #if len(players) == 0:
2196                 #       players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
2197
2198                 # Normally the ReplayThread exits if there are no players
2199                 # TODO: Decide which behaviour to use, and fix it
2200                 end = (len(players) == 0)
2201                 if end:
2202                         players = [Player("dummy", "white"), Player("dummy", "black")]
2203                 elif len(players) != 2:
2204                         sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2205                         if graphics_enabled:
2206                                 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
2207                         return 44
2208                 game = ReplayThread(players, src_file, end=end, max_lines=max_lines)
2209         else:
2210                 board = Board(style)
2211                 game = GameThread(board, players) 
2212
2213
2214
2215         # Initialise GUI
2216         if graphics_enabled == True:
2217                 try:
2218                         graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
2219
2220                 except Exception,e:
2221                         graphics = None
2222                         sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
2223                         graphics_enabled = False
2224
2225         # If there are no players listed, display a nice pretty menu
2226         if len(players) != 2:
2227                 if graphics != None:
2228                         players = graphics.SelectPlayers(players)
2229                 else:
2230                         sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2231                         return 44
2232
2233         # If there are still no players, quit
2234         if players == None or len(players) != 2:
2235                 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
2236                 return 45
2237
2238
2239         # Wrap NetworkSender players around original players if necessary
2240         for i in range(len(players)):
2241                 if isinstance(players[i], NetworkReceiver):
2242                         players[i].board = board # Network players need direct access to the board
2243                         for j in range(len(players)):
2244                                 if j == i:
2245                                         continue
2246                                 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
2247                                         continue
2248                                 players[j] = NetworkSender(players[j], players[i].address)
2249                                 players[j].board = board
2250
2251         # Connect the networked players
2252         for p in players:
2253                 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
2254                         if graphics != None:
2255                                 graphics.board.display_grid(graphics.window, graphics.grid_sz)
2256                                 graphics.message("Connecting to " + p.colour + " player...")
2257                         p.connect()
2258
2259         
2260         # If using windows, select won't work; use horrible TimeoutPlayer hack
2261         if agent_timeout > 0:
2262                 if platform.system() == "Windows":
2263                         for i in range(len(players)):
2264                                 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
2265                                         players[i] = TimeoutPlayer(players[i], agent_timeout)
2266
2267                 else:
2268                         warned = False
2269                         # InternalAgents get wrapped to an ExternalAgent when there is a timeout
2270                         # This is not confusing at all.
2271                         for i in range(len(players)):
2272                                 if isinstance(players[i], InternalAgent):
2273                                                 players[i] = ExternalWrapper(players[i])
2274
2275
2276                 
2277
2278
2279
2280
2281         log_init(game.board, players)
2282         
2283         
2284         if graphics != None:
2285                 game.start() # This runs in a new thread
2286                 graphics.run()
2287                 if game.is_alive():
2288                         game.join()
2289         
2290
2291                 error = game.error + graphics.error
2292         else:
2293                 game.run()
2294                 error = game.error
2295         
2296
2297         if log_file != None and log_file != sys.stdout:
2298                 log_file.write("# EOF\n")
2299                 log_file.close()
2300
2301         if src_file != None and src_file != sys.stdin:
2302                 src_file.close()
2303
2304         return error
2305
2306 # This is how python does a main() function...
2307 if __name__ == "__main__":
2308         try:
2309                 sys.exit(main(sys.argv))
2310         except KeyboardInterrupt:
2311                 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
2312                 if isinstance(graphics, StoppableThread):
2313                         graphics.stop()
2314                         graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
2315
2316                 if isinstance(game, StoppableThread):
2317                         game.stop()
2318                         if game.is_alive():
2319                                 game.join()
2320
2321                 sys.exit(102)
2322
2323 # --- main.py --- #
2324 # EOF - created from make on Wed Jan 30 17:03:00 WST 2013

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