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

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