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)
17 self.types_revealed = [True, False] # Whether the types are known (by default the first type is always known at game start)
21 self.last_state = None
22 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
33 self.types_revealed = c.types_revealed[:]
35 self.last_state = None
36 self.move_pattern = None
40 # Make a string for the piece (used for debug)
42 return str(self.colour) + " " + str(self.current_type) + " " + str(self.types) + " at " + str(self.x) + ","+str(self.y)
44 # Draw the piece in a pygame surface
45 def draw(self, window, grid_sz = [80,80], style="quantum"):
47 # First draw the image corresponding to self.current_type
48 img = images[self.colour][self.current_type]
50 if style == "classical":
51 offset = [-rect.width/2, -rect.height/2]
53 offset = [-rect.width/2,-3*rect.height/4]
54 window.blit(img, (self.x * grid_sz[0] + grid_sz[0]/2 + offset[0], self.y * grid_sz[1] + grid_sz[1]/2 + offset[1]))
57 if style == "classical":
60 # Draw the two possible types underneath the current_type image
61 for i in range(len(self.types)):
62 if always_reveal_states == True or self.types_revealed[i] == True:
63 img = small_images[self.colour][self.types[i]]
65 img = small_images[self.colour]["unknown"] # If the type hasn't been revealed, show a placeholder
69 offset = [-rect.width/2,-rect.height/2]
72 target = (self.x * grid_sz[0] + grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])
74 target = (self.x * grid_sz[0] + 4*grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])
76 window.blit(img, target) # Blit shit
78 # Collapses the wave function!
80 if self.current_type == "unknown":
81 self.choice = random.randint(0,1)
82 self.current_type = self.types[self.choice]
83 self.types_revealed[self.choice] = True
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_revealed[0] == False or self.types_revealed[1] == False):
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 for c in ["black", "white"]:
114 del self.unrevealed_types[c]["unknown"]
119 # Add all the pieces with known primary types
120 for i in range(0, 2):
122 s = ["black", "white"][i]
126 c.append(Piece(s, 0, y, ["rook"]))
127 c.append(Piece(s, 1, y, ["knight"]))
128 c.append(Piece(s, 2, y, ["bishop"]))
129 k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
130 k.types_revealed[1] = True
131 k.current_type = "king"
134 c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
135 c.append(Piece(s, 5, y, ["bishop"]))
136 c.append(Piece(s, 6, y, ["knight"]))
137 c.append(Piece(s, 7, y, ["rook"]))
145 for x in range(0, w):
146 c.append(Piece(s, x, y, ["pawn"]))
149 types_left.update(piece_types)
150 del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
151 del types_left["unknown"] # We certainly don't want these!
154 self.grid[piece.x][piece.y] = piece
156 if len(piece.types) > 1:
158 if style == "agent": # Assign placeholder "unknown" secondary type
159 piece.types.append("unknown")
162 elif style == "quantum":
163 # The master allocates the secondary types
164 choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
165 types_left[choice] -= 1
166 if types_left[choice] <= 0:
167 del types_left[choice]
168 piece.types.append(choice)
169 elif style == "classical":
170 piece.types.append(piece.types[0])
171 piece.current_type = piece.types[0]
172 piece.types_revealed[1] = True
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])
184 def display_grid(self, window = None, grid_sz = [80,80]):
186 return # I was considering implementing a text only display, then I thought "Fuck that"
188 # The indentation is getting seriously out of hand...
189 for x in range(0, w):
190 for y in range(0, h):
192 c = pygame.Color(200,200,200)
194 c = pygame.Color(64,64,64)
195 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
197 def display_pieces(self, window = None, grid_sz = [80,80]):
200 for p in self.pieces["white"] + self.pieces["black"]:
201 p.draw(window, grid_sz, self.style)
203 # Draw the board in a pygame window
204 def display(self, window = None):
205 self.display_grid(window)
206 self.display_pieces(window)
214 if self.grid[x][y] == None:
216 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
217 raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
219 # Select a piece on the board (colour is the colour of whoever is doing the selecting)
220 def select(self, x,y, colour=None):
221 if not self.on_board(x, y): # Get on board everyone!
222 raise Exception("BOUNDS")
224 piece = self.grid[x][y]
226 raise Exception("EMPTY")
228 if colour != None and piece.colour != colour:
229 raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
231 # I'm not quite sure why I made this return a string, but screw logical design
232 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
235 # Update the board when a piece has been selected
236 # "type" is apparently reserved, so I'll use "state"
237 def update_select(self, x, y, type_index, state):
238 piece = self.grid[x][y]
239 if piece.types[type_index] == "unknown":
240 if not state in self.unrevealed_types[piece.colour].keys():
241 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
242 self.unrevealed_types[piece.colour][state] -= 1
243 if self.unrevealed_types[piece.colour][state] <= 0:
244 del self.unrevealed_types[piece.colour][state]
246 piece.types[type_index] = state
247 piece.types_revealed[type_index] = True
248 piece.current_type = state
250 if len(self.possible_moves(piece)) <= 0:
251 piece.deselect() # Piece can't move; deselect it
253 # Update the board when a piece has been moved
254 def update_move(self, x, y, x2, y2):
255 piece = self.grid[x][y]
256 self.grid[x][y] = None
257 taken = self.grid[x2][y2]
259 if taken.current_type == "king":
260 self.king[taken.colour] = None
261 self.pieces[taken.colour].remove(taken)
262 self.grid[x2][y2] = piece
266 # If the piece is a pawn, and it reaches the final row, it becomes a queen
267 # I know you are supposed to get a choice
268 # But that would be effort
269 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
270 if self.style == "classical":
271 piece.types[0] = "queen"
272 piece.types[1] = "queen"
274 piece.types[piece.choice] = "queen"
275 piece.current_type = "queen"
277 piece.deselect() # Uncollapse (?) the wavefunction!
280 # Update the board from a string
281 # Guesses what to do based on the format of the string
282 def update(self, result):
283 #print "Update called with \"" + str(result) + "\""
284 # String always starts with 'x y'
286 s = result.split(" ")
287 [x,y] = map(int, s[0:2])
289 raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
291 piece = self.grid[x][y]
293 raise Exception("EMPTY")
295 # If a piece is being moved, the third token is '->'
296 # We could get away with just using four integers, but that wouldn't look as cool
298 # Last two tokens are the destination
300 [x2,y2] = map(int, s[3:])
302 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
304 # Move the piece (take opponent if possible)
305 self.update_move(x, y, x2, y2)
308 # Otherwise we will just assume a piece has been selected
310 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
311 state = s[3] # The last token is a string identifying the type
313 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
316 self.update_select(x, y, type_index, state)
320 # Gets each piece that could reach the given square and the probability that it could reach that square
321 # Will include allied pieces that defend the attacker
322 def coverage(self, x, y, colour = None, reject_allied = True):
326 pieces = self.pieces["white"] + self.pieces["black"]
328 pieces = self.pieces[colour]
331 prob = self.probability_grid(p, reject_allied)[x][y]
333 result.update({p : prob})
342 # Associates each square with a probability that the piece could move into it
343 # Look, I'm doing all the hard work for you here...
344 def probability_grid(self, p, reject_allied = True):
346 result = [[0.0] * w for _ in range(h)]
347 if not isinstance(p, Piece):
350 if p.current_type != "unknown":
351 #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
352 for point in self.possible_moves(p, reject_allied):
353 result[point[0]][point[1]] = 1.0
357 for i in range(len(p.types)):
360 if t == "unknown" or p.types_revealed[i] == False:
362 for t2 in self.unrevealed_types[p.colour].keys():
363 total_types += self.unrevealed_types[p.colour][t2]
365 for t2 in self.unrevealed_types[p.colour].keys():
366 prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
368 for point in self.possible_moves(p, reject_allied):
369 result[point[0]][point[1]] += prob2 * prob
373 for point in self.possible_moves(p, reject_allied):
374 result[point[0]][point[1]] += prob
377 p.current_type = "unknown"
380 def prob_is_type(self, p, state):
383 for i in range(len(p.types)):
388 if t == "unknown" or p.types_revealed[i] == False:
390 for t2 in self.unrevealed_types[p.colour].keys():
391 total_prob += self.unrevealed_types[p.colour][t2]
392 for t2 in self.unrevealed_types[p.colour].keys():
394 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
398 # Get all squares that the piece could move into
399 # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
400 # reject_allied indicates whether squares occupied by allied pieces will be removed
401 # (set to false to check for defense)
402 def possible_moves(self, p, reject_allied = True):
408 if p.current_type == "unknown":
409 raise Exception("SANITY: Piece state unknown")
410 # The below commented out code causes things to break badly
415 # result += self.possible_moves(p)
416 #p.current_type = "unknown"
419 if p.current_type == "king":
420 result = [[p.x-1,p.y],[p.x+1,p.y],[p.x,p.y-1],[p.x,p.y+1], [p.x-1,p.y-1],[p.x-1,p.y+1],[p.x+1,p.y-1],[p.x+1,p.y+1]]
421 elif p.current_type == "queen":
422 for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
423 result += self.scan(p.x, p.y, d[0], d[1])
424 elif p.current_type == "bishop":
425 for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
426 result += self.scan(p.x, p.y, d[0], d[1])
427 elif p.current_type == "rook":
428 for d in [[-1,0],[1,0],[0,-1],[0,1]]:
429 result += self.scan(p.x, p.y, d[0], d[1])
430 elif p.current_type == "knight":
431 # I would use two lines, but I'm not sure how python likes that
432 result = [[p.x-2, p.y-1], [p.x-2, p.y+1], [p.x+2, p.y-1], [p.x+2,p.y+1], [p.x-1,p.y-2], [p.x-1, p.y+2],[p.x+1,p.y-2],[p.x+1,p.y+2]]
433 elif p.current_type == "pawn":
434 if p.colour == "white":
436 # Pawn can't move forward into occupied square
437 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
438 result = [[p.x,p.y-1]]
439 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
440 if not self.on_board(f[0], f[1]):
442 if self.grid[f[0]][f[1]] != None: # Pawn can take diagonally
445 # Slightly embarrassing if the pawn jumps over someone on its first move...
446 if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
447 result.append([p.x, p.y-2])
449 # Vice versa for the black pawn
450 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
451 result = [[p.x,p.y+1]]
453 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
454 if not self.on_board(f[0], f[1]):
456 if self.grid[f[0]][f[1]] != None:
457 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
460 if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
461 result.append([p.x, p.y+2])
463 #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
465 # Remove illegal moves
466 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
467 for point in result[:]:
469 if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
470 result.remove(point) # Remove locations outside the board
472 g = self.grid[point[0]][point[1]]
474 if g != None and (g.colour == p.colour and reject_allied == True):
475 result.remove(point) # Remove allied pieces
481 # Scans in a direction until it hits a piece, returns all squares in the line
482 # (includes the final square (which contains a piece), but not the original square)
483 def scan(self, x, y, vx, vy):
491 if not self.on_board(xx, yy):
495 g = self.grid[xx][yy]
503 # I typed the full statement about 30 times before writing this function...
504 def on_board(self, x, y):
505 return (x >= 0 and x < w) and (y >= 0 and y < h)
512 agent_timeout = -1.0 # Timeout in seconds for AI players to make moves
513 # WARNING: Won't work for windows based operating systems
515 if platform.system() == "Windows":
516 agent_timeout = -1 # Hence this
518 # A player who can't play
520 def __init__(self, name, colour):
524 def update(self, result):
527 # Player that runs from another process
528 class ExternalAgent(Player):
531 def __init__(self, name, colour):
532 Player.__init__(self, name, colour)
533 self.p = subprocess.Popen(name,bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,universal_newlines=True)
535 self.send_message(colour)
537 def send_message(self, s):
538 if agent_timeout > 0.0:
539 ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
541 ready = [self.p.stdin]
542 if self.p.stdin in ready:
543 #sys.stderr.write("Writing \'" + s + "\' to " + str(self.p) + "\n")
545 self.p.stdin.write(s + "\n")
547 raise Exception("UNRESPONSIVE")
549 raise Exception("TIMEOUT")
551 def get_response(self):
552 if agent_timeout > 0.0:
553 ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
555 ready = [self.p.stdout]
556 if self.p.stdout in ready:
557 #sys.stderr.write("Reading from " + str(self.p) + " 's stdout...\n")
559 result = self.p.stdout.readline().strip("\r\n")
560 #sys.stderr.write("Read \'" + result + "\' from " + str(self.p) + "\n")
562 except: # Exception, e:
563 raise Exception("UNRESPONSIVE")
565 raise Exception("TIMEOUT")
569 self.send_message("SELECTION?")
570 line = self.get_response()
573 result = map(int, line.split(" "))
575 raise Exception("GIBBERISH \"" + str(line) + "\"")
578 def update(self, result):
579 #print "Update " + str(result) + " called for AgentPlayer"
580 self.send_message(result)
585 self.send_message("MOVE?")
586 line = self.get_response()
589 result = map(int, line.split(" "))
591 raise Exception("GIBBERISH \"" + str(line) + "\"")
594 def quit(self, final_result):
596 self.send_message("QUIT " + final_result)
600 # So you want to be a player here?
601 class HumanPlayer(Player):
602 def __init__(self, name, colour):
603 Player.__init__(self, name, colour)
605 # Select your preferred account
607 if isinstance(graphics, GraphicsThread):
608 # Basically, we let the graphics thread do some shit and then return that information to the game thread
609 graphics.cond.acquire()
610 # We wait for the graphics thread to select a piece
611 while graphics.stopped() == False and graphics.state["select"] == None:
612 graphics.cond.wait() # The difference between humans and machines is that humans sleep
613 select = graphics.state["select"]
616 graphics.cond.release()
617 if graphics.stopped():
619 return [select.x, select.y]
621 # Since I don't display the board in this case, I'm not sure why I filled it in...
623 sys.stdout.write("SELECTION?\n")
625 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
627 sys.stderr.write("ILLEGAL GIBBERISH\n")
629 # It's your move captain
631 if isinstance(graphics, GraphicsThread):
632 graphics.cond.acquire()
633 while graphics.stopped() == False and graphics.state["dest"] == None:
635 graphics.cond.release()
637 return graphics.state["dest"]
641 sys.stdout.write("MOVE?\n")
643 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
645 sys.stderr.write("ILLEGAL GIBBERISH\n")
648 # Are you sure you want to quit?
649 def quit(self, final_result):
651 sys.stdout.write("QUIT " + final_result + "\n")
653 # Completely useless function
654 def update(self, result):
655 if isinstance(graphics, GraphicsThread):
658 sys.stdout.write(result + "\n")
661 # Default internal player (makes random moves)
662 class InternalAgent(Player):
663 def __init__(self, name, colour):
664 Player.__init__(self, name, colour)
667 self.board = Board(style = "agent")
671 def update(self, result):
673 self.board.update(result)
676 def quit(self, final_result):
679 class AgentRandom(InternalAgent):
680 def __init__(self, name, colour):
681 InternalAgent.__init__(self, name, colour)
685 self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
687 # Check that the piece has some possibility to move
688 tmp = self.choice.current_type
689 if tmp == "unknown": # For unknown pieces, try both types
690 for t in self.choice.types:
693 self.choice.current_type = t
694 all_moves += self.board.possible_moves(self.choice)
696 all_moves = self.board.possible_moves(self.choice)
697 self.choice.current_type = tmp
698 if len(all_moves) > 0:
700 return [self.choice.x, self.choice.y]
703 moves = self.board.possible_moves(self.choice)
704 move = moves[random.randint(0, len(moves)-1)]
708 # Terrible, terrible hacks
710 def run_agent(agent):
711 #sys.stderr.write(sys.argv[0] + " : Running agent " + str(agent) + "\n")
713 line = sys.stdin.readline().strip(" \r\n")
714 if line == "SELECTION?":
715 #sys.stderr.write(sys.argv[0] + " : Make selection\n")
716 [x,y] = agent.select() # Gets your agent's selection
717 #sys.stderr.write(sys.argv[0] + " : Selection was " + str(agent.choice) + "\n")
718 sys.stdout.write(str(x) + " " + str(y) + "\n")
719 elif line == "MOVE?":
720 #sys.stderr.write(sys.argv[0] + " : Make move\n")
721 [x,y] = agent.get_move() # Gets your agent's move
722 sys.stdout.write(str(x) + " " + str(y) + "\n")
723 elif line.split(" ")[0] == "QUIT":
724 #sys.stderr.write(sys.argv[0] + " : Quitting\n")
725 agent.quit(" ".join(line.split(" ")[1:])) # Quits the game
728 agent.update(line) # Updates agent.board
734 class ExternalWrapper(ExternalAgent):
735 def __init__(self, agent):
736 run = "python -u -c \"import sys;import os;from qchess import *;agent = " + agent.__class__.__name__ + "('" + agent.name + "','"+agent.colour+"');sys.stdin.readline();sys.exit(run_agent(agent))\""
738 ExternalAgent.__init__(self, run, agent.colour)
742 # --- player.py --- #
746 class AgentBishop(InternalAgent): # Inherits from InternalAgent (in qchess)
747 def __init__(self, name, colour):
748 InternalAgent.__init__(self, name, colour)
749 self.value = {"pawn" : 1, "bishop" : 3, "knight" : 3, "rook" : 5, "queen" : 9, "king" : 100, "unknown" : 4}
751 self.aggression = 2.0 # Multiplier for scoring due to aggressive actions
752 self.defence = 1.0 # Multiplier for scoring due to defensive actions
754 self.depth = 0 # Current depth
755 self.max_depth = 2 # Recurse this many times (for some reason, makes more mistakes when this is increased???)
756 self.recurse_for = -1 # Recurse for the best few moves each times (less than 0 = all moves)
758 for p in self.board.pieces["white"] + self.board.pieces["black"]:
760 p.selected_moves = None
764 def get_value(self, piece):
767 return float(self.value[piece.types[0]] + self.value[piece.types[1]]) / 2.0
769 # Score possible moves for the piece
771 def prioritise_moves(self, piece):
773 #sys.stderr.write(sys.argv[0] + " : " + str(self) + " prioritise called for " + str(piece) + "\n")
777 grid = self.board.probability_grid(piece)
778 #sys.stderr.write("\t Probability grid " + str(grid) + "\n")
782 if grid[x][y] < 0.3: # Throw out moves with < 30% probability
783 #sys.stderr.write("\tReject " + str(x) + "," + str(y) + " (" + str(grid[x][y]) + ")\n")
786 target = self.board.grid[x][y]
791 # Get total probability that the move is protected
792 [xx,yy] = [piece.x, piece.y]
793 [piece.x, piece.y] = [x, y]
794 self.board.grid[x][y] = piece
795 self.board.grid[xx][yy] = None
797 defenders = self.board.coverage(x, y, piece.colour, reject_allied = False)
799 for d in defenders.keys():
800 d_prob += defenders[d]
801 if len(defenders.keys()) > 0:
802 d_prob /= float(len(defenders.keys()))
807 # Get total probability that the move is threatened
808 attackers = self.board.coverage(x, y, opponent(piece.colour), reject_allied = False)
810 for a in attackers.keys():
811 a_prob += attackers[a]
812 if len(attackers.keys()) > 0:
813 a_prob /= float(len(attackers.keys()))
818 self.board.grid[x][y] = target
819 self.board.grid[xx][yy] = piece
820 [piece.x, piece.y] = [xx, yy]
824 value = self.aggression * (1.0 + d_prob) * self.get_value(target) - self.defence * (1.0 - d_prob) * a_prob * self.get_value(piece)
826 # Adjust score based on movement of piece out of danger
827 attackers = self.board.coverage(piece.x, piece.y, opponent(piece.colour))
829 for a in attackers.keys():
830 s_prob += attackers[a]
831 if len(attackers.keys()) > 0:
832 s_prob /= float(len(attackers.keys()))
836 value += self.defence * s_prob * self.get_value(piece)
838 # Adjust score based on probability that the move is actually possible
839 moves.append([[x, y], grid[x][y] * value])
841 moves.sort(key = lambda e : e[1], reverse = True)
842 #sys.stderr.write(sys.argv[0] + ": Moves for " + str(piece) + " are " + str(moves) + "\n")
844 piece.last_moves = moves
845 piece.selected_moves = None
852 def select_best(self, colour):
856 for p in self.board.pieces[colour]:
857 self.choice = p # Temporarily pick that piece
858 m = self.prioritise_moves(p)
860 all_moves.update({p : m[0]})
862 if len(all_moves.items()) <= 0:
866 opts = all_moves.items()
867 opts.sort(key = lambda e : e[1][1], reverse = True)
869 if self.depth >= self.max_depth:
873 if self.recurse_for >= 0:
874 opts = opts[0:self.recurse_for]
875 #sys.stderr.write(sys.argv[0] + " : Before recurse, options are " + str(opts) + "\n")
877 # Take the best few moves, and recurse
878 for choice in opts[0:self.recurse_for]:
879 [xx,yy] = [choice[0].x, choice[0].y] # Remember position
880 [nx,ny] = choice[1][0] # Target
881 [choice[0].x, choice[0].y] = [nx, ny] # Set position
882 target = self.board.grid[nx][ny] # Remember piece in spot
883 self.board.grid[xx][yy] = None # Remove piece
884 self.board.grid[nx][ny] = choice[0] # Replace with moving piece
887 best_enemy_move = self.select_best(opponent(choice[0].colour))
888 choice[1][1] -= best_enemy_move[1][1] / float(self.depth + 1.0)
890 [choice[0].x, choice[0].y] = [xx, yy] # Restore position
891 self.board.grid[nx][ny] = target # Restore taken piece
892 self.board.grid[xx][yy] = choice[0] # Restore moved piece
896 opts.sort(key = lambda e : e[1][1], reverse = True)
897 #sys.stderr.write(sys.argv[0] + " : After recurse, options are " + str(opts) + "\n")
904 # Returns [x,y] of selected piece
906 #sys.stderr.write("Getting choice...")
907 self.choice = self.select_best(self.colour)[0]
908 #sys.stderr.write(" Done " + str(self.choice)+"\n")
909 return [self.choice.x, self.choice.y]
911 # Returns [x,y] of square to move selected piece into
913 #sys.stderr.write("Choice is " + str(self.choice) + "\n")
914 self.choice.selected_moves = self.choice.last_moves
915 moves = self.prioritise_moves(self.choice)
919 return InternalAgent.get_move(self)
921 # --- agent_bishop.py --- #
922 import multiprocessing
924 # Hacky alternative to using select for timing out players
926 # WARNING: Do not wrap around HumanPlayer or things breakify
927 # WARNING: Do not use in general or things breakify
929 class Sleeper(multiprocessing.Process):
930 def __init__(self, timeout):
931 multiprocessing.Process.__init__(self)
932 self.timeout = timeout
935 time.sleep(self.timeout)
938 class Worker(multiprocessing.Process):
939 def __init__(self, function, args, q):
940 multiprocessing.Process.__init__(self)
941 self.function = function
946 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args)
947 self.q.put(self.function(*self.args))
951 def TimeoutFunction(function, args, timeout):
952 q = multiprocessing.Queue()
953 w = Worker(function, args, q)
957 while True: # Busy loop of crappyness
962 #print "TimeoutFunction gets " + str(result)
964 elif not s.is_alive():
967 raise Exception("TIMEOUT")
972 # A player that wraps another player and times out its moves
974 # A (crappy) alternative to the use of select()
975 class TimeoutPlayer(Player):
976 def __init__(self, base_player, timeout):
977 Player.__init__(self, base_player.name, base_player.colour)
978 self.base_player = base_player
979 self.timeout = timeout
982 return TimeoutFunction(self.base_player.select, [], self.timeout)
986 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
988 def update(self, result):
989 return TimeoutFunction(self.base_player.update, [result], self.timeout)
991 def quit(self, final_result):
992 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
993 # --- timeout_player.py --- #
997 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
998 network_timeout_delay = 1.0 # Maximum time between two characters being received
1001 def __init__(self, colour, address = None):
1002 self.socket = socket.socket()
1003 #self.socket.setblocking(0)
1005 if colour == "white":
1012 # print str(self) + " listens on port " + str(self.port)
1015 self.host = socket.gethostname()
1016 self.socket.bind((self.host, self.port))
1017 self.socket.listen(5)
1019 self.src, self.address = self.socket.accept()
1020 self.src.send("ok\n")
1021 if self.get_response() == "QUIT":
1025 self.socket.connect((address, self.port))
1026 self.src = self.socket
1027 self.src.send("ok\n")
1028 if self.get_response() == "QUIT":
1031 def get_response(self):
1032 # Timeout the start of the message (first character)
1033 if network_timeout_start > 0.0:
1034 ready = select.select([self.src], [], [], network_timeout_start)[0]
1037 if self.src in ready:
1038 s = self.src.recv(1)
1040 raise Exception("UNRESPONSIVE")
1043 while s[len(s)-1] != '\n':
1044 # Timeout on each character in the message
1045 if network_timeout_delay > 0.0:
1046 ready = select.select([self.src], [], [], network_timeout_delay)[0]
1049 if self.src in ready:
1050 s += self.src.recv(1)
1052 raise Exception("UNRESPONSIVE")
1054 return s.strip(" \r\n")
1056 def send_message(self,s):
1057 if network_timeout_start > 0.0:
1058 ready = select.select([], [self.src], [], network_timeout_start)[1]
1062 if self.src in ready:
1063 self.src.send(s + "\n")
1065 raise Exception("UNRESPONSIVE")
1067 def check_quit(self, s):
1071 game.final_result = " ".join(s[1:]) + " " + str(opponent(self.colour))
1077 class NetworkSender(Player,Network):
1078 def __init__(self, base_player, address = None):
1079 self.base_player = base_player
1080 Player.__init__(self, base_player.name, base_player.colour)
1082 self.address = address
1085 Network.__init__(self, self.base_player.colour, self.address)
1090 [x,y] = self.base_player.select()
1091 choice = self.board.grid[x][y]
1092 s = str(x) + " " + str(y)
1093 #print str(self) + ".select sends " + s
1094 self.send_message(s)
1098 [x,y] = self.base_player.get_move()
1099 s = str(x) + " " + str(y)
1100 #print str(self) + ".get_move sends " + s
1101 self.send_message(s)
1104 def update(self, s):
1105 self.base_player.update(s)
1107 [x,y] = map(int, s[0:2])
1108 selected = self.board.grid[x][y]
1109 if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
1110 s = " ".join(s[0:3])
1112 if selected.types_revealed[i] == True:
1113 s += " " + str(selected.types[i])
1116 #print str(self) + ".update sends " + s
1117 self.send_message(s)
1120 def quit(self, final_result):
1121 self.base_player.quit(final_result)
1122 #self.src.send("QUIT " + str(final_result) + "\n")
1125 class NetworkReceiver(Player,Network):
1126 def __init__(self, colour, address=None):
1128 Player.__init__(self, address, colour)
1130 self.address = address
1135 Network.__init__(self, self.colour, self.address)
1140 s = self.get_response()
1141 #print str(self) + ".select gets " + s
1142 [x,y] = map(int,s.split(" "))
1143 if x == -1 and y == -1:
1144 #print str(self) + ".select quits the game"
1146 game.final_state = "network terminated " + self.colour
1150 s = self.get_response()
1151 #print str(self) + ".get_move gets " + s
1152 [x,y] = map(int,s.split(" "))
1153 if x == -1 and y == -1:
1154 #print str(self) + ".get_move quits the game"
1156 game.final_state = "network terminated " + self.colour
1160 def update(self, result):
1162 result = result.split(" ")
1163 [x,y] = map(int, result[0:2])
1164 selected = self.board.grid[x][y]
1165 if selected != None and selected.colour == self.colour and len(result) > 2 and not "->" in result:
1166 s = self.get_response()
1167 #print str(self) + ".update - receives " + str(s)
1169 selected.choice = int(s[2])
1171 selected.types[i] = str(s[3+i])
1172 if s[3+i] == "unknown":
1173 selected.types_revealed[i] = False
1175 selected.types_revealed[i] = True
1176 selected.current_type = selected.types[selected.choice]
1179 #print str(self) + ".update - ignore result " + str(result)
1182 def quit(self, final_result):
1185 # --- network.py --- #
1188 # A thread that can be stopped!
1189 # Except it can only be stopped if it checks self.stopped() periodically
1190 # So it can sort of be stopped
1191 class StoppableThread(threading.Thread):
1193 threading.Thread.__init__(self)
1194 self._stop = threading.Event()
1200 return self._stop.isSet()
1201 # --- thread_util.py --- #
1207 def __init__(self, log):
1211 self.log.write("# Log starts " + str(datetime.datetime.now()) + "\n")
1214 now = datetime.datetime.now()
1215 self.log.write(str(now) + " : " + s + "\n")
1216 self.logged.append((now, s))
1218 def setup(self, board, players):
1221 self.log.write("# " + p.colour + " : " + p.name + "\n")
1223 self.log.write("# Initial board\n")
1224 for x in range(0, w):
1225 for y in range(0, h):
1226 if board.grid[x][y] != None:
1227 self.log.write(str(board.grid[x][y]) + "\n")
1229 self.log.write("# Start game\n")
1232 self.log.write("# EOF\n")
1235 class HttpLog(LogFile):
1236 def __init__(self, file_name):
1237 LogFile.__init__(self, open(file_name, "w", 0))
1238 self.file_name = file_name
1242 now = datetime.datetime.now()
1243 self.logged.append((now, s))
1247 self.log = open(self.file_name, "w", 0)
1248 self.log.write("# Short log updated " + str(datetime.datetime.now()) + "\n")
1249 LogFile.setup(self, game.board, game.players)
1251 elif self.phase == 1:
1252 for message in self.logged[len(self.logged)-2:]:
1253 self.log.write(str(message[0]) + " : " + message[1] + "\n")
1255 self.phase = (self.phase + 1) % 2
1258 self.log.write("# EOF\n")
1262 class HeadRequest(urllib2.Request):
1263 def get_method(self):
1266 class HttpGetter(StoppableThread):
1267 def __init__(self, address):
1268 StoppableThread.__init__(self)
1269 self.address = address
1270 self.log = urllib2.urlopen(address)
1272 self.lock = threading.RLock() #lock for access of self.state
1273 self.cond = threading.Condition() # conditional
1276 while not self.stopped():
1277 line = self.log.readline()
1279 date_mod = datetime.datetime.strptime(self.log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1282 next_log = urllib2.urlopen(HeadRequest(self.address))
1283 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1284 while date_new <= date_mod and not self.stopped():
1285 next_log = urllib2.urlopen(HeadRequest(self.address))
1286 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1290 self.log = urllib2.urlopen(self.address)
1291 line = self.log.readline()
1294 self.lines.append(line)
1295 self.cond.notifyAll()
1298 #sys.stderr.write(" HttpGetter got \'" + str(line) + "\'\n")
1307 def __init__(self, address):
1308 self.getter = HttpGetter(address)
1312 self.getter.cond.acquire()
1313 while len(self.getter.lines) == 0:
1314 self.getter.cond.wait()
1316 result = self.getter.lines[0]
1317 self.getter.lines = self.getter.lines[1:]
1318 self.getter.cond.release()
1327 if log_file != None:
1331 def log_init(board, players):
1332 if log_file != None:
1333 log_file.setup(board, players)
1341 # A thread that runs the game
1342 class GameThread(StoppableThread):
1343 def __init__(self, board, players):
1344 StoppableThread.__init__(self)
1346 self.players = players
1347 self.state = {"turn" : None} # The game state
1348 self.error = 0 # Whether the thread exits with an error
1349 self.lock = threading.RLock() #lock for access of self.state
1350 self.cond = threading.Condition() # conditional for some reason, I forgot
1351 self.final_result = ""
1355 # Run the game (run in new thread with start(), run in current thread with run())
1358 while not self.stopped():
1360 for p in self.players:
1362 if isinstance(p, NetworkSender):
1363 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
1365 self.state["turn"] = p
1368 [x,y] = p.select() # Player selects a square
1375 result = self.board.select(x, y, colour = p.colour)
1376 for p2 in self.players:
1377 p2.update(result) # Inform players of what happened
1382 target = self.board.grid[x][y]
1383 if isinstance(graphics, GraphicsThread):
1385 graphics.state["moves"] = self.board.possible_moves(target)
1386 graphics.state["select"] = target
1388 time.sleep(turn_delay)
1391 if len(self.board.possible_moves(target)) == 0:
1392 #print "Piece cannot move"
1394 if isinstance(graphics, GraphicsThread):
1396 graphics.state["moves"] = None
1397 graphics.state["select"] = None
1398 graphics.state["dest"] = None
1402 [x2,y2] = p.get_move() # Player selects a destination
1409 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1412 self.board.update_move(x, y, x2, y2)
1414 for p2 in self.players:
1415 p2.update(result) # Inform players of what happened
1419 if isinstance(graphics, GraphicsThread):
1421 graphics.state["moves"] = [[x2,y2]]
1423 time.sleep(turn_delay)
1425 if isinstance(graphics, GraphicsThread):
1427 graphics.state["select"] = None
1428 graphics.state["dest"] = None
1429 graphics.state["moves"] = None
1431 # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
1432 # except Exception,e:
1433 # result = e.message
1434 # #sys.stderr.write(result + "\n")
1438 # self.final_result = self.state["turn"].colour + " " + e.message
1440 if self.board.king["black"] == None:
1441 if self.board.king["white"] == None:
1443 self.final_result = self.state["turn"].colour + " DRAW"
1446 self.final_result = "white"
1448 elif self.board.king["white"] == None:
1450 self.final_result = "black"
1458 for p2 in self.players:
1459 p2.quit(self.final_result)
1461 log(self.final_result)
1463 if isinstance(graphics, GraphicsThread):
1467 # A thread that replays a log file
1468 class ReplayThread(GameThread):
1469 def __init__(self, players, src, end=False,max_lines=None):
1470 self.board = Board(style="empty")
1471 GameThread.__init__(self, self.board, players)
1473 self.max_lines = max_lines
1474 self.line_number = 0
1477 self.reset_board(self.src.readline())
1479 def reset_board(self, line):
1480 pieces = {"white" : [], "black" : []}
1481 king = {"white" : None, "black" : None}
1482 grid = [[None] * w for _ in range(h)]
1485 self.board.grid[x][y] = None
1486 while line != "# Start game":
1488 line = self.src.readline().strip(" \r\n")
1491 tokens = line.split(" ")
1492 [x, y] = map(int, tokens[len(tokens)-1].split(","))
1493 current_type = tokens[1]
1494 types = map(lambda e : e.strip("'[], "), (tokens[2]+tokens[3]).split(","))
1496 target = Piece(tokens[0], x, y, types)
1497 target.current_type = current_type
1500 target.choice = types.index(current_type)
1504 pieces[tokens[0]].append(target)
1505 if target.current_type == "king":
1506 king[tokens[0]] = target
1509 line = self.src.readline().strip(" \r\n")
1511 self.board.pieces = pieces
1512 self.board.king = king
1513 self.board.grid = grid
1515 # Update the player's boards
1519 line = self.src.readline().strip(" \r\n")
1520 while line != "# EOF":
1527 line = self.src.readline().strip(" \r\n")
1530 tokens = line.split(" ")
1531 if tokens[0] == "white" or tokens[0] == "black":
1532 self.reset_board(line)
1533 line = self.src.readline().strip(" \r\n")
1536 move = line.split(":")
1537 move = move[len(move)-1].strip(" \r\n")
1538 tokens = move.split(" ")
1542 [x,y] = map(int, tokens[0:2])
1549 target = self.board.grid[x][y]
1551 if target.colour == "white":
1552 self.state["turn"] = self.players[0]
1554 self.state["turn"] = self.players[1]
1556 move_piece = (tokens[2] == "->")
1558 [x2,y2] = map(int, tokens[len(tokens)-2:])
1560 if isinstance(graphics, GraphicsThread):
1562 graphics.state["select"] = target
1565 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
1566 if isinstance(graphics, GraphicsThread):
1568 graphics.state["moves"] = self.board.possible_moves(target)
1569 time.sleep(turn_delay)
1571 self.board.update_move(x, y, x2, y2)
1572 if isinstance(graphics, GraphicsThread):
1574 graphics.state["moves"] = [[x2,y2]]
1575 time.sleep(turn_delay)
1577 graphics.state["select"] = None
1578 graphics.state["moves"] = None
1579 graphics.state["dest"] = None
1585 for p in self.players:
1588 line = self.src.readline().strip(" \r\n")
1605 if self.max_lines != None and self.max_lines > count:
1606 sys.stderr.write(sys.argv[0] + " : Replaying from file; stopping at last line (" + str(count) + ")\n")
1607 sys.stderr.write(sys.argv[0] + " : (You requested line " + str(self.max_lines) + ")\n")
1609 if self.end and isinstance(graphics, GraphicsThread):
1611 pass # Let the user stop the display
1614 game = GameThread(self.board, self.players)
1620 def opponent(colour):
1621 if colour == "white":
1632 # Dictionary that stores the unicode character representations of the different pieces
1633 # Chess was clearly the reason why unicode was invented
1634 # For some reason none of the pygame chess implementations I found used them!
1635 piece_char = {"white" : {"king" : u'\u2654',
1636 "queen" : u'\u2655',
1638 "bishop" : u'\u2657',
1639 "knight" : u'\u2658',
1642 "black" : {"king" : u'\u265A',
1643 "queen" : u'\u265B',
1645 "bishop" : u'\u265D',
1646 "knight" : u'\u265E',
1650 images = {"white" : {}, "black" : {}}
1651 small_images = {"white" : {}, "black" : {}}
1653 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
1655 # Get the font sizes
1656 l_size = 5*(grid_sz[0] / 8)
1657 s_size = 3*(grid_sz[0] / 8)
1659 for c in piece_char.keys():
1662 for p in piece_char[c].keys():
1663 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
1664 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})
1666 for p in piece_char[c].keys():
1667 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1668 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1669 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1670 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1673 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
1674 if not os.path.exists(image_dir):
1675 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
1676 for c in piece_char.keys():
1677 for p in piece_char[c].keys():
1678 images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
1679 small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
1680 # --- images.py --- #
1681 graphics_enabled = True
1685 graphics_enabled = False
1690 # A thread to make things pretty
1691 class GraphicsThread(StoppableThread):
1692 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1693 StoppableThread.__init__(self)
1697 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1698 pygame.display.set_caption(title)
1700 #print "Initialised properly"
1702 self.grid_sz = grid_sz[:]
1703 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
1705 self.lock = threading.RLock()
1706 self.cond = threading.Condition()
1709 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
1712 create_images(grid_sz)
1715 for c in images.keys():
1716 for p in images[c].keys():
1717 images[c][p] = images[c][p].convert(self.window)
1718 small_images[c][p] = small_images[c][p].convert(self.window)
1725 # On the run from the world
1728 while not self.stopped():
1730 #print "Display grid"
1731 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
1733 #print "Display overlay"
1736 #print "Display pieces"
1737 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
1739 pygame.display.flip()
1741 for event in pygame.event.get():
1742 if event.type == pygame.QUIT:
1743 if isinstance(game, GameThread):
1745 game.final_result = ""
1746 if game.state["turn"] != None:
1747 game.final_result = game.state["turn"].colour + " "
1748 game.final_result += "terminated"
1752 elif event.type == pygame.MOUSEBUTTONDOWN:
1753 self.mouse_down(event)
1754 elif event.type == pygame.MOUSEBUTTONUP:
1755 self.mouse_up(event)
1762 self.message("Game ends, result \""+str(game.final_result) + "\"")
1765 # Wake up anyone who is sleeping
1770 pygame.quit() # Time to say goodbye
1772 # Mouse release event handler
1773 def mouse_up(self, event):
1774 if event.button == 3:
1776 self.state["overlay"] = None
1777 elif event.button == 2:
1779 self.state["coverage"] = None
1781 # Mouse click event handler
1782 def mouse_down(self, event):
1783 if event.button == 1:
1784 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
1785 if isinstance(game, GameThread):
1787 p = game.state["turn"]
1792 if isinstance(p, HumanPlayer):
1794 s = self.board.grid[m[0]][m[1]]
1795 select = self.state["select"]
1797 if s != None and s.colour != p.colour:
1798 self.message("Wrong colour") # Look at all this user friendliness!
1801 # Notify human player of move
1804 self.state["select"] = s
1805 self.state["dest"] = None
1814 if self.state["moves"] == None:
1817 if not m in self.state["moves"]:
1818 self.message("Illegal Move") # I still think last year's mouse interface was adequate
1823 if self.state["dest"] == None:
1825 self.state["dest"] = m
1826 self.state["select"] = None
1827 self.state["moves"] = None
1830 elif event.button == 3:
1831 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1832 if isinstance(game, GameThread):
1834 p = game.state["turn"]
1839 if isinstance(p, HumanPlayer):
1841 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
1843 elif event.button == 2:
1844 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1845 if isinstance(game, GameThread):
1847 p = game.state["turn"]
1852 if isinstance(p, HumanPlayer):
1854 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
1859 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
1860 # Draw square over the selected piece
1862 select = self.state["select"]
1864 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
1865 square_img.fill(pygame.Color(0,255,0,64))
1866 self.window.blit(square_img, mp)
1867 # If a piece is selected, draw all reachable squares
1868 # (This quality user interface has been patented)
1870 m = self.state["moves"]
1872 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
1874 mp = [self.grid_sz[i] * move[i] for i in range(2)]
1875 self.window.blit(square_img, mp)
1876 # If a piece is overlayed, show all squares that it has a probability to reach
1878 m = self.state["overlay"]
1883 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
1884 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
1885 self.window.blit(square_img, mp)
1886 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
1887 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
1888 self.window.blit(text, mp)
1890 # If a square is selected, highlight all pieces that have a probability to reach it
1892 m = self.state["coverage"]
1895 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
1896 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
1897 self.window.blit(square_img, mp)
1898 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
1899 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
1900 self.window.blit(text, mp)
1901 # Draw a square where the mouse is
1902 # This also serves to indicate who's turn it is
1904 if isinstance(game, GameThread):
1906 turn = game.state["turn"]
1910 if isinstance(turn, HumanPlayer):
1911 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
1912 square_img.fill(pygame.Color(0,0,255,128))
1913 if turn.colour == "white":
1914 c = pygame.Color(255,255,255)
1916 c = pygame.Color(0,0,0)
1917 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
1918 self.window.blit(square_img, mp)
1920 # Message in a bottle
1921 def message(self, string, pos = None, colour = None, font_size = 20):
1922 #print "Drawing message..."
1923 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
1925 colour = pygame.Color(0,0,0)
1927 text = font.render(string, 1, colour)
1930 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
1931 s.fill(pygame.Color(128,128,128))
1933 tmp = self.window.get_size()
1936 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
1938 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
1941 rect = (pos[0], pos[1], text.get_width(), text.get_height())
1943 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
1944 self.window.blit(s, pos)
1945 self.window.blit(text, pos)
1947 pygame.display.flip()
1949 def getstr(self, prompt = None):
1950 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
1951 s.blit(self.window, (0,0))
1957 self.message(prompt)
1958 self.message(result, pos = (0, 1))
1961 for event in pygame.event.get():
1962 if event.type == pygame.QUIT:
1964 if event.type == pygame.KEYDOWN:
1965 if event.key == pygame.K_BACKSPACE:
1966 result = result[0:len(result)-1]
1967 self.window.blit(s, (0,0)) # Revert the display
1972 if event.unicode == '\r':
1975 result += str(event.unicode)
1980 # Function to pick a button
1981 def SelectButton(self, choices, prompt = None, font_size=20):
1983 #print "Select button called!"
1984 self.board.display_grid(self.window, self.grid_sz)
1986 self.message(prompt)
1987 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
1989 sz = self.window.get_size()
1992 for i in range(len(choices)):
1995 text = font.render(c, 1, pygame.Color(0,0,0))
1996 p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
1997 targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
2000 mp =pygame.mouse.get_pos()
2001 for i in range(len(choices)):
2003 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
2004 font_colour = pygame.Color(255,0,0)
2005 box_colour = pygame.Color(0,0,255,128)
2007 font_colour = pygame.Color(0,0,0)
2008 box_colour = pygame.Color(128,128,128)
2010 text = font.render(c, 1, font_colour)
2011 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
2013 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
2014 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
2015 self.window.blit(s, targets[i][0:2])
2018 pygame.display.flip()
2020 for event in pygame.event.get():
2021 if event.type == pygame.QUIT:
2023 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
2024 for i in range(len(targets)):
2026 if event.pos[0] > t[0] and event.pos[0] < t[2]:
2027 if event.pos[1] > t[1] and event.pos[1] < t[3]:
2029 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
2032 # Function to pick players in a nice GUI way
2033 def SelectPlayers(self, players = []):
2036 #print "SelectPlayers called"
2038 missing = ["white", "black"]
2040 missing.remove(p.colour)
2042 for colour in missing:
2045 choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
2047 players.append(HumanPlayer("human", colour))
2050 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2051 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2052 internal_agents.remove(('InternalAgent', InternalAgent))
2053 if len(internal_agents) > 0:
2054 choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
2059 agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
2060 players.append(agent[1](agent[0], colour))
2064 from tkFileDialog import askopenfilename
2065 root = Tkinter.Tk() # Need a root to make Tkinter behave
2066 root.withdraw() # Some sort of magic incantation
2067 path = askopenfilename(parent=root, initialdir="../agents",title=
2070 return self.SelectPlayers()
2071 players.append(make_player(path, colour))
2076 self.board.display_grid(self.window, self.grid_sz)
2077 pygame.display.flip()
2078 path = self.getstr(prompt = "Enter path:")
2083 return self.SelectPlayers()
2086 p = make_player(path, colour)
2088 self.board.display_grid(self.window, self.grid_sz)
2089 pygame.display.flip()
2090 self.message("Invalid path!")
2096 while address == "":
2097 self.board.display_grid(self.window, self.grid_sz)
2099 address = self.getstr(prompt = "Address? (leave blank for server)")
2106 map(int, address.split("."))
2108 self.board.display_grid(self.window, self.grid_sz)
2109 self.message("Invalid IPv4 address!")
2112 players.append(NetworkReceiver(colour, address))
2115 #print str(self) + ".SelectPlayers returns " + str(players)
2120 # --- graphics.py --- #
2121 #!/usr/bin/python -u
2123 # Do you know what the -u does? It unbuffers stdin and stdout
2124 # I can't remember why, but last year things broke without that
2127 UCC::Progcomp 2013 Quantum Chess game
2128 @author Sam Moore [SZM] "matches"
2129 @copyright The University Computer Club, Incorporated
2130 (ie: You can copy it for not for profit purposes)
2133 # system python modules or whatever they are called
2139 [game, graphics] = [None, None]
2141 def make_player(name, colour):
2143 if name[1:] == "human":
2144 return HumanPlayer(name, colour)
2145 s = name[1:].split(":")
2146 if s[0] == "network":
2150 return NetworkReceiver(colour, address)
2151 if s[0] == "internal":
2154 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2155 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2156 internal_agents.remove(('InternalAgent', InternalAgent))
2159 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
2160 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2163 for a in internal_agents:
2165 return a[1](name, colour)
2167 sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
2168 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2173 return ExternalAgent(name, colour)
2177 # The main function! It does the main stuff!
2180 # Apparently python will silently treat things as local unless you do this
2181 # Anyone who says "You should never use a global variable" can die in a fire
2186 global agent_timeout
2189 global graphics_enabled
2190 global always_reveal_states
2198 # Get the important warnings out of the way
2199 if platform.system() == "Windows":
2200 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
2201 if platform.release() == "Vista":
2202 sys.stderr.write(sys.argv[0] + " : God help you.\n")
2207 while i < len(argv)-1:
2211 p = make_player(arg, colour)
2212 if not isinstance(p, Player):
2213 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
2216 if colour == "white":
2218 elif colour == "black":
2221 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
2224 # Option parsing goes here
2225 if arg[1] == '-' and arg[2:] == "classical":
2227 elif arg[1] == '-' and arg[2:] == "quantum":
2229 elif arg[1] == '-' and arg[2:] == "reveal":
2230 always_reveal_states = True
2231 elif (arg[1] == '-' and arg[2:] == "graphics"):
2232 graphics_enabled = not graphics_enabled
2233 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
2234 # Load game from file
2235 if len(arg[2:].split("=")) == 1:
2236 src_file = sys.stdin
2238 f = arg[2:].split("=")[1]
2240 src_file = HttpReplay("http://" + f.split(":")[0][1:])
2242 src_file = open(f.split(":")[0], "r", 0)
2244 if len(f.split(":")) == 2:
2245 max_lines = int(f.split(":")[1])
2247 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
2249 if len(arg[2:].split("=")) == 1:
2250 log_file = LogFile(sys.stdout)
2252 f = arg[2:].split("=")[1]
2254 log_file = HttpLog(f[1:])
2256 log_file = LogFile(open(f, "w", 0))
2257 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
2259 if len(arg[2:].split("=")) == 1:
2262 turn_delay = float(arg[2:].split("=")[1])
2264 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
2266 if len(arg[2:].split("=")) == 1:
2269 agent_timeout = float(arg[2:].split("=")[1])
2271 elif (arg[1] == '-' and arg[2:] == "help"):
2273 os.system("less data/help.txt") # The best help function
2279 # Construct a GameThread! Make it global! Damn the consequences!
2281 if src_file != None:
2282 # Hack to stop ReplayThread from exiting
2283 #if len(players) == 0:
2284 # players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
2286 # Normally the ReplayThread exits if there are no players
2287 # TODO: Decide which behaviour to use, and fix it
2288 end = (len(players) == 0)
2290 players = [Player("dummy", "white"), Player("dummy", "black")]
2291 elif len(players) != 2:
2292 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2293 if graphics_enabled:
2294 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
2296 game = ReplayThread(players, src_file, end=end, max_lines=max_lines)
2298 board = Board(style)
2299 game = GameThread(board, players)
2304 if graphics_enabled == True:
2306 graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
2310 sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
2311 graphics_enabled = False
2313 # If there are no players listed, display a nice pretty menu
2314 if len(players) != 2:
2315 if graphics != None:
2316 players = graphics.SelectPlayers(players)
2318 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2321 # If there are still no players, quit
2322 if players == None or len(players) != 2:
2323 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
2327 # Wrap NetworkSender players around original players if necessary
2328 for i in range(len(players)):
2329 if isinstance(players[i], NetworkReceiver):
2330 players[i].board = board # Network players need direct access to the board
2331 for j in range(len(players)):
2334 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
2336 players[j] = NetworkSender(players[j], players[i].address)
2337 players[j].board = board
2339 # Connect the networked players
2341 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
2342 if graphics != None:
2343 graphics.board.display_grid(graphics.window, graphics.grid_sz)
2344 graphics.message("Connecting to " + p.colour + " player...")
2348 # If using windows, select won't work; use horrible TimeoutPlayer hack
2349 if agent_timeout > 0:
2350 if platform.system() == "Windows":
2351 for i in range(len(players)):
2352 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
2353 players[i] = TimeoutPlayer(players[i], agent_timeout)
2357 # InternalAgents get wrapped to an ExternalAgent when there is a timeout
2358 # This is not confusing at all.
2359 for i in range(len(players)):
2360 if isinstance(players[i], InternalAgent):
2361 players[i] = ExternalWrapper(players[i])
2369 log_init(game.board, players)
2372 if graphics != None:
2373 game.start() # This runs in a new thread
2379 error = game.error + graphics.error
2385 if log_file != None and log_file != sys.stdout:
2388 if src_file != None and src_file != sys.stdin:
2393 # This is how python does a main() function...
2394 if __name__ == "__main__":
2396 sys.exit(main(sys.argv))
2397 except KeyboardInterrupt:
2398 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
2399 if isinstance(graphics, StoppableThread):
2401 graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
2403 if isinstance(game, StoppableThread):
2411 # EOF - created from make on Wed Jan 30 21:00:29 WST 2013