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}
8 # Class to represent a quantum chess 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)
19 self.last_state = None
21 self.move_pattern = None
23 self.possible_moves = None
26 def init_from_copy(self, c):
27 self.colour = c.colour
30 self.types = c.types[:]
31 self.current_type = c.current_type
32 self.choice = c.choice
34 self.last_state = None
35 self.move_pattern = None
39 # Make a string for the piece (used for debug)
41 return str(self.colour) + " " + str(self.current_type) + " " + str(self.types) + " at " + str(self.x) + ","+str(self.y)
43 # Draw the piece in a pygame surface
44 def draw(self, window, grid_sz = [80,80], style="quantum"):
46 # First draw the image corresponding to self.current_type
47 img = images[self.colour][self.current_type]
49 if style == "classical":
50 offset = [-rect.width/2, -rect.height/2]
52 offset = [-rect.width/2,-3*rect.height/4]
53 window.blit(img, (self.x * grid_sz[0] + grid_sz[0]/2 + offset[0], self.y * grid_sz[1] + grid_sz[1]/2 + offset[1]))
56 if style == "classical":
59 # Draw the two possible types underneath the current_type image
60 for i in range(len(self.types)):
61 if always_reveal_states == True or self.types[i][0] != '?':
62 img = small_images[self.colour][self.types[i]]
64 img = small_images[self.colour]["unknown"] # If the type hasn't been revealed, show a placeholder
68 offset = [-rect.width/2,-rect.height/2]
71 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 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 window.blit(img, target) # Blit shit
77 # Collapses the wave function!
79 if self.current_type == "unknown" or not self.choice in [0,1]:
80 self.choice = random.randint(0,1)
81 if self.types[self.choice][0] == '?':
82 self.types[self.choice] = self.types[self.choice][1:]
83 self.current_type = self.types[self.choice]
86 # Uncollapses (?) the wave function!
88 #print "Deselect called"
89 if (self.x + self.y) % 2 != 0:
90 if (self.types[0] != self.types[1]) or (self.types[0][0] == '?' or self.types[1][0] == '?'):
91 self.current_type = "unknown"
94 self.choice = 0 # Both the two types are the same
96 # The sad moment when you realise that you do not understand anything about a subject you studied for 4 years...
98 [w,h] = [8,8] # Width and height of board(s)
100 always_reveal_states = False
102 # Class to represent a quantum chess board
104 # Initialise; if master=True then the secondary piece types are assigned
105 # Otherwise, they are left as unknown
106 # So you can use this class in Agent programs, and fill in the types as they are revealed
107 def __init__(self, style="agent"):
109 self.pieces = {"white" : [], "black" : []}
110 self.grid = [[None] * w for _ in range(h)] # 2D List (you can get arrays in python, somehow, but they scare me)
111 self.unrevealed_types = {"white" : piece_types.copy(), "black" : piece_types.copy()}
112 self.king = {"white" : None, "black" : None} # We need to keep track of the king, because he is important
113 self.max_moves = None
116 for c in ["black", "white"]:
117 del self.unrevealed_types[c]["unknown"]
122 # Add all the pieces with known primary types
123 for i in range(0, 2):
125 s = ["black", "white"][i]
129 c.append(Piece(s, 0, y, ["rook"]))
130 c.append(Piece(s, 1, y, ["knight"]))
131 c.append(Piece(s, 2, y, ["bishop"]))
132 k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
133 k.current_type = "king"
136 c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
137 c.append(Piece(s, 5, y, ["bishop"]))
138 c.append(Piece(s, 6, y, ["knight"]))
139 c.append(Piece(s, 7, y, ["rook"]))
147 for x in range(0, w):
148 c.append(Piece(s, x, y, ["pawn"]))
151 types_left.update(piece_types)
152 del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
153 del types_left["unknown"] # We certainly don't want these!
156 self.grid[piece.x][piece.y] = piece
158 if len(piece.types) > 1:
160 if style == "agent": # Assign placeholder "unknown" secondary type
161 piece.types.append("unknown")
164 elif style == "quantum":
165 # The master allocates the secondary types
166 choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
167 types_left[choice] -= 1
168 if types_left[choice] <= 0:
169 del types_left[choice]
170 piece.types.append('?' + choice)
171 elif style == "classical":
172 piece.types.append(piece.types[0])
173 piece.current_type = piece.types[0]
177 newboard = Board(master = False)
178 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
179 mypieces = self.pieces["white"] + self.pieces["black"]
181 for i in range(len(mypieces)):
182 newpieces[i].init_from_copy(mypieces[i])
184 # Reset the board from a string
185 def reset_board(self, s):
186 self.pieces = {"white" : [], "black" : []}
187 self.king = {"white" : None, "black" : None}
188 self.grid = [[None] * w for _ in range(h)]
191 self.grid[x][y] = None
193 for line in s.split("\n"):
199 tokens = line.split(" ")
200 [x, y] = map(int, tokens[len(tokens)-1].split(","))
201 current_type = tokens[1]
202 types = map(lambda e : e.strip(" '[],"), line.split('[')[1].split(']')[0].split(','))
204 target = Piece(tokens[0], x, y, types)
205 target.current_type = current_type
208 target.choice = types.index(current_type)
212 self.pieces[tokens[0]].append(target)
213 if target.current_type == "king":
214 self.king[tokens[0]] = target
216 self.grid[x][y] = target
219 def display_grid(self, window = None, grid_sz = [80,80]):
221 return # I was considering implementing a text only display, then I thought "Fuck that"
223 # The indentation is getting seriously out of hand...
224 for x in range(0, w):
225 for y in range(0, h):
227 c = pygame.Color(200,200,200)
229 c = pygame.Color(64,64,64)
230 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
232 def display_pieces(self, window = None, grid_sz = [80,80]):
235 for p in self.pieces["white"] + self.pieces["black"]:
236 p.draw(window, grid_sz, self.style)
238 # Draw the board in a pygame window
239 def display(self, window = None):
240 self.display_grid(window)
241 self.display_pieces(window)
249 if self.grid[x][y] == None:
251 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
252 raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
254 # Select a piece on the board (colour is the colour of whoever is doing the selecting)
255 def select(self, x,y, colour=None):
256 if not self.on_board(x, y): # Get on board everyone!
257 raise Exception("BOUNDS")
259 piece = self.grid[x][y]
261 raise Exception("EMPTY")
263 if colour != None and piece.colour != colour:
264 raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
266 # I'm not quite sure why I made this return a string, but screw logical design
267 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
270 # Update the board when a piece has been selected
271 # "type" is apparently reserved, so I'll use "state"
272 def update_select(self, x, y, type_index, state):
273 piece = self.grid[x][y]
274 if piece.types[type_index] == "unknown":
275 if not state in self.unrevealed_types[piece.colour].keys():
276 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
277 self.unrevealed_types[piece.colour][state] -= 1
278 if self.unrevealed_types[piece.colour][state] <= 0:
279 del self.unrevealed_types[piece.colour][state]
281 piece.types[type_index] = state
282 piece.current_type = state
284 if len(self.possible_moves(piece)) <= 0:
285 piece.deselect() # Piece can't move; deselect it
287 # Piece needs to recalculate moves
288 piece.possible_moves = None
290 # Update the board when a piece has been moved
291 def update_move(self, x, y, x2, y2):
293 piece = self.grid[x][y]
294 #print "Moving " + str(x) + "," + str(y) + " to " + str(x2) + "," + str(y2) + "; possible_moves are " + str(self.possible_moves(piece))
296 if not [x2,y2] in self.possible_moves(piece):
297 raise Exception("ILLEGAL move " + str(x2)+","+str(y2))
299 self.grid[x][y] = None
300 taken = self.grid[x2][y2]
302 if taken.current_type == "king":
303 self.king[taken.colour] = None
304 self.pieces[taken.colour].remove(taken)
305 self.grid[x2][y2] = piece
309 # If the piece is a pawn, and it reaches the final row, it becomes a queen
310 # I know you are supposed to get a choice
311 # But that would be effort
312 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
313 if self.style == "classical":
314 piece.types[0] = "queen"
315 piece.types[1] = "queen"
317 piece.types[piece.choice] = "queen"
318 piece.current_type = "queen"
320 piece.deselect() # Uncollapse (?) the wavefunction!
323 # All other pieces need to recalculate moves
324 for p in self.pieces["white"] + self.pieces["black"]:
325 p.possible_moves = None
329 # Update the board from a string
330 # Guesses what to do based on the format of the string
331 def update(self, result):
332 #print "Update called with \"" + str(result) + "\""
333 # String always starts with 'x y'
335 s = result.split(" ")
336 [x,y] = map(int, s[0:2])
338 raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
340 piece = self.grid[x][y]
342 raise Exception("EMPTY")
344 # If a piece is being moved, the third token is '->'
345 # We could get away with just using four integers, but that wouldn't look as cool
347 # Last two tokens are the destination
349 [x2,y2] = map(int, s[3:])
351 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
353 # Move the piece (take opponent if possible)
354 self.update_move(x, y, x2, y2)
357 # Otherwise we will just assume a piece has been selected
359 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
360 state = s[3] # The last token is a string identifying the type
362 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
365 self.update_select(x, y, type_index, state)
369 # Gets each piece that could reach the given square and the probability that it could reach that square
370 # Will include allied pieces that defend the attacker
371 def coverage(self, x, y, colour = None, reject_allied = True):
375 pieces = self.pieces["white"] + self.pieces["black"]
377 pieces = self.pieces[colour]
380 prob = self.probability_grid(p, reject_allied)[x][y]
382 result.update({p : prob})
391 # Associates each square with a probability that the piece could move into it
392 # Look, I'm doing all the hard work for you here...
393 def probability_grid(self, p, reject_allied = True):
395 result = [[0.0] * w for _ in range(h)]
396 if not isinstance(p, Piece):
399 if p.current_type != "unknown":
400 #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
401 for point in self.possible_moves(p, reject_allied):
402 result[point[0]][point[1]] = 1.0
406 for i in range(len(p.types)):
409 if t == "unknown" or p.types[i][0] == '?':
411 for t2 in self.unrevealed_types[p.colour].keys():
412 total_types += self.unrevealed_types[p.colour][t2]
414 for t2 in self.unrevealed_types[p.colour].keys():
415 prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
417 for point in self.possible_moves(p, reject_allied):
418 result[point[0]][point[1]] += prob2 * prob
422 for point in self.possible_moves(p, reject_allied):
423 result[point[0]][point[1]] += prob
426 p.current_type = "unknown"
429 def prob_is_type(self, p, state):
432 for i in range(len(p.types)):
437 if t == "unknown" or p.types[i][0] == '?':
439 for t2 in self.unrevealed_types[p.colour].keys():
440 total_prob += self.unrevealed_types[p.colour][t2]
441 for t2 in self.unrevealed_types[p.colour].keys():
443 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
447 # Get all squares that the piece could move into
448 # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
449 # reject_allied indicates whether squares occupied by allied pieces will be removed
450 # (set to false to check for defense)
451 def possible_moves(self, p, reject_allied = True, state=None):
453 raise Exception("SANITY: No piece")
457 if state != None and state != p.current_type:
458 old_type = p.current_type
459 p.current_type = state
460 result = self.possible_moves(p, reject_allied, state=None)
461 p.current_type = old_type
464 if p.possible_moves != None:
465 return p.possible_moves
472 if p.current_type == "unknown":
473 raise Exception("SANITY: Piece state unknown")
474 # The below commented out code causes things to break badly
479 # result += self.possible_moves(p)
480 #p.current_type = "unknown"
483 if p.current_type == "king":
484 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]]
485 elif p.current_type == "queen":
486 for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
487 result += self.scan(p.x, p.y, d[0], d[1])
488 elif p.current_type == "bishop":
489 for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
490 result += self.scan(p.x, p.y, d[0], d[1])
491 elif p.current_type == "rook":
492 for d in [[-1,0],[1,0],[0,-1],[0,1]]:
493 result += self.scan(p.x, p.y, d[0], d[1])
494 elif p.current_type == "knight":
495 # I would use two lines, but I'm not sure how python likes that
496 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]]
497 elif p.current_type == "pawn":
498 if p.colour == "white":
500 # Pawn can't move forward into occupied square
501 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
502 result = [[p.x,p.y-1]]
503 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
504 if not self.on_board(f[0], f[1]):
506 if self.grid[f[0]][f[1]] != None: # Pawn can take diagonally
509 # Slightly embarrassing if the pawn jumps over someone on its first move...
510 if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
511 result.append([p.x, p.y-2])
513 # Vice versa for the black pawn
514 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
515 result = [[p.x,p.y+1]]
517 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
518 if not self.on_board(f[0], f[1]):
520 if self.grid[f[0]][f[1]] != None:
521 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
524 if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
525 result.append([p.x, p.y+2])
527 #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
529 # Remove illegal moves
530 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
531 for point in result[:]:
533 if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
534 result.remove(point) # Remove locations outside the board
536 g = self.grid[point[0]][point[1]]
538 if g != None and (g.colour == p.colour and reject_allied == True):
539 result.remove(point) # Remove allied pieces
543 p.possible_moves = result
547 # Scans in a direction until it hits a piece, returns all squares in the line
548 # (includes the final square (which contains a piece), but not the original square)
549 def scan(self, x, y, vx, vy):
557 if not self.on_board(xx, yy):
561 g = self.grid[xx][yy]
567 # Returns "white", "black" or "DRAW" if the game should end
568 def end_condition(self):
569 if self.king["white"] == None:
570 if self.king["black"] == None:
571 return "DRAW" # This shouldn't happen
573 elif self.king["black"] == None:
575 elif len(self.pieces["white"]) == 1 and len(self.pieces["black"]) == 1:
577 elif self.max_moves != None and self.moves > self.max_moves:
582 # I typed the full statement about 30 times before writing this function...
583 def on_board(self, x, y):
584 return (x >= 0 and x < w) and (y >= 0 and y < h)
586 # Pushes a move temporarily
587 def push_move(self, piece, x, y):
588 target = self.grid[x][y]
589 self.move_stack.append([piece, target, piece.x, piece.y, x, y])
590 [piece.x, piece.y] = [x, y]
591 self.grid[x][y] = piece
592 self.grid[piece.x][piece.y] = None
594 for p in self.pieces["white"] + self.pieces["black"]:
595 p.possible_moves = None
599 #print str(self.move_stack)
600 [piece, target, x1, y1, x2, y2] = self.move_stack[len(self.move_stack)-1]
601 self.move_stack = self.move_stack[:-1]
604 self.grid[x1][y1] = piece
608 self.grid[x2][y2] = target
610 for p in self.pieces["white"] + self.pieces["black"]:
611 p.possible_moves = None
619 agent_timeout = -1.0 # Timeout in seconds for AI players to make moves
620 # WARNING: Won't work for windows based operating systems
622 if platform.system() == "Windows":
623 agent_timeout = -1 # Hence this
625 # A player who can't play
627 def __init__(self, name, colour):
631 def update(self, result):
634 def reset_board(self, s):
637 # Player that runs from another process
638 class ExternalAgent(Player):
641 def __init__(self, name, colour):
642 Player.__init__(self, name, colour)
643 self.p = subprocess.Popen(name,bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,universal_newlines=True)
645 self.send_message(colour)
647 def send_message(self, s):
648 if agent_timeout > 0.0:
649 ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
651 ready = [self.p.stdin]
652 if self.p.stdin in ready:
653 #sys.stderr.write("Writing \'" + s + "\' to " + str(self.p) + "\n")
655 self.p.stdin.write(s + "\n")
657 raise Exception("UNRESPONSIVE")
659 raise Exception("TIMEOUT")
661 def get_response(self):
662 if agent_timeout > 0.0:
663 ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
665 ready = [self.p.stdout]
666 if self.p.stdout in ready:
667 #sys.stderr.write("Reading from " + str(self.p) + " 's stdout...\n")
669 result = self.p.stdout.readline().strip(" \t\r\n")
670 #sys.stderr.write("Read \'" + result + "\' from " + str(self.p) + "\n")
672 except: # Exception, e:
673 raise Exception("UNRESPONSIVE")
675 raise Exception("TIMEOUT")
679 self.send_message("SELECTION?")
680 line = self.get_response()
683 m = re.match("\s*(\d+)\s+(\d+)\s*", line)
684 result = map(int, [m.group(1), m.group(2)])
686 raise Exception("GIBBERISH \"" + str(line) + "\"")
689 def update(self, result):
690 #print "Update " + str(result) + " called for AgentPlayer"
691 self.send_message(result)
696 self.send_message("MOVE?")
697 line = self.get_response()
700 m = re.match("\s*(\d+)\s+(\d+)\s*", line)
701 result = map(int, [m.group(1), m.group(2)])
704 raise Exception("GIBBERISH \"" + str(line) + "\"")
707 def reset_board(self, s):
708 self.send_message("BOARD")
709 for line in s.split("\n"):
710 self.send_message(line.strip(" \r\n"))
711 self.send_message("END BOARD")
713 def quit(self, final_result):
715 self.send_message("QUIT " + final_result)
719 # So you want to be a player here?
720 class HumanPlayer(Player):
721 def __init__(self, name, colour):
722 Player.__init__(self, name, colour)
724 # Select your preferred account
726 if isinstance(graphics, GraphicsThread):
727 # Basically, we let the graphics thread do some shit and then return that information to the game thread
728 graphics.cond.acquire()
729 # We wait for the graphics thread to select a piece
730 while graphics.stopped() == False and graphics.state["select"] == None:
731 graphics.cond.wait() # The difference between humans and machines is that humans sleep
732 select = graphics.state["select"]
735 graphics.cond.release()
736 if graphics.stopped():
738 return [select.x, select.y]
740 # Since I don't display the board in this case, I'm not sure why I filled it in...
742 sys.stdout.write("SELECTION?\n")
744 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
746 sys.stderr.write("ILLEGAL GIBBERISH\n")
748 # It's your move captain
750 if isinstance(graphics, GraphicsThread):
751 graphics.cond.acquire()
752 while graphics.stopped() == False and graphics.state["dest"] == None:
754 graphics.cond.release()
756 return graphics.state["dest"]
760 sys.stdout.write("MOVE?\n")
762 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
764 sys.stderr.write("ILLEGAL GIBBERISH\n")
767 # Are you sure you want to quit?
768 def quit(self, final_result):
770 sys.stdout.write("QUIT " + final_result + "\n")
772 # Completely useless function
773 def update(self, result):
774 if isinstance(graphics, GraphicsThread):
777 sys.stdout.write(result + "\n")
780 # Default internal player (makes random moves)
781 class InternalAgent(Player):
782 def __init__(self, name, colour):
783 Player.__init__(self, name, colour)
786 self.board = Board(style = "agent")
790 def update(self, result):
792 self.board.update(result)
795 def reset_board(self, s):
796 self.board.reset_board(s)
798 def quit(self, final_result):
801 class AgentRandom(InternalAgent):
802 def __init__(self, name, colour):
803 InternalAgent.__init__(self, name, colour)
807 self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
809 # Check that the piece has some possibility to move
810 tmp = self.choice.current_type
811 if tmp == "unknown": # For unknown pieces, try both types
812 for t in self.choice.types:
815 self.choice.current_type = t
816 all_moves += self.board.possible_moves(self.choice)
818 all_moves = self.board.possible_moves(self.choice)
819 self.choice.current_type = tmp
820 if len(all_moves) > 0:
822 return [self.choice.x, self.choice.y]
825 moves = self.board.possible_moves(self.choice)
826 move = moves[random.randint(0, len(moves)-1)]
830 # Terrible, terrible hacks
832 def run_agent(agent):
833 #sys.stderr.write(sys.argv[0] + " : Running agent " + str(agent) + "\n")
835 line = sys.stdin.readline().strip(" \r\n")
836 if line == "SELECTION?":
837 #sys.stderr.write(sys.argv[0] + " : Make selection\n")
838 [x,y] = agent.select() # Gets your agent's selection
839 #sys.stderr.write(sys.argv[0] + " : Selection was " + str(agent.choice) + "\n")
840 sys.stdout.write(str(x) + " " + str(y) + "\n")
841 elif line == "MOVE?":
842 #sys.stderr.write(sys.argv[0] + " : Make move\n")
843 [x,y] = agent.get_move() # Gets your agent's move
844 sys.stdout.write(str(x) + " " + str(y) + "\n")
845 elif line.split(" ")[0] == "QUIT":
846 #sys.stderr.write(sys.argv[0] + " : Quitting\n")
847 agent.quit(" ".join(line.split(" ")[1:])) # Quits the game
849 elif line.split(" ")[0] == "BOARD":
851 line = sys.stdin.readline().strip(" \r\n")
852 while line != "END BOARD":
854 line = sys.stdin.readline().strip(" \r\n")
855 agent.board.reset_board(s)
858 agent.update(line) # Updates agent.board
864 class ExternalWrapper(ExternalAgent):
865 def __init__(self, agent):
866 run = "python -u -c \"import sys;import os;from qchess import *;agent = " + agent.__class__.__name__ + "('" + agent.name + "','"+agent.colour+"');sys.stdin.readline();sys.exit(run_agent(agent))\""
868 ExternalAgent.__init__(self, run, agent.colour)
872 # --- player.py --- #
876 class AgentBishop(AgentRandom): # Inherits from AgentRandom (in qchess)
877 def __init__(self, name, colour):
878 InternalAgent.__init__(self, name, colour)
879 self.value = {"pawn" : 1, "bishop" : 3, "knight" : 3, "rook" : 5, "queen" : 9, "king" : 100, "unknown" : 4}
881 self.aggression = 2.0 # Multiplier for scoring due to aggressive actions
882 self.defence = 1.0 # Multiplier for scoring due to defensive actions
884 self.depth = 0 # Current depth
885 self.max_depth = 2 # Recurse this many times (for some reason, makes more mistakes when this is increased???)
886 self.recurse_for = -1 # Recurse for the best few moves each times (less than 0 = all moves)
888 for p in self.board.pieces["white"] + self.board.pieces["black"]:
890 p.selected_moves = None
894 def get_value(self, piece):
897 return float(self.value[piece.types[0]] + self.value[piece.types[1]]) / 2.0
899 # Score possible moves for the piece
901 def prioritise_moves(self, piece):
903 #sys.stderr.write(sys.argv[0] + " : " + str(self) + " prioritise called for " + str(piece) + "\n")
907 grid = self.board.probability_grid(piece)
908 #sys.stderr.write("\t Probability grid " + str(grid) + "\n")
912 if grid[x][y] < 0.3: # Throw out moves with < 30% probability
913 #sys.stderr.write("\tReject " + str(x) + "," + str(y) + " (" + str(grid[x][y]) + ")\n")
916 target = self.board.grid[x][y]
921 # Get total probability that the move is protected
922 self.board.push_move(piece, x, y)
926 defenders = self.board.coverage(x, y, piece.colour, reject_allied = False)
928 for d in defenders.keys():
929 d_prob += defenders[d]
930 if len(defenders.keys()) > 0:
931 d_prob /= float(len(defenders.keys()))
936 # Get total probability that the move is threatened
937 attackers = self.board.coverage(x, y, opponent(piece.colour), reject_allied = False)
939 for a in attackers.keys():
940 a_prob += attackers[a]
941 if len(attackers.keys()) > 0:
942 a_prob /= float(len(attackers.keys()))
947 self.board.pop_move()
952 value = self.aggression * (1.0 + d_prob) * self.get_value(target) - self.defence * (1.0 - d_prob) * a_prob * self.get_value(piece)
954 # Adjust score based on movement of piece out of danger
955 attackers = self.board.coverage(piece.x, piece.y, opponent(piece.colour))
957 for a in attackers.keys():
958 s_prob += attackers[a]
959 if len(attackers.keys()) > 0:
960 s_prob /= float(len(attackers.keys()))
964 value += self.defence * s_prob * self.get_value(piece)
966 # Adjust score based on probability that the move is actually possible
967 moves.append([[x, y], grid[x][y] * value])
969 moves.sort(key = lambda e : e[1], reverse = True)
970 #sys.stderr.write(sys.argv[0] + ": Moves for " + str(piece) + " are " + str(moves) + "\n")
972 piece.last_moves = moves
973 piece.selected_moves = None
980 def select_best(self, colour):
984 for p in self.board.pieces[colour]:
985 self.choice = p # Temporarily pick that piece
986 m = self.prioritise_moves(p)
988 all_moves.update({p : m[0]})
990 if len(all_moves.items()) <= 0:
994 opts = all_moves.items()
995 opts.sort(key = lambda e : e[1][1], reverse = True)
997 if self.depth >= self.max_depth:
1001 if self.recurse_for >= 0:
1002 opts = opts[0:self.recurse_for]
1003 #sys.stderr.write(sys.argv[0] + " : Before recurse, options are " + str(opts) + "\n")
1005 # Take the best few moves, and recurse
1006 for choice in opts[0:self.recurse_for]:
1007 [xx,yy] = [choice[0].x, choice[0].y] # Remember position
1008 [nx,ny] = choice[1][0] # Target
1009 [choice[0].x, choice[0].y] = [nx, ny] # Set position
1010 target = self.board.grid[nx][ny] # Remember piece in spot
1011 self.board.grid[xx][yy] = None # Remove piece
1012 self.board.grid[nx][ny] = choice[0] # Replace with moving piece
1015 best_enemy_move = self.select_best(opponent(choice[0].colour))
1016 choice[1][1] -= best_enemy_move[1][1] / float(self.depth + 1.0)
1018 [choice[0].x, choice[0].y] = [xx, yy] # Restore position
1019 self.board.grid[nx][ny] = target # Restore taken piece
1020 self.board.grid[xx][yy] = choice[0] # Restore moved piece
1024 opts.sort(key = lambda e : e[1][1], reverse = True)
1025 #sys.stderr.write(sys.argv[0] + " : After recurse, options are " + str(opts) + "\n")
1028 return list(opts[0])
1032 # Returns [x,y] of selected piece
1034 #sys.stderr.write("Getting choice...")
1035 self.choice = self.select_best(self.colour)[0]
1037 #sys.stderr.write(" Done " + str(self.choice)+"\n")
1038 return [self.choice.x, self.choice.y]
1040 # Returns [x,y] of square to move selected piece into
1042 #sys.stderr.write("Choice is " + str(self.choice) + "\n")
1043 self.choice.selected_moves = self.choice.last_moves
1044 moves = self.prioritise_moves(self.choice)
1048 return AgentRandom.get_move(self)
1050 # --- agent_bishop.py --- #
1051 import multiprocessing
1053 # Hacky alternative to using select for timing out players
1055 # WARNING: Do not wrap around HumanPlayer or things breakify
1056 # WARNING: Do not use in general or things breakify
1058 class Sleeper(multiprocessing.Process):
1059 def __init__(self, timeout):
1060 multiprocessing.Process.__init__(self)
1061 self.timeout = timeout
1064 time.sleep(self.timeout)
1067 class Worker(multiprocessing.Process):
1068 def __init__(self, function, args, q):
1069 multiprocessing.Process.__init__(self)
1070 self.function = function
1075 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args)
1076 self.q.put(self.function(*self.args))
1080 def TimeoutFunction(function, args, timeout):
1081 q = multiprocessing.Queue()
1082 w = Worker(function, args, q)
1083 s = Sleeper(timeout)
1086 while True: # Busy loop of crappyness
1087 if not w.is_alive():
1091 #print "TimeoutFunction gets " + str(result)
1093 elif not s.is_alive():
1096 raise Exception("TIMEOUT")
1101 # A player that wraps another player and times out its moves
1103 # A (crappy) alternative to the use of select()
1104 class TimeoutPlayer(Player):
1105 def __init__(self, base_player, timeout):
1106 Player.__init__(self, base_player.name, base_player.colour)
1107 self.base_player = base_player
1108 self.timeout = timeout
1111 return TimeoutFunction(self.base_player.select, [], self.timeout)
1115 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
1117 def update(self, result):
1118 return TimeoutFunction(self.base_player.update, [result], self.timeout)
1120 def quit(self, final_result):
1121 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
1122 # --- timeout_player.py --- #
1126 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
1127 network_timeout_delay = 1.0 # Maximum time between two characters being received
1130 def __init__(self, colour, address = None):
1131 self.socket = socket.socket()
1132 #self.socket.setblocking(0)
1134 if colour == "white":
1141 # print str(self) + " listens on port " + str(self.port)
1144 self.host = socket.gethostname()
1145 self.socket.bind((self.host, self.port))
1146 self.socket.listen(5)
1148 self.src, self.address = self.socket.accept()
1149 self.src.send("ok\n")
1150 if self.get_response() == "QUIT":
1154 self.socket.connect((address, self.port))
1155 self.src = self.socket
1156 self.src.send("ok\n")
1157 if self.get_response() == "QUIT":
1160 def get_response(self):
1161 # Timeout the start of the message (first character)
1162 if network_timeout_start > 0.0:
1163 ready = select.select([self.src], [], [], network_timeout_start)[0]
1166 if self.src in ready:
1167 s = self.src.recv(1)
1169 raise Exception("UNRESPONSIVE")
1172 while s[len(s)-1] != '\n':
1173 # Timeout on each character in the message
1174 if network_timeout_delay > 0.0:
1175 ready = select.select([self.src], [], [], network_timeout_delay)[0]
1178 if self.src in ready:
1179 s += self.src.recv(1)
1181 raise Exception("UNRESPONSIVE")
1183 return s.strip(" \r\n")
1185 def send_message(self,s):
1186 if network_timeout_start > 0.0:
1187 ready = select.select([], [self.src], [], network_timeout_start)[1]
1191 if self.src in ready:
1192 self.src.send(s + "\n")
1194 raise Exception("UNRESPONSIVE")
1196 def check_quit(self, s):
1200 game.final_result = " ".join(s[1:]) + " " + str(opponent(self.colour))
1206 class NetworkSender(Player,Network):
1207 def __init__(self, base_player, address = None):
1208 self.base_player = base_player
1209 Player.__init__(self, base_player.name, base_player.colour)
1211 self.address = address
1214 Network.__init__(self, self.base_player.colour, self.address)
1219 [x,y] = self.base_player.select()
1220 choice = self.board.grid[x][y]
1221 s = str(x) + " " + str(y)
1222 #print str(self) + ".select sends " + s
1223 self.send_message(s)
1227 [x,y] = self.base_player.get_move()
1228 s = str(x) + " " + str(y)
1229 #print str(self) + ".get_move sends " + s
1230 self.send_message(s)
1233 def update(self, s):
1234 self.base_player.update(s)
1236 [x,y] = map(int, s[0:2])
1237 selected = self.board.grid[x][y]
1238 if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
1239 s = " ".join(s[0:3])
1241 if selected.types_revealed[i] == True:
1242 s += " " + str(selected.types[i])
1245 #print str(self) + ".update sends " + s
1246 self.send_message(s)
1249 def quit(self, final_result):
1250 self.base_player.quit(final_result)
1251 #self.src.send("QUIT " + str(final_result) + "\n")
1254 class NetworkReceiver(Player,Network):
1255 def __init__(self, colour, address=None):
1257 Player.__init__(self, address, colour)
1259 self.address = address
1264 Network.__init__(self, self.colour, self.address)
1269 s = self.get_response()
1270 #print str(self) + ".select gets " + s
1271 [x,y] = map(int,s.split(" "))
1272 if x == -1 and y == -1:
1273 #print str(self) + ".select quits the game"
1275 game.final_state = "network terminated " + self.colour
1279 s = self.get_response()
1280 #print str(self) + ".get_move gets " + s
1281 [x,y] = map(int,s.split(" "))
1282 if x == -1 and y == -1:
1283 #print str(self) + ".get_move quits the game"
1285 game.final_state = "network terminated " + self.colour
1289 def update(self, result):
1291 result = result.split(" ")
1292 [x,y] = map(int, result[0:2])
1293 selected = self.board.grid[x][y]
1294 if selected != None and selected.colour == self.colour and len(result) > 2 and not "->" in result:
1295 s = self.get_response()
1296 #print str(self) + ".update - receives " + str(s)
1298 selected.choice = int(s[2])
1300 selected.types[i] = str(s[3+i])
1301 if s[3+i] == "unknown":
1302 selected.types_revealed[i] = False
1304 selected.types_revealed[i] = True
1305 selected.current_type = selected.types[selected.choice]
1308 #print str(self) + ".update - ignore result " + str(result)
1311 def quit(self, final_result):
1314 # --- network.py --- #
1317 # A thread that can be stopped!
1318 # Except it can only be stopped if it checks self.stopped() periodically
1319 # So it can sort of be stopped
1320 class StoppableThread(threading.Thread):
1322 threading.Thread.__init__(self)
1323 self._stop = threading.Event()
1329 return self._stop.isSet()
1330 # --- thread_util.py --- #
1336 def __init__(self, log):
1340 self.log.write("# Log starts " + str(datetime.datetime.now()) + "\n")
1343 now = datetime.datetime.now()
1344 self.log.write(str(now) + " : " + s + "\n")
1345 self.logged.append((now, s))
1347 def setup(self, board, players):
1350 self.log.write("# " + p.colour + " : " + p.name + "\n")
1352 self.log.write("# Initial board\n")
1353 for x in range(0, w):
1354 for y in range(0, h):
1355 if board.grid[x][y] != None:
1356 self.log.write(str(board.grid[x][y]) + "\n")
1358 self.log.write("# Start game\n")
1361 self.log.write("# EOF\n")
1362 if self.log != sys.stdout:
1365 class ShortLog(LogFile):
1366 def __init__(self, file_name):
1368 self.log = sys.stdout
1370 self.log = open(file_name, "w", 0)
1371 LogFile.__init__(self, self.log)
1372 self.file_name = file_name
1376 now = datetime.datetime.now()
1377 self.logged.append((now, s))
1380 if self.log != sys.stdout:
1382 self.log = open(self.file_name, "w", 0)
1383 self.log.write("# Short log updated " + str(datetime.datetime.now()) + "\n")
1384 LogFile.setup(self, game.board, game.players)
1386 elif self.phase == 1:
1387 for message in self.logged[len(self.logged)-2:]:
1388 self.log.write(str(message[0]) + " : " + message[1] + "\n")
1390 self.phase = (self.phase + 1) % 2
1394 ending = self.logged[len(self.logged)-1]
1395 self.log.write(str(ending[0]) + " : " + ending[1] + "\n")
1396 self.log.write("# EOF\n")
1397 if self.log != sys.stdout:
1401 class HeadRequest(urllib2.Request):
1402 def get_method(self):
1405 class HttpGetter(StoppableThread):
1406 def __init__(self, address):
1407 StoppableThread.__init__(self)
1408 self.address = address
1409 self.log = urllib2.urlopen(address)
1411 self.lock = threading.RLock() #lock for access of self.state
1412 self.cond = threading.Condition() # conditional
1415 while not self.stopped():
1416 line = self.log.readline()
1418 date_mod = datetime.datetime.strptime(self.log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1421 next_log = urllib2.urlopen(HeadRequest(self.address))
1422 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1423 while date_new <= date_mod and not self.stopped():
1424 next_log = urllib2.urlopen(HeadRequest(self.address))
1425 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1429 self.log = urllib2.urlopen(self.address)
1430 line = self.log.readline()
1433 self.lines.append(line)
1434 self.cond.notifyAll()
1437 #sys.stderr.write(" HttpGetter got \'" + str(line) + "\'\n")
1446 def __init__(self, address):
1447 self.getter = HttpGetter(address)
1451 self.getter.cond.acquire()
1452 while len(self.getter.lines) == 0:
1453 self.getter.cond.wait()
1455 result = self.getter.lines[0]
1456 self.getter.lines = self.getter.lines[1:]
1457 self.getter.cond.release()
1466 def __init__(self, filename):
1467 self.f = open(filename, "r", 0)
1468 self.filename = filename
1469 self.mod = os.path.getmtime(filename)
1473 line = self.f.readline()
1476 mod2 = os.path.getmtime(self.filename)
1478 #sys.stderr.write("File changed!\n")
1481 self.f = open(self.filename, "r", 0)
1483 new_line = self.f.readline()
1485 if " ".join(new_line.split(" ")[0:3]) != "# Short log":
1486 for i in range(self.count):
1487 new_line = self.f.readline()
1488 #sys.stderr.write("Read back " + str(i) + ": " + str(new_line) + "\n")
1489 new_line = self.f.readline()
1507 def log_init(board, players):
1509 l.setup(board, players)
1517 # A thread that runs the game
1518 class GameThread(StoppableThread):
1519 def __init__(self, board, players):
1520 StoppableThread.__init__(self)
1522 self.players = players
1523 self.state = {"turn" : None} # The game state
1524 self.error = 0 # Whether the thread exits with an error
1525 self.lock = threading.RLock() #lock for access of self.state
1526 self.cond = threading.Condition() # conditional for some reason, I forgot
1527 self.final_result = ""
1531 # Run the game (run in new thread with start(), run in current thread with run())
1534 while not self.stopped():
1536 for p in self.players:
1538 if isinstance(p, NetworkSender):
1539 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
1541 self.state["turn"] = p
1544 [x,y] = p.select() # Player selects a square
1551 result = self.board.select(x, y, colour = p.colour)
1552 for p2 in self.players:
1553 p2.update(result) # Inform players of what happened
1558 target = self.board.grid[x][y]
1559 if isinstance(graphics, GraphicsThread):
1561 graphics.state["moves"] = self.board.possible_moves(target)
1562 graphics.state["select"] = target
1564 time.sleep(turn_delay)
1567 if len(self.board.possible_moves(target)) == 0:
1568 #print "Piece cannot move"
1570 if isinstance(graphics, GraphicsThread):
1572 graphics.state["moves"] = None
1573 graphics.state["select"] = None
1574 graphics.state["dest"] = None
1578 [x2,y2] = p.get_move() # Player selects a destination
1585 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1588 self.board.update_move(x, y, x2, y2)
1590 for p2 in self.players:
1591 p2.update(result) # Inform players of what happened
1595 if isinstance(graphics, GraphicsThread):
1597 graphics.state["moves"] = [[x2,y2]]
1599 time.sleep(turn_delay)
1601 if isinstance(graphics, GraphicsThread):
1603 graphics.state["select"] = None
1604 graphics.state["dest"] = None
1605 graphics.state["moves"] = None
1607 # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
1608 # except Exception,e:
1609 # result = e.message
1610 # #sys.stderr.write(result + "\n")
1614 # self.final_result = self.state["turn"].colour + " " + e.message
1616 end = self.board.end_condition()
1620 self.final_result = self.state["turn"].colour + " " + end
1622 self.final_result = end
1629 for p2 in self.players:
1630 p2.quit(self.final_result)
1632 log(self.final_result)
1634 if isinstance(graphics, GraphicsThread):
1638 # A thread that replays a log file
1639 class ReplayThread(GameThread):
1640 def __init__(self, players, src, end=False,max_moves=None):
1641 self.board = Board(style="empty")
1642 self.board.max_moves = max_moves
1643 GameThread.__init__(self, self.board, players)
1647 self.reset_board(self.src.readline())
1649 def reset_board(self, line):
1652 while line != "# Start game" and line != "# EOF":
1655 line = self.src.readline().strip(" \r\n")
1659 line = self.src.readline().strip(" \r\n")
1662 self_str += line + "\n"
1664 if self.players[0].name == "dummy" and self.players[1].name == "dummy":
1665 line = self.src.readline().strip(" \r\n")
1668 tokens = line.split(" ")
1669 types = map(lambda e : e.strip("[] ,'"), tokens[2:4])
1670 for i in range(len(types)):
1671 if types[i][0] == "?":
1672 types[i] = "unknown"
1674 agent_str += tokens[0] + " " + tokens[1] + " " + str(types) + " ".join(tokens[4:]) + "\n"
1675 line = self.src.readline().strip(" \r\n")
1677 for p in self.players:
1678 p.reset_board(agent_str)
1681 self.board.reset_board(self_str)
1687 line = self.src.readline().strip(" \r\n")
1688 while line != "# EOF":
1700 line = self.src.readline().strip(" \r\n")
1703 tokens = line.split(" ")
1704 if tokens[0] == "white" or tokens[0] == "black":
1705 self.reset_board(line)
1707 line = self.src.readline().strip(" \r\n")
1710 move = line.split(":")
1711 move = move[len(move)-1].strip(" \r\n")
1712 tokens = move.split(" ")
1716 [x,y] = map(int, tokens[0:2])
1724 target = self.board.grid[x][y]
1726 if target.colour == "white":
1727 self.state["turn"] = self.players[0]
1729 self.state["turn"] = self.players[1]
1731 move_piece = (tokens[2] == "->")
1733 [x2,y2] = map(int, tokens[len(tokens)-2:])
1735 if isinstance(graphics, GraphicsThread):
1737 graphics.state["select"] = target
1740 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
1741 if isinstance(graphics, GraphicsThread):
1743 if target.current_type != "unknown":
1744 graphics.state["moves"] = self.board.possible_moves(target)
1746 graphics.state["moves"] = None
1747 time.sleep(turn_delay)
1749 self.board.update_move(x, y, x2, y2)
1750 if isinstance(graphics, GraphicsThread):
1752 graphics.state["moves"] = [[x2,y2]]
1753 time.sleep(turn_delay)
1755 graphics.state["select"] = None
1756 graphics.state["moves"] = None
1757 graphics.state["dest"] = None
1763 for p in self.players:
1767 line = self.src.readline().strip(" \r\n")
1770 end = self.board.end_condition()
1772 self.final_result = end
1790 if self.end and isinstance(graphics, GraphicsThread):
1792 pass # Let the user stop the display
1793 elif not self.end and self.board.end_condition() == None:
1795 # Work out the last move
1797 t = last_line.split(" ")
1798 if t[len(t)-2] == "black":
1799 self.players.reverse()
1800 elif t[len(t)-2] == "white":
1802 elif self.state["turn"] != None and self.state["turn"].colour == "white":
1803 self.players.reverse()
1806 game = GameThread(self.board, self.players)
1813 def opponent(colour):
1814 if colour == "white":
1825 # Dictionary that stores the unicode character representations of the different pieces
1826 # Chess was clearly the reason why unicode was invented
1827 # For some reason none of the pygame chess implementations I found used them!
1828 piece_char = {"white" : {"king" : u'\u2654',
1829 "queen" : u'\u2655',
1831 "bishop" : u'\u2657',
1832 "knight" : u'\u2658',
1835 "black" : {"king" : u'\u265A',
1836 "queen" : u'\u265B',
1838 "bishop" : u'\u265D',
1839 "knight" : u'\u265E',
1843 images = {"white" : {}, "black" : {}}
1844 small_images = {"white" : {}, "black" : {}}
1846 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
1848 # Get the font sizes
1849 l_size = 5*(grid_sz[0] / 8)
1850 s_size = 3*(grid_sz[0] / 8)
1852 for c in piece_char.keys():
1855 for p in piece_char[c].keys():
1856 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
1857 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})
1859 for p in piece_char[c].keys():
1860 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1861 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1862 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1863 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1866 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
1867 if not os.path.exists(image_dir):
1868 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
1869 for c in piece_char.keys():
1870 for p in piece_char[c].keys():
1871 images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
1872 small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
1873 # --- images.py --- #
1874 graphics_enabled = True
1878 graphics_enabled = False
1883 # A thread to make things pretty
1884 class GraphicsThread(StoppableThread):
1885 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1886 StoppableThread.__init__(self)
1890 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1891 pygame.display.set_caption(title)
1893 #print "Initialised properly"
1895 self.grid_sz = grid_sz[:]
1896 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
1898 self.lock = threading.RLock()
1899 self.cond = threading.Condition()
1902 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
1905 create_images(grid_sz)
1908 for c in images.keys():
1909 for p in images[c].keys():
1910 images[c][p] = images[c][p].convert(self.window)
1911 small_images[c][p] = small_images[c][p].convert(self.window)
1918 # On the run from the world
1921 while not self.stopped():
1923 #print "Display grid"
1924 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
1926 #print "Display overlay"
1929 #print "Display pieces"
1930 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
1932 pygame.display.flip()
1934 for event in pygame.event.get():
1935 if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_q):
1936 if isinstance(game, GameThread):
1938 game.final_result = ""
1939 if game.state["turn"] != None:
1940 game.final_result = game.state["turn"].colour + " "
1941 game.final_result += "terminated"
1945 elif event.type == pygame.MOUSEBUTTONDOWN:
1946 self.mouse_down(event)
1947 elif event.type == pygame.MOUSEBUTTONUP:
1948 self.mouse_up(event)
1955 self.message("Game ends, result \""+str(game.final_result) + "\"")
1958 # Wake up anyone who is sleeping
1963 pygame.quit() # Time to say goodbye
1965 # Mouse release event handler
1966 def mouse_up(self, event):
1967 if event.button == 3:
1969 self.state["overlay"] = None
1970 elif event.button == 2:
1972 self.state["coverage"] = None
1974 # Mouse click event handler
1975 def mouse_down(self, event):
1976 if event.button == 1:
1977 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
1978 if isinstance(game, GameThread):
1980 p = game.state["turn"]
1985 if isinstance(p, HumanPlayer):
1987 s = self.board.grid[m[0]][m[1]]
1988 select = self.state["select"]
1990 if s != None and s.colour != p.colour:
1991 self.message("Wrong colour") # Look at all this user friendliness!
1994 # Notify human player of move
1997 self.state["select"] = s
1998 self.state["dest"] = None
2007 if self.state["moves"] == None:
2010 if not m in self.state["moves"]:
2011 self.message("Illegal Move") # I still think last year's mouse interface was adequate
2016 if self.state["dest"] == None:
2018 self.state["dest"] = m
2019 self.state["select"] = None
2020 self.state["moves"] = None
2023 elif event.button == 3:
2024 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2025 if isinstance(game, GameThread):
2027 p = game.state["turn"]
2032 if isinstance(p, HumanPlayer):
2034 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
2036 elif event.button == 2:
2037 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2038 if isinstance(game, GameThread):
2040 p = game.state["turn"]
2045 if isinstance(p, HumanPlayer):
2047 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
2052 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
2053 # Draw square over the selected piece
2055 select = self.state["select"]
2057 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
2058 square_img.fill(pygame.Color(0,255,0,64))
2059 self.window.blit(square_img, mp)
2060 # If a piece is selected, draw all reachable squares
2061 # (This quality user interface has been patented)
2063 m = self.state["moves"]
2065 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
2067 mp = [self.grid_sz[i] * move[i] for i in range(2)]
2068 self.window.blit(square_img, mp)
2069 # If a piece is overlayed, show all squares that it has a probability to reach
2071 m = self.state["overlay"]
2076 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
2077 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
2078 self.window.blit(square_img, mp)
2079 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2080 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
2081 self.window.blit(text, mp)
2083 # If a square is selected, highlight all pieces that have a probability to reach it
2085 m = self.state["coverage"]
2088 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
2089 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
2090 self.window.blit(square_img, mp)
2091 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2092 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
2093 self.window.blit(text, mp)
2094 # Draw a square where the mouse is
2095 # This also serves to indicate who's turn it is
2097 if isinstance(game, GameThread):
2099 turn = game.state["turn"]
2103 if isinstance(turn, HumanPlayer):
2104 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
2105 square_img.fill(pygame.Color(0,0,255,128))
2106 if turn.colour == "white":
2107 c = pygame.Color(255,255,255)
2109 c = pygame.Color(0,0,0)
2110 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
2111 self.window.blit(square_img, mp)
2113 # Message in a bottle
2114 def message(self, string, pos = None, colour = None, font_size = 20):
2115 #print "Drawing message..."
2116 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2118 colour = pygame.Color(0,0,0)
2120 text = font.render(string, 1, colour)
2123 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
2124 s.fill(pygame.Color(128,128,128))
2126 tmp = self.window.get_size()
2129 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
2131 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
2134 rect = (pos[0], pos[1], text.get_width(), text.get_height())
2136 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
2137 self.window.blit(s, pos)
2138 self.window.blit(text, pos)
2140 pygame.display.flip()
2142 def getstr(self, prompt = None):
2143 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
2144 s.blit(self.window, (0,0))
2150 self.message(prompt)
2151 self.message(result, pos = (0, 1))
2154 for event in pygame.event.get():
2155 if event.type == pygame.QUIT:
2157 if event.type == pygame.KEYDOWN:
2158 if event.key == pygame.K_BACKSPACE:
2159 result = result[0:len(result)-1]
2160 self.window.blit(s, (0,0)) # Revert the display
2165 if event.unicode == '\r':
2168 result += str(event.unicode)
2173 # Function to pick a button
2174 def SelectButton(self, choices, prompt = None, font_size=20):
2176 #print "Select button called!"
2177 self.board.display_grid(self.window, self.grid_sz)
2179 self.message(prompt)
2180 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2182 sz = self.window.get_size()
2185 for i in range(len(choices)):
2188 text = font.render(c, 1, pygame.Color(0,0,0))
2189 p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
2190 targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
2193 mp =pygame.mouse.get_pos()
2194 for i in range(len(choices)):
2196 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
2197 font_colour = pygame.Color(255,0,0)
2198 box_colour = pygame.Color(0,0,255,128)
2200 font_colour = pygame.Color(0,0,0)
2201 box_colour = pygame.Color(128,128,128)
2203 text = font.render(c, 1, font_colour)
2204 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
2206 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
2207 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
2208 self.window.blit(s, targets[i][0:2])
2211 pygame.display.flip()
2213 for event in pygame.event.get():
2214 if event.type == pygame.QUIT:
2216 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
2217 for i in range(len(targets)):
2219 if event.pos[0] > t[0] and event.pos[0] < t[2]:
2220 if event.pos[1] > t[1] and event.pos[1] < t[3]:
2222 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
2225 # Function to pick players in a nice GUI way
2226 def SelectPlayers(self, players = []):
2229 #print "SelectPlayers called"
2231 missing = ["white", "black"]
2233 missing.remove(p.colour)
2235 for colour in missing:
2238 choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
2240 players.append(HumanPlayer("human", colour))
2243 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2244 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2245 internal_agents.remove(('InternalAgent', InternalAgent))
2246 if len(internal_agents) > 0:
2247 choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
2252 agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
2253 players.append(agent[1](agent[0], colour))
2257 from tkFileDialog import askopenfilename
2258 root = Tkinter.Tk() # Need a root to make Tkinter behave
2259 root.withdraw() # Some sort of magic incantation
2260 path = askopenfilename(parent=root, initialdir="../agents",title=
2263 return self.SelectPlayers()
2264 players.append(make_player(path, colour))
2269 self.board.display_grid(self.window, self.grid_sz)
2270 pygame.display.flip()
2271 path = self.getstr(prompt = "Enter path:")
2276 return self.SelectPlayers()
2279 p = make_player(path, colour)
2281 self.board.display_grid(self.window, self.grid_sz)
2282 pygame.display.flip()
2283 self.message("Invalid path!")
2289 while address == "":
2290 self.board.display_grid(self.window, self.grid_sz)
2292 address = self.getstr(prompt = "Address? (leave blank for server)")
2299 map(int, address.split("."))
2301 self.board.display_grid(self.window, self.grid_sz)
2302 self.message("Invalid IPv4 address!")
2305 players.append(NetworkReceiver(colour, address))
2308 #print str(self) + ".SelectPlayers returns " + str(players)
2313 # --- graphics.py --- #
2314 #!/usr/bin/python -u
2316 # Do you know what the -u does? It unbuffers stdin and stdout
2317 # I can't remember why, but last year things broke without that
2320 UCC::Progcomp 2013 Quantum Chess game
2321 @author Sam Moore [SZM] "matches"
2322 @copyright The University Computer Club, Incorporated
2323 (ie: You can copy it for not for profit purposes)
2326 # system python modules or whatever they are called
2332 [game, graphics] = [None, None]
2334 def make_player(name, colour):
2336 if name[1:] == "human":
2337 return HumanPlayer(name, colour)
2338 s = name[1:].split(":")
2339 if s[0] == "network":
2343 return NetworkReceiver(colour, address)
2344 if s[0] == "internal":
2347 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2348 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2349 internal_agents.remove(('InternalAgent', InternalAgent))
2352 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
2353 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2356 for a in internal_agents:
2358 return a[1](name, colour)
2360 sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
2361 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2366 return ExternalAgent(name, colour)
2370 # The main function! It does the main stuff!
2373 # Apparently python will silently treat things as local unless you do this
2374 # Anyone who says "You should never use a global variable" can die in a fire
2379 global agent_timeout
2382 global graphics_enabled
2383 global always_reveal_states
2391 # Get the important warnings out of the way
2392 if platform.system() == "Windows":
2393 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
2394 if platform.release() == "Vista":
2395 sys.stderr.write(sys.argv[0] + " : God help you.\n")
2400 while i < len(argv)-1:
2404 p = make_player(arg, colour)
2405 if not isinstance(p, Player):
2406 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
2409 if colour == "white":
2411 elif colour == "black":
2414 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
2417 # Option parsing goes here
2418 if arg[1] == '-' and arg[2:] == "classical":
2420 elif arg[1] == '-' and arg[2:] == "quantum":
2422 elif arg[1] == '-' and arg[2:] == "reveal":
2423 always_reveal_states = True
2424 elif (arg[1] == '-' and arg[2:] == "graphics"):
2425 graphics_enabled = True
2426 elif (arg[1] == '-' and arg[2:] == "no-graphics"):
2427 graphics_enabled = False
2428 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
2429 # Load game from file
2430 if len(arg[2:].split("=")) == 1:
2431 src_file = sys.stdin
2433 f = arg[2:].split("=")[1]
2434 if f[0:7] == "http://":
2435 src_file = HttpReplay(f)
2437 src_file = FileReplay(f.split(":")[0])
2439 if len(f.split(":")) == 2:
2440 max_moves = int(f.split(":")[1])
2442 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
2444 if len(arg[2:].split("=")) == 1:
2445 log_files.append(LogFile(sys.stdout))
2447 f = arg[2:].split("=")[1]
2449 log_files.append(ShortLog(f[1:]))
2451 log_files.append(LogFile(open(f, "w", 0)))
2452 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
2454 if len(arg[2:].split("=")) == 1:
2457 turn_delay = float(arg[2:].split("=")[1])
2459 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
2461 if len(arg[2:].split("=")) == 1:
2464 agent_timeout = float(arg[2:].split("=")[1])
2466 elif (arg[1] == '-' and arg[2:] == "help"):
2468 os.system("less data/help.txt") # The best help function
2474 # Construct a GameThread! Make it global! Damn the consequences!
2476 if src_file != None:
2477 # Hack to stop ReplayThread from exiting
2478 #if len(players) == 0:
2479 # players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
2481 # Normally the ReplayThread exits if there are no players
2482 # TODO: Decide which behaviour to use, and fix it
2483 end = (len(players) == 0)
2485 players = [Player("dummy", "white"), Player("dummy", "black")]
2486 elif len(players) != 2:
2487 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2488 if graphics_enabled:
2489 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
2491 game = ReplayThread(players, src_file, end=end, max_moves=max_moves)
2493 board = Board(style)
2494 board.max_moves = max_moves
2495 game = GameThread(board, players)
2501 if graphics_enabled == True:
2503 graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
2507 sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
2508 graphics_enabled = False
2510 # If there are no players listed, display a nice pretty menu
2511 if len(players) != 2:
2512 if graphics != None:
2513 players = graphics.SelectPlayers(players)
2515 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2518 # If there are still no players, quit
2519 if players == None or len(players) != 2:
2520 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
2524 # Wrap NetworkSender players around original players if necessary
2525 for i in range(len(players)):
2526 if isinstance(players[i], NetworkReceiver):
2527 players[i].board = board # Network players need direct access to the board
2528 for j in range(len(players)):
2531 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
2533 players[j] = NetworkSender(players[j], players[i].address)
2534 players[j].board = board
2536 # Connect the networked players
2538 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
2539 if graphics != None:
2540 graphics.board.display_grid(graphics.window, graphics.grid_sz)
2541 graphics.message("Connecting to " + p.colour + " player...")
2545 # If using windows, select won't work; use horrible TimeoutPlayer hack
2546 if agent_timeout > 0:
2547 if platform.system() == "Windows":
2548 for i in range(len(players)):
2549 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
2550 players[i] = TimeoutPlayer(players[i], agent_timeout)
2554 # InternalAgents get wrapped to an ExternalAgent when there is a timeout
2555 # This is not confusing at all.
2556 for i in range(len(players)):
2557 if isinstance(players[i], InternalAgent):
2558 players[i] = ExternalWrapper(players[i])
2566 log_init(game.board, players)
2569 if graphics != None:
2570 game.start() # This runs in a new thread
2576 error = game.error + graphics.error
2585 if src_file != None and src_file != sys.stdin:
2588 sys.stdout.write(game.final_result + "\n")
2592 # This is how python does a main() function...
2593 if __name__ == "__main__":
2595 sys.exit(main(sys.argv))
2596 except KeyboardInterrupt:
2597 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
2598 if isinstance(graphics, StoppableThread):
2600 graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
2602 if isinstance(game, StoppableThread):
2610 # EOF - created from make on Thu Mar 14 22:36:37 WST 2013