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
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":
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
115 for c in ["black", "white"]:
116 del self.unrevealed_types[c]["unknown"]
121 # Add all the pieces with known primary types
122 for i in range(0, 2):
124 s = ["black", "white"][i]
128 c.append(Piece(s, 0, y, ["rook"]))
129 c.append(Piece(s, 1, y, ["knight"]))
130 c.append(Piece(s, 2, y, ["bishop"]))
131 k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
132 k.current_type = "king"
135 c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
136 c.append(Piece(s, 5, y, ["bishop"]))
137 c.append(Piece(s, 6, y, ["knight"]))
138 c.append(Piece(s, 7, y, ["rook"]))
146 for x in range(0, w):
147 c.append(Piece(s, x, y, ["pawn"]))
150 types_left.update(piece_types)
151 del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
152 del types_left["unknown"] # We certainly don't want these!
155 self.grid[piece.x][piece.y] = piece
157 if len(piece.types) > 1:
159 if style == "agent": # Assign placeholder "unknown" secondary type
160 piece.types.append("unknown")
163 elif style == "quantum":
164 # The master allocates the secondary types
165 choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
166 types_left[choice] -= 1
167 if types_left[choice] <= 0:
168 del types_left[choice]
169 piece.types.append('?' + choice)
170 elif style == "classical":
171 piece.types.append(piece.types[0])
172 piece.current_type = piece.types[0]
176 newboard = Board(master = False)
177 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
178 mypieces = self.pieces["white"] + self.pieces["black"]
180 for i in range(len(mypieces)):
181 newpieces[i].init_from_copy(mypieces[i])
183 # Reset the board from a string
184 def reset_board(self, s):
185 self.pieces = {"white" : [], "black" : []}
186 self.king = {"white" : None, "black" : None}
187 self.grid = [[None] * w for _ in range(h)]
190 self.grid[x][y] = None
192 for line in s.split("\n"):
198 tokens = line.split(" ")
199 [x, y] = map(int, tokens[len(tokens)-1].split(","))
200 current_type = tokens[1]
201 types = map(lambda e : e.strip(" '[],"), line.split('[')[1].split(']')[0].split(','))
203 target = Piece(tokens[0], x, y, types)
204 target.current_type = current_type
207 target.choice = types.index(current_type)
211 self.pieces[tokens[0]].append(target)
212 if target.current_type == "king":
213 self.king[tokens[0]] = target
215 self.grid[x][y] = target
218 def display_grid(self, window = None, grid_sz = [80,80]):
220 return # I was considering implementing a text only display, then I thought "Fuck that"
222 # The indentation is getting seriously out of hand...
223 for x in range(0, w):
224 for y in range(0, h):
226 c = pygame.Color(200,200,200)
228 c = pygame.Color(64,64,64)
229 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
231 def display_pieces(self, window = None, grid_sz = [80,80]):
234 for p in self.pieces["white"] + self.pieces["black"]:
235 p.draw(window, grid_sz, self.style)
237 # Draw the board in a pygame window
238 def display(self, window = None):
239 self.display_grid(window)
240 self.display_pieces(window)
248 if self.grid[x][y] == None:
250 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
251 raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
253 # Select a piece on the board (colour is the colour of whoever is doing the selecting)
254 def select(self, x,y, colour=None):
255 if not self.on_board(x, y): # Get on board everyone!
256 raise Exception("BOUNDS")
258 piece = self.grid[x][y]
260 raise Exception("EMPTY")
262 if colour != None and piece.colour != colour:
263 raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
265 # I'm not quite sure why I made this return a string, but screw logical design
266 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
269 # Update the board when a piece has been selected
270 # "type" is apparently reserved, so I'll use "state"
271 def update_select(self, x, y, type_index, state):
272 piece = self.grid[x][y]
273 if piece.types[type_index] == "unknown":
274 if not state in self.unrevealed_types[piece.colour].keys():
275 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
276 self.unrevealed_types[piece.colour][state] -= 1
277 if self.unrevealed_types[piece.colour][state] <= 0:
278 del self.unrevealed_types[piece.colour][state]
280 piece.types[type_index] = state
281 piece.current_type = state
283 if len(self.possible_moves(piece)) <= 0:
284 piece.deselect() # Piece can't move; deselect it
286 # Update the board when a piece has been moved
287 def update_move(self, x, y, x2, y2):
288 piece = self.grid[x][y]
289 self.grid[x][y] = None
290 taken = self.grid[x2][y2]
292 if taken.current_type == "king":
293 self.king[taken.colour] = None
294 self.pieces[taken.colour].remove(taken)
295 self.grid[x2][y2] = piece
299 # If the piece is a pawn, and it reaches the final row, it becomes a queen
300 # I know you are supposed to get a choice
301 # But that would be effort
302 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
303 if self.style == "classical":
304 piece.types[0] = "queen"
305 piece.types[1] = "queen"
307 piece.types[piece.choice] = "queen"
308 piece.current_type = "queen"
310 piece.deselect() # Uncollapse (?) the wavefunction!
314 # Update the board from a string
315 # Guesses what to do based on the format of the string
316 def update(self, result):
317 #print "Update called with \"" + str(result) + "\""
318 # String always starts with 'x y'
320 s = result.split(" ")
321 [x,y] = map(int, s[0:2])
323 raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
325 piece = self.grid[x][y]
327 raise Exception("EMPTY")
329 # If a piece is being moved, the third token is '->'
330 # We could get away with just using four integers, but that wouldn't look as cool
332 # Last two tokens are the destination
334 [x2,y2] = map(int, s[3:])
336 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
338 # Move the piece (take opponent if possible)
339 self.update_move(x, y, x2, y2)
342 # Otherwise we will just assume a piece has been selected
344 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
345 state = s[3] # The last token is a string identifying the type
347 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
350 self.update_select(x, y, type_index, state)
354 # Gets each piece that could reach the given square and the probability that it could reach that square
355 # Will include allied pieces that defend the attacker
356 def coverage(self, x, y, colour = None, reject_allied = True):
360 pieces = self.pieces["white"] + self.pieces["black"]
362 pieces = self.pieces[colour]
365 prob = self.probability_grid(p, reject_allied)[x][y]
367 result.update({p : prob})
376 # Associates each square with a probability that the piece could move into it
377 # Look, I'm doing all the hard work for you here...
378 def probability_grid(self, p, reject_allied = True):
380 result = [[0.0] * w for _ in range(h)]
381 if not isinstance(p, Piece):
384 if p.current_type != "unknown":
385 #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
386 for point in self.possible_moves(p, reject_allied):
387 result[point[0]][point[1]] = 1.0
391 for i in range(len(p.types)):
394 if t == "unknown" or p.types[i][0] == '?':
396 for t2 in self.unrevealed_types[p.colour].keys():
397 total_types += self.unrevealed_types[p.colour][t2]
399 for t2 in self.unrevealed_types[p.colour].keys():
400 prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
402 for point in self.possible_moves(p, reject_allied):
403 result[point[0]][point[1]] += prob2 * prob
407 for point in self.possible_moves(p, reject_allied):
408 result[point[0]][point[1]] += prob
411 p.current_type = "unknown"
414 def prob_is_type(self, p, state):
417 for i in range(len(p.types)):
422 if t == "unknown" or p.types[i][0] == '?':
424 for t2 in self.unrevealed_types[p.colour].keys():
425 total_prob += self.unrevealed_types[p.colour][t2]
426 for t2 in self.unrevealed_types[p.colour].keys():
428 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
432 # Get all squares that the piece could move into
433 # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
434 # reject_allied indicates whether squares occupied by allied pieces will be removed
435 # (set to false to check for defense)
436 def possible_moves(self, p, reject_allied = True):
442 if p.current_type == "unknown":
443 raise Exception("SANITY: Piece state unknown")
444 # The below commented out code causes things to break badly
449 # result += self.possible_moves(p)
450 #p.current_type = "unknown"
453 if p.current_type == "king":
454 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]]
455 elif p.current_type == "queen":
456 for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
457 result += self.scan(p.x, p.y, d[0], d[1])
458 elif p.current_type == "bishop":
459 for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
460 result += self.scan(p.x, p.y, d[0], d[1])
461 elif p.current_type == "rook":
462 for d in [[-1,0],[1,0],[0,-1],[0,1]]:
463 result += self.scan(p.x, p.y, d[0], d[1])
464 elif p.current_type == "knight":
465 # I would use two lines, but I'm not sure how python likes that
466 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]]
467 elif p.current_type == "pawn":
468 if p.colour == "white":
470 # Pawn can't move forward into occupied square
471 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
472 result = [[p.x,p.y-1]]
473 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
474 if not self.on_board(f[0], f[1]):
476 if self.grid[f[0]][f[1]] != None: # Pawn can take diagonally
479 # Slightly embarrassing if the pawn jumps over someone on its first move...
480 if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
481 result.append([p.x, p.y-2])
483 # Vice versa for the black pawn
484 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
485 result = [[p.x,p.y+1]]
487 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
488 if not self.on_board(f[0], f[1]):
490 if self.grid[f[0]][f[1]] != None:
491 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
494 if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
495 result.append([p.x, p.y+2])
497 #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
499 # Remove illegal moves
500 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
501 for point in result[:]:
503 if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
504 result.remove(point) # Remove locations outside the board
506 g = self.grid[point[0]][point[1]]
508 if g != None and (g.colour == p.colour and reject_allied == True):
509 result.remove(point) # Remove allied pieces
515 # Scans in a direction until it hits a piece, returns all squares in the line
516 # (includes the final square (which contains a piece), but not the original square)
517 def scan(self, x, y, vx, vy):
525 if not self.on_board(xx, yy):
529 g = self.grid[xx][yy]
535 # Returns "white", "black" or "DRAW" if the game should end
536 def end_condition(self):
537 if self.king["white"] == None:
538 if self.king["black"] == None:
539 return "DRAW" # This shouldn't happen
541 elif self.king["black"] == None:
543 elif len(self.pieces["white"]) == 1 and len(self.pieces["black"]) == 1:
545 elif self.max_moves != None and self.moves > self.max_moves:
550 # I typed the full statement about 30 times before writing this function...
551 def on_board(self, x, y):
552 return (x >= 0 and x < w) and (y >= 0 and y < h)
559 agent_timeout = -1.0 # Timeout in seconds for AI players to make moves
560 # WARNING: Won't work for windows based operating systems
562 if platform.system() == "Windows":
563 agent_timeout = -1 # Hence this
565 # A player who can't play
567 def __init__(self, name, colour):
571 def update(self, result):
574 def reset_board(self, s):
577 # Player that runs from another process
578 class ExternalAgent(Player):
581 def __init__(self, name, colour):
582 Player.__init__(self, name, colour)
583 self.p = subprocess.Popen(name,bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,universal_newlines=True)
585 self.send_message(colour)
587 def send_message(self, s):
588 if agent_timeout > 0.0:
589 ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
591 ready = [self.p.stdin]
592 if self.p.stdin in ready:
593 #sys.stderr.write("Writing \'" + s + "\' to " + str(self.p) + "\n")
595 self.p.stdin.write(s + "\n")
597 raise Exception("UNRESPONSIVE")
599 raise Exception("TIMEOUT")
601 def get_response(self):
602 if agent_timeout > 0.0:
603 ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
605 ready = [self.p.stdout]
606 if self.p.stdout in ready:
607 #sys.stderr.write("Reading from " + str(self.p) + " 's stdout...\n")
609 result = self.p.stdout.readline().strip("\r\n")
610 #sys.stderr.write("Read \'" + result + "\' from " + str(self.p) + "\n")
612 except: # Exception, e:
613 raise Exception("UNRESPONSIVE")
615 raise Exception("TIMEOUT")
619 self.send_message("SELECTION?")
620 line = self.get_response()
623 result = map(int, line.split(" "))
625 raise Exception("GIBBERISH \"" + str(line) + "\"")
628 def update(self, result):
629 #print "Update " + str(result) + " called for AgentPlayer"
630 self.send_message(result)
635 self.send_message("MOVE?")
636 line = self.get_response()
639 result = map(int, line.split(" "))
641 raise Exception("GIBBERISH \"" + str(line) + "\"")
644 def reset_board(self, s):
645 self.send_message("BOARD")
646 for line in s.split("\n"):
647 self.send_message(line.strip(" \r\n"))
648 self.send_message("END BOARD")
650 def quit(self, final_result):
652 self.send_message("QUIT " + final_result)
656 # So you want to be a player here?
657 class HumanPlayer(Player):
658 def __init__(self, name, colour):
659 Player.__init__(self, name, colour)
661 # Select your preferred account
663 if isinstance(graphics, GraphicsThread):
664 # Basically, we let the graphics thread do some shit and then return that information to the game thread
665 graphics.cond.acquire()
666 # We wait for the graphics thread to select a piece
667 while graphics.stopped() == False and graphics.state["select"] == None:
668 graphics.cond.wait() # The difference between humans and machines is that humans sleep
669 select = graphics.state["select"]
672 graphics.cond.release()
673 if graphics.stopped():
675 return [select.x, select.y]
677 # Since I don't display the board in this case, I'm not sure why I filled it in...
679 sys.stdout.write("SELECTION?\n")
681 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
683 sys.stderr.write("ILLEGAL GIBBERISH\n")
685 # It's your move captain
687 if isinstance(graphics, GraphicsThread):
688 graphics.cond.acquire()
689 while graphics.stopped() == False and graphics.state["dest"] == None:
691 graphics.cond.release()
693 return graphics.state["dest"]
697 sys.stdout.write("MOVE?\n")
699 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
701 sys.stderr.write("ILLEGAL GIBBERISH\n")
704 # Are you sure you want to quit?
705 def quit(self, final_result):
707 sys.stdout.write("QUIT " + final_result + "\n")
709 # Completely useless function
710 def update(self, result):
711 if isinstance(graphics, GraphicsThread):
714 sys.stdout.write(result + "\n")
717 # Default internal player (makes random moves)
718 class InternalAgent(Player):
719 def __init__(self, name, colour):
720 Player.__init__(self, name, colour)
723 self.board = Board(style = "agent")
727 def update(self, result):
729 self.board.update(result)
732 def reset_board(self, s):
733 self.board.reset_board(s)
735 def quit(self, final_result):
738 class AgentRandom(InternalAgent):
739 def __init__(self, name, colour):
740 InternalAgent.__init__(self, name, colour)
744 self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
746 # Check that the piece has some possibility to move
747 tmp = self.choice.current_type
748 if tmp == "unknown": # For unknown pieces, try both types
749 for t in self.choice.types:
752 self.choice.current_type = t
753 all_moves += self.board.possible_moves(self.choice)
755 all_moves = self.board.possible_moves(self.choice)
756 self.choice.current_type = tmp
757 if len(all_moves) > 0:
759 return [self.choice.x, self.choice.y]
762 moves = self.board.possible_moves(self.choice)
763 move = moves[random.randint(0, len(moves)-1)]
767 # Terrible, terrible hacks
769 def run_agent(agent):
770 #sys.stderr.write(sys.argv[0] + " : Running agent " + str(agent) + "\n")
772 line = sys.stdin.readline().strip(" \r\n")
773 if line == "SELECTION?":
774 #sys.stderr.write(sys.argv[0] + " : Make selection\n")
775 [x,y] = agent.select() # Gets your agent's selection
776 #sys.stderr.write(sys.argv[0] + " : Selection was " + str(agent.choice) + "\n")
777 sys.stdout.write(str(x) + " " + str(y) + "\n")
778 elif line == "MOVE?":
779 #sys.stderr.write(sys.argv[0] + " : Make move\n")
780 [x,y] = agent.get_move() # Gets your agent's move
781 sys.stdout.write(str(x) + " " + str(y) + "\n")
782 elif line.split(" ")[0] == "QUIT":
783 #sys.stderr.write(sys.argv[0] + " : Quitting\n")
784 agent.quit(" ".join(line.split(" ")[1:])) # Quits the game
786 elif line.split(" ")[0] == "BOARD":
788 line = sys.stdin.readline().strip(" \r\n")
789 while line != "END BOARD":
791 line = sys.stdin.readline().strip(" \r\n")
792 agent.board.reset_board(s)
795 agent.update(line) # Updates agent.board
801 class ExternalWrapper(ExternalAgent):
802 def __init__(self, agent):
803 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))\""
805 ExternalAgent.__init__(self, run, agent.colour)
809 # --- player.py --- #
813 class AgentBishop(AgentRandom): # Inherits from AgentRandom (in qchess)
814 def __init__(self, name, colour):
815 InternalAgent.__init__(self, name, colour)
816 self.value = {"pawn" : 1, "bishop" : 3, "knight" : 3, "rook" : 5, "queen" : 9, "king" : 100, "unknown" : 4}
818 self.aggression = 2.0 # Multiplier for scoring due to aggressive actions
819 self.defence = 1.0 # Multiplier for scoring due to defensive actions
821 self.depth = 0 # Current depth
822 self.max_depth = 2 # Recurse this many times (for some reason, makes more mistakes when this is increased???)
823 self.recurse_for = -1 # Recurse for the best few moves each times (less than 0 = all moves)
825 for p in self.board.pieces["white"] + self.board.pieces["black"]:
827 p.selected_moves = None
831 def get_value(self, piece):
834 return float(self.value[piece.types[0]] + self.value[piece.types[1]]) / 2.0
836 # Score possible moves for the piece
838 def prioritise_moves(self, piece):
840 #sys.stderr.write(sys.argv[0] + " : " + str(self) + " prioritise called for " + str(piece) + "\n")
844 grid = self.board.probability_grid(piece)
845 #sys.stderr.write("\t Probability grid " + str(grid) + "\n")
849 if grid[x][y] < 0.3: # Throw out moves with < 30% probability
850 #sys.stderr.write("\tReject " + str(x) + "," + str(y) + " (" + str(grid[x][y]) + ")\n")
853 target = self.board.grid[x][y]
858 # Get total probability that the move is protected
859 [xx,yy] = [piece.x, piece.y]
860 [piece.x, piece.y] = [x, y]
861 self.board.grid[x][y] = piece
862 self.board.grid[xx][yy] = None
864 defenders = self.board.coverage(x, y, piece.colour, reject_allied = False)
866 for d in defenders.keys():
867 d_prob += defenders[d]
868 if len(defenders.keys()) > 0:
869 d_prob /= float(len(defenders.keys()))
874 # Get total probability that the move is threatened
875 attackers = self.board.coverage(x, y, opponent(piece.colour), reject_allied = False)
877 for a in attackers.keys():
878 a_prob += attackers[a]
879 if len(attackers.keys()) > 0:
880 a_prob /= float(len(attackers.keys()))
885 self.board.grid[x][y] = target
886 self.board.grid[xx][yy] = piece
887 [piece.x, piece.y] = [xx, yy]
891 value = self.aggression * (1.0 + d_prob) * self.get_value(target) - self.defence * (1.0 - d_prob) * a_prob * self.get_value(piece)
893 # Adjust score based on movement of piece out of danger
894 attackers = self.board.coverage(piece.x, piece.y, opponent(piece.colour))
896 for a in attackers.keys():
897 s_prob += attackers[a]
898 if len(attackers.keys()) > 0:
899 s_prob /= float(len(attackers.keys()))
903 value += self.defence * s_prob * self.get_value(piece)
905 # Adjust score based on probability that the move is actually possible
906 moves.append([[x, y], grid[x][y] * value])
908 moves.sort(key = lambda e : e[1], reverse = True)
909 #sys.stderr.write(sys.argv[0] + ": Moves for " + str(piece) + " are " + str(moves) + "\n")
911 piece.last_moves = moves
912 piece.selected_moves = None
919 def select_best(self, colour):
923 for p in self.board.pieces[colour]:
924 self.choice = p # Temporarily pick that piece
925 m = self.prioritise_moves(p)
927 all_moves.update({p : m[0]})
929 if len(all_moves.items()) <= 0:
933 opts = all_moves.items()
934 opts.sort(key = lambda e : e[1][1], reverse = True)
936 if self.depth >= self.max_depth:
940 if self.recurse_for >= 0:
941 opts = opts[0:self.recurse_for]
942 #sys.stderr.write(sys.argv[0] + " : Before recurse, options are " + str(opts) + "\n")
944 # Take the best few moves, and recurse
945 for choice in opts[0:self.recurse_for]:
946 [xx,yy] = [choice[0].x, choice[0].y] # Remember position
947 [nx,ny] = choice[1][0] # Target
948 [choice[0].x, choice[0].y] = [nx, ny] # Set position
949 target = self.board.grid[nx][ny] # Remember piece in spot
950 self.board.grid[xx][yy] = None # Remove piece
951 self.board.grid[nx][ny] = choice[0] # Replace with moving piece
954 best_enemy_move = self.select_best(opponent(choice[0].colour))
955 choice[1][1] -= best_enemy_move[1][1] / float(self.depth + 1.0)
957 [choice[0].x, choice[0].y] = [xx, yy] # Restore position
958 self.board.grid[nx][ny] = target # Restore taken piece
959 self.board.grid[xx][yy] = choice[0] # Restore moved piece
963 opts.sort(key = lambda e : e[1][1], reverse = True)
964 #sys.stderr.write(sys.argv[0] + " : After recurse, options are " + str(opts) + "\n")
971 # Returns [x,y] of selected piece
973 #sys.stderr.write("Getting choice...")
974 self.choice = self.select_best(self.colour)[0]
976 #sys.stderr.write(" Done " + str(self.choice)+"\n")
977 return [self.choice.x, self.choice.y]
979 # Returns [x,y] of square to move selected piece into
981 #sys.stderr.write("Choice is " + str(self.choice) + "\n")
982 self.choice.selected_moves = self.choice.last_moves
983 moves = self.prioritise_moves(self.choice)
987 return AgentRandom.get_move(self)
989 # --- agent_bishop.py --- #
990 import multiprocessing
992 # Hacky alternative to using select for timing out players
994 # WARNING: Do not wrap around HumanPlayer or things breakify
995 # WARNING: Do not use in general or things breakify
997 class Sleeper(multiprocessing.Process):
998 def __init__(self, timeout):
999 multiprocessing.Process.__init__(self)
1000 self.timeout = timeout
1003 time.sleep(self.timeout)
1006 class Worker(multiprocessing.Process):
1007 def __init__(self, function, args, q):
1008 multiprocessing.Process.__init__(self)
1009 self.function = function
1014 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args)
1015 self.q.put(self.function(*self.args))
1019 def TimeoutFunction(function, args, timeout):
1020 q = multiprocessing.Queue()
1021 w = Worker(function, args, q)
1022 s = Sleeper(timeout)
1025 while True: # Busy loop of crappyness
1026 if not w.is_alive():
1030 #print "TimeoutFunction gets " + str(result)
1032 elif not s.is_alive():
1035 raise Exception("TIMEOUT")
1040 # A player that wraps another player and times out its moves
1042 # A (crappy) alternative to the use of select()
1043 class TimeoutPlayer(Player):
1044 def __init__(self, base_player, timeout):
1045 Player.__init__(self, base_player.name, base_player.colour)
1046 self.base_player = base_player
1047 self.timeout = timeout
1050 return TimeoutFunction(self.base_player.select, [], self.timeout)
1054 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
1056 def update(self, result):
1057 return TimeoutFunction(self.base_player.update, [result], self.timeout)
1059 def quit(self, final_result):
1060 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
1061 # --- timeout_player.py --- #
1065 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
1066 network_timeout_delay = 1.0 # Maximum time between two characters being received
1069 def __init__(self, colour, address = None):
1070 self.socket = socket.socket()
1071 #self.socket.setblocking(0)
1073 if colour == "white":
1080 # print str(self) + " listens on port " + str(self.port)
1083 self.host = socket.gethostname()
1084 self.socket.bind((self.host, self.port))
1085 self.socket.listen(5)
1087 self.src, self.address = self.socket.accept()
1088 self.src.send("ok\n")
1089 if self.get_response() == "QUIT":
1093 self.socket.connect((address, self.port))
1094 self.src = self.socket
1095 self.src.send("ok\n")
1096 if self.get_response() == "QUIT":
1099 def get_response(self):
1100 # Timeout the start of the message (first character)
1101 if network_timeout_start > 0.0:
1102 ready = select.select([self.src], [], [], network_timeout_start)[0]
1105 if self.src in ready:
1106 s = self.src.recv(1)
1108 raise Exception("UNRESPONSIVE")
1111 while s[len(s)-1] != '\n':
1112 # Timeout on each character in the message
1113 if network_timeout_delay > 0.0:
1114 ready = select.select([self.src], [], [], network_timeout_delay)[0]
1117 if self.src in ready:
1118 s += self.src.recv(1)
1120 raise Exception("UNRESPONSIVE")
1122 return s.strip(" \r\n")
1124 def send_message(self,s):
1125 if network_timeout_start > 0.0:
1126 ready = select.select([], [self.src], [], network_timeout_start)[1]
1130 if self.src in ready:
1131 self.src.send(s + "\n")
1133 raise Exception("UNRESPONSIVE")
1135 def check_quit(self, s):
1139 game.final_result = " ".join(s[1:]) + " " + str(opponent(self.colour))
1145 class NetworkSender(Player,Network):
1146 def __init__(self, base_player, address = None):
1147 self.base_player = base_player
1148 Player.__init__(self, base_player.name, base_player.colour)
1150 self.address = address
1153 Network.__init__(self, self.base_player.colour, self.address)
1158 [x,y] = self.base_player.select()
1159 choice = self.board.grid[x][y]
1160 s = str(x) + " " + str(y)
1161 #print str(self) + ".select sends " + s
1162 self.send_message(s)
1166 [x,y] = self.base_player.get_move()
1167 s = str(x) + " " + str(y)
1168 #print str(self) + ".get_move sends " + s
1169 self.send_message(s)
1172 def update(self, s):
1173 self.base_player.update(s)
1175 [x,y] = map(int, s[0:2])
1176 selected = self.board.grid[x][y]
1177 if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
1178 s = " ".join(s[0:3])
1180 if selected.types_revealed[i] == True:
1181 s += " " + str(selected.types[i])
1184 #print str(self) + ".update sends " + s
1185 self.send_message(s)
1188 def quit(self, final_result):
1189 self.base_player.quit(final_result)
1190 #self.src.send("QUIT " + str(final_result) + "\n")
1193 class NetworkReceiver(Player,Network):
1194 def __init__(self, colour, address=None):
1196 Player.__init__(self, address, colour)
1198 self.address = address
1203 Network.__init__(self, self.colour, self.address)
1208 s = self.get_response()
1209 #print str(self) + ".select gets " + s
1210 [x,y] = map(int,s.split(" "))
1211 if x == -1 and y == -1:
1212 #print str(self) + ".select quits the game"
1214 game.final_state = "network terminated " + self.colour
1218 s = self.get_response()
1219 #print str(self) + ".get_move gets " + s
1220 [x,y] = map(int,s.split(" "))
1221 if x == -1 and y == -1:
1222 #print str(self) + ".get_move quits the game"
1224 game.final_state = "network terminated " + self.colour
1228 def update(self, result):
1230 result = result.split(" ")
1231 [x,y] = map(int, result[0:2])
1232 selected = self.board.grid[x][y]
1233 if selected != None and selected.colour == self.colour and len(result) > 2 and not "->" in result:
1234 s = self.get_response()
1235 #print str(self) + ".update - receives " + str(s)
1237 selected.choice = int(s[2])
1239 selected.types[i] = str(s[3+i])
1240 if s[3+i] == "unknown":
1241 selected.types_revealed[i] = False
1243 selected.types_revealed[i] = True
1244 selected.current_type = selected.types[selected.choice]
1247 #print str(self) + ".update - ignore result " + str(result)
1250 def quit(self, final_result):
1253 # --- network.py --- #
1256 # A thread that can be stopped!
1257 # Except it can only be stopped if it checks self.stopped() periodically
1258 # So it can sort of be stopped
1259 class StoppableThread(threading.Thread):
1261 threading.Thread.__init__(self)
1262 self._stop = threading.Event()
1268 return self._stop.isSet()
1269 # --- thread_util.py --- #
1275 def __init__(self, log):
1279 self.log.write("# Log starts " + str(datetime.datetime.now()) + "\n")
1282 now = datetime.datetime.now()
1283 self.log.write(str(now) + " : " + s + "\n")
1284 self.logged.append((now, s))
1286 def setup(self, board, players):
1289 self.log.write("# " + p.colour + " : " + p.name + "\n")
1291 self.log.write("# Initial board\n")
1292 for x in range(0, w):
1293 for y in range(0, h):
1294 if board.grid[x][y] != None:
1295 self.log.write(str(board.grid[x][y]) + "\n")
1297 self.log.write("# Start game\n")
1300 self.log.write("# EOF\n")
1301 if self.log != sys.stdout:
1304 class ShortLog(LogFile):
1305 def __init__(self, file_name):
1307 self.log = sys.stdout
1309 self.log = open(file_name, "w", 0)
1310 LogFile.__init__(self, self.log)
1311 self.file_name = file_name
1315 now = datetime.datetime.now()
1316 self.logged.append((now, s))
1319 if self.log != sys.stdout:
1321 self.log = open(self.file_name, "w", 0)
1322 self.log.write("# Short log updated " + str(datetime.datetime.now()) + "\n")
1323 LogFile.setup(self, game.board, game.players)
1325 elif self.phase == 1:
1326 for message in self.logged[len(self.logged)-2:]:
1327 self.log.write(str(message[0]) + " : " + message[1] + "\n")
1329 self.phase = (self.phase + 1) % 2
1333 ending = self.logged[len(self.logged)-1]
1334 self.log.write(str(ending[0]) + " : " + ending[1] + "\n")
1335 self.log.write("# EOF\n")
1336 if self.log != sys.stdout:
1340 class HeadRequest(urllib2.Request):
1341 def get_method(self):
1344 class HttpGetter(StoppableThread):
1345 def __init__(self, address):
1346 StoppableThread.__init__(self)
1347 self.address = address
1348 self.log = urllib2.urlopen(address)
1350 self.lock = threading.RLock() #lock for access of self.state
1351 self.cond = threading.Condition() # conditional
1354 while not self.stopped():
1355 line = self.log.readline()
1357 date_mod = datetime.datetime.strptime(self.log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1360 next_log = urllib2.urlopen(HeadRequest(self.address))
1361 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1362 while date_new <= date_mod and not self.stopped():
1363 next_log = urllib2.urlopen(HeadRequest(self.address))
1364 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1368 self.log = urllib2.urlopen(self.address)
1369 line = self.log.readline()
1372 self.lines.append(line)
1373 self.cond.notifyAll()
1376 #sys.stderr.write(" HttpGetter got \'" + str(line) + "\'\n")
1385 def __init__(self, address):
1386 self.getter = HttpGetter(address)
1390 self.getter.cond.acquire()
1391 while len(self.getter.lines) == 0:
1392 self.getter.cond.wait()
1394 result = self.getter.lines[0]
1395 self.getter.lines = self.getter.lines[1:]
1396 self.getter.cond.release()
1409 def log_init(board, players):
1411 l.setup(board, players)
1419 # A thread that runs the game
1420 class GameThread(StoppableThread):
1421 def __init__(self, board, players):
1422 StoppableThread.__init__(self)
1424 self.players = players
1425 self.state = {"turn" : None} # The game state
1426 self.error = 0 # Whether the thread exits with an error
1427 self.lock = threading.RLock() #lock for access of self.state
1428 self.cond = threading.Condition() # conditional for some reason, I forgot
1429 self.final_result = ""
1433 # Run the game (run in new thread with start(), run in current thread with run())
1436 while not self.stopped():
1438 for p in self.players:
1440 if isinstance(p, NetworkSender):
1441 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
1443 self.state["turn"] = p
1446 [x,y] = p.select() # Player selects a square
1453 result = self.board.select(x, y, colour = p.colour)
1454 for p2 in self.players:
1455 p2.update(result) # Inform players of what happened
1460 target = self.board.grid[x][y]
1461 if isinstance(graphics, GraphicsThread):
1463 graphics.state["moves"] = self.board.possible_moves(target)
1464 graphics.state["select"] = target
1466 time.sleep(turn_delay)
1469 if len(self.board.possible_moves(target)) == 0:
1470 #print "Piece cannot move"
1472 if isinstance(graphics, GraphicsThread):
1474 graphics.state["moves"] = None
1475 graphics.state["select"] = None
1476 graphics.state["dest"] = None
1480 [x2,y2] = p.get_move() # Player selects a destination
1487 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1490 self.board.update_move(x, y, x2, y2)
1492 for p2 in self.players:
1493 p2.update(result) # Inform players of what happened
1497 if isinstance(graphics, GraphicsThread):
1499 graphics.state["moves"] = [[x2,y2]]
1501 time.sleep(turn_delay)
1503 if isinstance(graphics, GraphicsThread):
1505 graphics.state["select"] = None
1506 graphics.state["dest"] = None
1507 graphics.state["moves"] = None
1509 # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
1510 # except Exception,e:
1511 # result = e.message
1512 # #sys.stderr.write(result + "\n")
1516 # self.final_result = self.state["turn"].colour + " " + e.message
1518 end = self.board.end_condition()
1522 self.final_result = self.state["turn"].colour + " " + end
1524 self.final_result = end
1531 for p2 in self.players:
1532 p2.quit(self.final_result)
1534 log(self.final_result)
1536 if isinstance(graphics, GraphicsThread):
1540 # A thread that replays a log file
1541 class ReplayThread(GameThread):
1542 def __init__(self, players, src, end=False,max_moves=None):
1543 self.board = Board(style="empty")
1544 self.board.max_moves = max_moves
1545 GameThread.__init__(self, self.board, players)
1549 self.reset_board(self.src.readline())
1551 def reset_board(self, line):
1554 while line != "# Start game" and line != "# EOF":
1557 line = self.src.readline().strip(" \r\n")
1561 line = self.src.readline().strip(" \r\n")
1564 self_str += line + "\n"
1566 if self.players[0].name == "dummy" and self.players[1].name == "dummy":
1567 line = self.src.readline().strip(" \r\n")
1570 tokens = line.split(" ")
1571 types = map(lambda e : e.strip("[] ,'"), tokens[2:4])
1572 for i in range(len(types)):
1573 if types[i][0] == "?":
1574 types[i] = "unknown"
1576 agent_str += tokens[0] + " " + tokens[1] + " " + str(types) + " ".join(tokens[4:]) + "\n"
1577 line = self.src.readline().strip(" \r\n")
1579 for p in self.players:
1580 p.reset_board(agent_str)
1583 self.board.reset_board(self_str)
1589 line = self.src.readline().strip(" \r\n")
1590 while line != "# EOF":
1600 line = self.src.readline().strip(" \r\n")
1603 tokens = line.split(" ")
1604 if tokens[0] == "white" or tokens[0] == "black":
1605 self.reset_board(line)
1607 line = self.src.readline().strip(" \r\n")
1610 move = line.split(":")
1611 move = move[len(move)-1].strip(" \r\n")
1612 tokens = move.split(" ")
1616 [x,y] = map(int, tokens[0:2])
1624 target = self.board.grid[x][y]
1626 if target.colour == "white":
1627 self.state["turn"] = self.players[0]
1629 self.state["turn"] = self.players[1]
1631 move_piece = (tokens[2] == "->")
1633 [x2,y2] = map(int, tokens[len(tokens)-2:])
1635 if isinstance(graphics, GraphicsThread):
1637 graphics.state["select"] = target
1640 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
1641 if isinstance(graphics, GraphicsThread):
1643 graphics.state["moves"] = self.board.possible_moves(target)
1644 time.sleep(turn_delay)
1646 self.board.update_move(x, y, x2, y2)
1647 if isinstance(graphics, GraphicsThread):
1649 graphics.state["moves"] = [[x2,y2]]
1650 time.sleep(turn_delay)
1652 graphics.state["select"] = None
1653 graphics.state["moves"] = None
1654 graphics.state["dest"] = None
1660 for p in self.players:
1664 line = self.src.readline().strip(" \r\n")
1667 end = self.board.end_condition()
1669 self.final_result = end
1687 if self.end and isinstance(graphics, GraphicsThread):
1689 pass # Let the user stop the display
1690 elif not self.end and self.board.end_condition() == None:
1692 # Work out the last move
1694 t = last_line.split(" ")
1695 if t[len(t)-2] == "black":
1696 self.players.reverse()
1697 elif t[len(t)-2] == "white":
1699 elif self.state["turn"] != None and self.state["turn"].colour == "white":
1700 self.players.reverse()
1703 game = GameThread(self.board, self.players)
1710 def opponent(colour):
1711 if colour == "white":
1722 # Dictionary that stores the unicode character representations of the different pieces
1723 # Chess was clearly the reason why unicode was invented
1724 # For some reason none of the pygame chess implementations I found used them!
1725 piece_char = {"white" : {"king" : u'\u2654',
1726 "queen" : u'\u2655',
1728 "bishop" : u'\u2657',
1729 "knight" : u'\u2658',
1732 "black" : {"king" : u'\u265A',
1733 "queen" : u'\u265B',
1735 "bishop" : u'\u265D',
1736 "knight" : u'\u265E',
1740 images = {"white" : {}, "black" : {}}
1741 small_images = {"white" : {}, "black" : {}}
1743 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
1745 # Get the font sizes
1746 l_size = 5*(grid_sz[0] / 8)
1747 s_size = 3*(grid_sz[0] / 8)
1749 for c in piece_char.keys():
1752 for p in piece_char[c].keys():
1753 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
1754 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})
1756 for p in piece_char[c].keys():
1757 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1758 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1759 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1760 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1763 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
1764 if not os.path.exists(image_dir):
1765 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
1766 for c in piece_char.keys():
1767 for p in piece_char[c].keys():
1768 images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
1769 small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
1770 # --- images.py --- #
1771 graphics_enabled = True
1775 graphics_enabled = False
1780 # A thread to make things pretty
1781 class GraphicsThread(StoppableThread):
1782 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1783 StoppableThread.__init__(self)
1787 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1788 pygame.display.set_caption(title)
1790 #print "Initialised properly"
1792 self.grid_sz = grid_sz[:]
1793 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
1795 self.lock = threading.RLock()
1796 self.cond = threading.Condition()
1799 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
1802 create_images(grid_sz)
1805 for c in images.keys():
1806 for p in images[c].keys():
1807 images[c][p] = images[c][p].convert(self.window)
1808 small_images[c][p] = small_images[c][p].convert(self.window)
1815 # On the run from the world
1818 while not self.stopped():
1820 #print "Display grid"
1821 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
1823 #print "Display overlay"
1826 #print "Display pieces"
1827 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
1829 pygame.display.flip()
1831 for event in pygame.event.get():
1832 if event.type == pygame.QUIT:
1833 if isinstance(game, GameThread):
1835 game.final_result = ""
1836 if game.state["turn"] != None:
1837 game.final_result = game.state["turn"].colour + " "
1838 game.final_result += "terminated"
1842 elif event.type == pygame.MOUSEBUTTONDOWN:
1843 self.mouse_down(event)
1844 elif event.type == pygame.MOUSEBUTTONUP:
1845 self.mouse_up(event)
1852 self.message("Game ends, result \""+str(game.final_result) + "\"")
1855 # Wake up anyone who is sleeping
1860 pygame.quit() # Time to say goodbye
1862 # Mouse release event handler
1863 def mouse_up(self, event):
1864 if event.button == 3:
1866 self.state["overlay"] = None
1867 elif event.button == 2:
1869 self.state["coverage"] = None
1871 # Mouse click event handler
1872 def mouse_down(self, event):
1873 if event.button == 1:
1874 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
1875 if isinstance(game, GameThread):
1877 p = game.state["turn"]
1882 if isinstance(p, HumanPlayer):
1884 s = self.board.grid[m[0]][m[1]]
1885 select = self.state["select"]
1887 if s != None and s.colour != p.colour:
1888 self.message("Wrong colour") # Look at all this user friendliness!
1891 # Notify human player of move
1894 self.state["select"] = s
1895 self.state["dest"] = None
1904 if self.state["moves"] == None:
1907 if not m in self.state["moves"]:
1908 self.message("Illegal Move") # I still think last year's mouse interface was adequate
1913 if self.state["dest"] == None:
1915 self.state["dest"] = m
1916 self.state["select"] = None
1917 self.state["moves"] = None
1920 elif event.button == 3:
1921 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1922 if isinstance(game, GameThread):
1924 p = game.state["turn"]
1929 if isinstance(p, HumanPlayer):
1931 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
1933 elif event.button == 2:
1934 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1935 if isinstance(game, GameThread):
1937 p = game.state["turn"]
1942 if isinstance(p, HumanPlayer):
1944 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
1949 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
1950 # Draw square over the selected piece
1952 select = self.state["select"]
1954 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
1955 square_img.fill(pygame.Color(0,255,0,64))
1956 self.window.blit(square_img, mp)
1957 # If a piece is selected, draw all reachable squares
1958 # (This quality user interface has been patented)
1960 m = self.state["moves"]
1962 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
1964 mp = [self.grid_sz[i] * move[i] for i in range(2)]
1965 self.window.blit(square_img, mp)
1966 # If a piece is overlayed, show all squares that it has a probability to reach
1968 m = self.state["overlay"]
1973 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
1974 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
1975 self.window.blit(square_img, mp)
1976 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
1977 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
1978 self.window.blit(text, mp)
1980 # If a square is selected, highlight all pieces that have a probability to reach it
1982 m = self.state["coverage"]
1985 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
1986 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
1987 self.window.blit(square_img, mp)
1988 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
1989 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
1990 self.window.blit(text, mp)
1991 # Draw a square where the mouse is
1992 # This also serves to indicate who's turn it is
1994 if isinstance(game, GameThread):
1996 turn = game.state["turn"]
2000 if isinstance(turn, HumanPlayer):
2001 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
2002 square_img.fill(pygame.Color(0,0,255,128))
2003 if turn.colour == "white":
2004 c = pygame.Color(255,255,255)
2006 c = pygame.Color(0,0,0)
2007 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
2008 self.window.blit(square_img, mp)
2010 # Message in a bottle
2011 def message(self, string, pos = None, colour = None, font_size = 20):
2012 #print "Drawing message..."
2013 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2015 colour = pygame.Color(0,0,0)
2017 text = font.render(string, 1, colour)
2020 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
2021 s.fill(pygame.Color(128,128,128))
2023 tmp = self.window.get_size()
2026 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
2028 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
2031 rect = (pos[0], pos[1], text.get_width(), text.get_height())
2033 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
2034 self.window.blit(s, pos)
2035 self.window.blit(text, pos)
2037 pygame.display.flip()
2039 def getstr(self, prompt = None):
2040 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
2041 s.blit(self.window, (0,0))
2047 self.message(prompt)
2048 self.message(result, pos = (0, 1))
2051 for event in pygame.event.get():
2052 if event.type == pygame.QUIT:
2054 if event.type == pygame.KEYDOWN:
2055 if event.key == pygame.K_BACKSPACE:
2056 result = result[0:len(result)-1]
2057 self.window.blit(s, (0,0)) # Revert the display
2062 if event.unicode == '\r':
2065 result += str(event.unicode)
2070 # Function to pick a button
2071 def SelectButton(self, choices, prompt = None, font_size=20):
2073 #print "Select button called!"
2074 self.board.display_grid(self.window, self.grid_sz)
2076 self.message(prompt)
2077 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2079 sz = self.window.get_size()
2082 for i in range(len(choices)):
2085 text = font.render(c, 1, pygame.Color(0,0,0))
2086 p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
2087 targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
2090 mp =pygame.mouse.get_pos()
2091 for i in range(len(choices)):
2093 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
2094 font_colour = pygame.Color(255,0,0)
2095 box_colour = pygame.Color(0,0,255,128)
2097 font_colour = pygame.Color(0,0,0)
2098 box_colour = pygame.Color(128,128,128)
2100 text = font.render(c, 1, font_colour)
2101 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
2103 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
2104 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
2105 self.window.blit(s, targets[i][0:2])
2108 pygame.display.flip()
2110 for event in pygame.event.get():
2111 if event.type == pygame.QUIT:
2113 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
2114 for i in range(len(targets)):
2116 if event.pos[0] > t[0] and event.pos[0] < t[2]:
2117 if event.pos[1] > t[1] and event.pos[1] < t[3]:
2119 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
2122 # Function to pick players in a nice GUI way
2123 def SelectPlayers(self, players = []):
2126 #print "SelectPlayers called"
2128 missing = ["white", "black"]
2130 missing.remove(p.colour)
2132 for colour in missing:
2135 choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
2137 players.append(HumanPlayer("human", colour))
2140 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2141 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2142 internal_agents.remove(('InternalAgent', InternalAgent))
2143 if len(internal_agents) > 0:
2144 choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
2149 agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
2150 players.append(agent[1](agent[0], colour))
2154 from tkFileDialog import askopenfilename
2155 root = Tkinter.Tk() # Need a root to make Tkinter behave
2156 root.withdraw() # Some sort of magic incantation
2157 path = askopenfilename(parent=root, initialdir="../agents",title=
2160 return self.SelectPlayers()
2161 players.append(make_player(path, colour))
2166 self.board.display_grid(self.window, self.grid_sz)
2167 pygame.display.flip()
2168 path = self.getstr(prompt = "Enter path:")
2173 return self.SelectPlayers()
2176 p = make_player(path, colour)
2178 self.board.display_grid(self.window, self.grid_sz)
2179 pygame.display.flip()
2180 self.message("Invalid path!")
2186 while address == "":
2187 self.board.display_grid(self.window, self.grid_sz)
2189 address = self.getstr(prompt = "Address? (leave blank for server)")
2196 map(int, address.split("."))
2198 self.board.display_grid(self.window, self.grid_sz)
2199 self.message("Invalid IPv4 address!")
2202 players.append(NetworkReceiver(colour, address))
2205 #print str(self) + ".SelectPlayers returns " + str(players)
2210 # --- graphics.py --- #
2211 #!/usr/bin/python -u
2213 # Do you know what the -u does? It unbuffers stdin and stdout
2214 # I can't remember why, but last year things broke without that
2217 UCC::Progcomp 2013 Quantum Chess game
2218 @author Sam Moore [SZM] "matches"
2219 @copyright The University Computer Club, Incorporated
2220 (ie: You can copy it for not for profit purposes)
2223 # system python modules or whatever they are called
2229 [game, graphics] = [None, None]
2231 def make_player(name, colour):
2233 if name[1:] == "human":
2234 return HumanPlayer(name, colour)
2235 s = name[1:].split(":")
2236 if s[0] == "network":
2240 return NetworkReceiver(colour, address)
2241 if s[0] == "internal":
2244 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2245 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2246 internal_agents.remove(('InternalAgent', InternalAgent))
2249 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
2250 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2253 for a in internal_agents:
2255 return a[1](name, colour)
2257 sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
2258 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2263 return ExternalAgent(name, colour)
2267 # The main function! It does the main stuff!
2270 # Apparently python will silently treat things as local unless you do this
2271 # Anyone who says "You should never use a global variable" can die in a fire
2276 global agent_timeout
2279 global graphics_enabled
2280 global always_reveal_states
2288 # Get the important warnings out of the way
2289 if platform.system() == "Windows":
2290 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
2291 if platform.release() == "Vista":
2292 sys.stderr.write(sys.argv[0] + " : God help you.\n")
2297 while i < len(argv)-1:
2301 p = make_player(arg, colour)
2302 if not isinstance(p, Player):
2303 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
2306 if colour == "white":
2308 elif colour == "black":
2311 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
2314 # Option parsing goes here
2315 if arg[1] == '-' and arg[2:] == "classical":
2317 elif arg[1] == '-' and arg[2:] == "quantum":
2319 elif arg[1] == '-' and arg[2:] == "reveal":
2320 always_reveal_states = True
2321 elif (arg[1] == '-' and arg[2:] == "graphics"):
2322 graphics_enabled = not graphics_enabled
2323 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
2324 # Load game from file
2325 if len(arg[2:].split("=")) == 1:
2326 src_file = sys.stdin
2328 f = arg[2:].split("=")[1]
2329 if f[0:7] == "http://":
2330 src_file = HttpReplay(f)
2332 src_file = open(f.split(":")[0], "r", 0)
2334 if len(f.split(":")) == 2:
2335 max_moves = int(f.split(":")[1])
2337 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
2339 if len(arg[2:].split("=")) == 1:
2340 log_files.append(LogFile(sys.stdout))
2342 f = arg[2:].split("=")[1]
2344 log_files.append(ShortLog(f[1:]))
2346 log_files.append(LogFile(open(f, "w", 0)))
2347 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
2349 if len(arg[2:].split("=")) == 1:
2352 turn_delay = float(arg[2:].split("=")[1])
2354 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
2356 if len(arg[2:].split("=")) == 1:
2359 agent_timeout = float(arg[2:].split("=")[1])
2361 elif (arg[1] == '-' and arg[2:] == "help"):
2363 os.system("less data/help.txt") # The best help function
2369 # Construct a GameThread! Make it global! Damn the consequences!
2371 if src_file != None:
2372 # Hack to stop ReplayThread from exiting
2373 #if len(players) == 0:
2374 # players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
2376 # Normally the ReplayThread exits if there are no players
2377 # TODO: Decide which behaviour to use, and fix it
2378 end = (len(players) == 0)
2380 players = [Player("dummy", "white"), Player("dummy", "black")]
2381 elif len(players) != 2:
2382 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2383 if graphics_enabled:
2384 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
2386 game = ReplayThread(players, src_file, end=end, max_moves=max_moves)
2388 board = Board(style)
2389 board.max_moves = max_moves
2390 game = GameThread(board, players)
2396 if graphics_enabled == True:
2398 graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
2402 sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
2403 graphics_enabled = False
2405 # If there are no players listed, display a nice pretty menu
2406 if len(players) != 2:
2407 if graphics != None:
2408 players = graphics.SelectPlayers(players)
2410 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2413 # If there are still no players, quit
2414 if players == None or len(players) != 2:
2415 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
2419 # Wrap NetworkSender players around original players if necessary
2420 for i in range(len(players)):
2421 if isinstance(players[i], NetworkReceiver):
2422 players[i].board = board # Network players need direct access to the board
2423 for j in range(len(players)):
2426 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
2428 players[j] = NetworkSender(players[j], players[i].address)
2429 players[j].board = board
2431 # Connect the networked players
2433 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
2434 if graphics != None:
2435 graphics.board.display_grid(graphics.window, graphics.grid_sz)
2436 graphics.message("Connecting to " + p.colour + " player...")
2440 # If using windows, select won't work; use horrible TimeoutPlayer hack
2441 if agent_timeout > 0:
2442 if platform.system() == "Windows":
2443 for i in range(len(players)):
2444 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
2445 players[i] = TimeoutPlayer(players[i], agent_timeout)
2449 # InternalAgents get wrapped to an ExternalAgent when there is a timeout
2450 # This is not confusing at all.
2451 for i in range(len(players)):
2452 if isinstance(players[i], InternalAgent):
2453 players[i] = ExternalWrapper(players[i])
2461 log_init(game.board, players)
2464 if graphics != None:
2465 game.start() # This runs in a new thread
2471 error = game.error + graphics.error
2480 if src_file != None and src_file != sys.stdin:
2485 # This is how python does a main() function...
2486 if __name__ == "__main__":
2488 sys.exit(main(sys.argv))
2489 except KeyboardInterrupt:
2490 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
2491 if isinstance(graphics, StoppableThread):
2493 graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
2495 if isinstance(game, StoppableThread):
2503 # EOF - created from make on Thu Jan 31 13:37:15 WST 2013