4 # I know using non-abreviated strings is inefficient, but this is python, who cares?
5 # Oh, yeah, this stores the number of pieces of each type in a normal chess game
6 piece_types = {"pawn" : 8, "bishop" : 2, "knight" : 2, "rook" : 2, "queen" : 1, "king" : 1, "unknown" : 0}
8 # Class to represent a quantum chess piece
10 def __init__(self, colour, x, y, types):
11 self.colour = colour # Colour (string) either "white" or "black"
12 self.x = x # x coordinate (0 - 8), none of this fancy 'a', 'b' shit here
13 self.y = y # y coordinate (0 - 8)
14 self.types = types # List of possible types the piece can be (should just be two)
15 self.current_type = "unknown" # Current type
16 self.choice = -1 # Index of the current type in self.types (-1 = unknown type)
19 self.last_state = None
21 self.move_pattern = None
23 self.possible_moves = None
26 def init_from_copy(self, c):
27 self.colour = c.colour
30 self.types = c.types[:]
31 self.current_type = c.current_type
32 self.choice = c.choice
34 self.last_state = None
35 self.move_pattern = None
39 # Make a string for the piece (used for debug)
41 return str(self.colour) + " " + str(self.current_type) + " " + str(self.types) + " at " + str(self.x) + ","+str(self.y)
43 # Draw the piece in a pygame surface
44 def draw(self, window, grid_sz = [80,80], style="quantum"):
46 # First draw the image corresponding to self.current_type
47 img = images[self.colour][self.current_type]
49 if style == "classical":
50 offset = [-rect.width/2, -rect.height/2]
52 offset = [-rect.width/2,-3*rect.height/4]
53 window.blit(img, (self.x * grid_sz[0] + grid_sz[0]/2 + offset[0], self.y * grid_sz[1] + grid_sz[1]/2 + offset[1]))
56 if style == "classical":
59 # Draw the two possible types underneath the current_type image
60 for i in range(len(self.types)):
61 if always_reveal_states == True or self.types[i][0] != '?':
62 img = small_images[self.colour][self.types[i]]
64 img = small_images[self.colour]["unknown"] # If the type hasn't been revealed, show a placeholder
68 offset = [-rect.width/2,-rect.height/2]
71 target = (self.x * grid_sz[0] + grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])
73 target = (self.x * grid_sz[0] + 4*grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])
75 window.blit(img, target) # Blit shit
77 # Collapses the wave function!
79 if self.current_type == "unknown" or not self.choice in [0,1]:
80 self.choice = random.randint(0,1)
81 if self.types[self.choice][0] == '?':
82 self.types[self.choice] = self.types[self.choice][1:]
83 self.current_type = self.types[self.choice]
86 # Uncollapses (?) the wave function!
88 #print "Deselect called"
89 if (self.x + self.y) % 2 != 0:
90 if (self.types[0] != self.types[1]) or (self.types[0][0] == '?' or self.types[1][0] == '?'):
91 self.current_type = "unknown"
94 self.choice = 0 # Both the two types are the same
96 # The sad moment when you realise that you do not understand anything about a subject you studied for 4 years...
98 [w,h] = [8,8] # Width and height of board(s)
100 always_reveal_states = False
102 # Class to represent a quantum chess board
104 # Initialise; if master=True then the secondary piece types are assigned
105 # Otherwise, they are left as unknown
106 # So you can use this class in Agent programs, and fill in the types as they are revealed
107 def __init__(self, style="agent"):
109 self.pieces = {"white" : [], "black" : []}
110 self.grid = [[None] * w for _ in range(h)] # 2D List (you can get arrays in python, somehow, but they scare me)
111 self.unrevealed_types = {"white" : piece_types.copy(), "black" : piece_types.copy()}
112 self.king = {"white" : None, "black" : None} # We need to keep track of the king, because he is important
113 self.max_moves = None
116 for c in ["black", "white"]:
117 del self.unrevealed_types[c]["unknown"]
122 # Add all the pieces with known primary types
123 for i in range(0, 2):
125 s = ["black", "white"][i]
129 c.append(Piece(s, 0, y, ["rook"]))
130 c.append(Piece(s, 1, y, ["knight"]))
131 c.append(Piece(s, 2, y, ["bishop"]))
132 k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
133 k.current_type = "king"
136 c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
137 c.append(Piece(s, 5, y, ["bishop"]))
138 c.append(Piece(s, 6, y, ["knight"]))
139 c.append(Piece(s, 7, y, ["rook"]))
147 for x in range(0, w):
148 c.append(Piece(s, x, y, ["pawn"]))
151 types_left.update(piece_types)
152 del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
153 del types_left["unknown"] # We certainly don't want these!
156 self.grid[piece.x][piece.y] = piece
158 if len(piece.types) > 1:
160 if style == "agent": # Assign placeholder "unknown" secondary type
161 piece.types.append("unknown")
164 elif style == "quantum":
165 # The master allocates the secondary types
166 choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
167 types_left[choice] -= 1
168 if types_left[choice] <= 0:
169 del types_left[choice]
170 piece.types.append('?' + choice)
171 elif style == "classical":
172 piece.types.append(piece.types[0])
173 piece.current_type = piece.types[0]
177 newboard = Board(master = False)
178 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
179 mypieces = self.pieces["white"] + self.pieces["black"]
181 for i in range(len(mypieces)):
182 newpieces[i].init_from_copy(mypieces[i])
184 # Reset the board from a string
185 def reset_board(self, s):
186 self.pieces = {"white" : [], "black" : []}
187 self.king = {"white" : None, "black" : None}
188 self.grid = [[None] * w for _ in range(h)]
191 self.grid[x][y] = None
193 for line in s.split("\n"):
199 tokens = line.split(" ")
200 [x, y] = map(int, tokens[len(tokens)-1].split(","))
201 current_type = tokens[1]
202 types = map(lambda e : e.strip(" '[],"), line.split('[')[1].split(']')[0].split(','))
204 target = Piece(tokens[0], x, y, types)
205 target.current_type = current_type
208 target.choice = types.index(current_type)
212 self.pieces[tokens[0]].append(target)
213 if target.current_type == "king":
214 self.king[tokens[0]] = target
216 self.grid[x][y] = target
219 def display_grid(self, window = None, grid_sz = [80,80]):
221 return # I was considering implementing a text only display, then I thought "Fuck that"
223 # The indentation is getting seriously out of hand...
224 for x in range(0, w):
225 for y in range(0, h):
227 c = pygame.Color(200,200,200)
229 c = pygame.Color(64,64,64)
230 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
232 def display_pieces(self, window = None, grid_sz = [80,80]):
235 for p in self.pieces["white"] + self.pieces["black"]:
236 p.draw(window, grid_sz, self.style)
238 # Draw the board in a pygame window
239 def display(self, window = None):
240 self.display_grid(window)
241 self.display_pieces(window)
249 if self.grid[x][y] == None:
251 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
252 raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
254 # Select a piece on the board (colour is the colour of whoever is doing the selecting)
255 def select(self, x,y, colour=None):
256 if not self.on_board(x, y): # Get on board everyone!
257 raise Exception("BOUNDS")
259 piece = self.grid[x][y]
261 raise Exception("EMPTY")
263 if colour != None and piece.colour != colour:
264 raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
266 # I'm not quite sure why I made this return a string, but screw logical design
267 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
270 # Update the board when a piece has been selected
271 # "type" is apparently reserved, so I'll use "state"
272 def update_select(self, x, y, type_index, state):
273 piece = self.grid[x][y]
274 if piece.types[type_index] == "unknown":
275 if not state in self.unrevealed_types[piece.colour].keys():
276 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
277 self.unrevealed_types[piece.colour][state] -= 1
278 if self.unrevealed_types[piece.colour][state] <= 0:
279 del self.unrevealed_types[piece.colour][state]
281 piece.types[type_index] = state
282 piece.current_type = state
284 if len(self.possible_moves(piece)) <= 0:
285 piece.deselect() # Piece can't move; deselect it
287 # Piece needs to recalculate moves
288 piece.possible_moves = None
290 # Update the board when a piece has been moved
291 def update_move(self, x, y, x2, y2):
293 piece = self.grid[x][y]
294 #print "Moving " + str(x) + "," + str(y) + " to " + str(x2) + "," + str(y2) + "; possible_moves are " + str(self.possible_moves(piece))
296 if not [x2,y2] in self.possible_moves(piece):
297 raise Exception("ILLEGAL move")
299 self.grid[x][y] = None
300 taken = self.grid[x2][y2]
302 if taken.current_type == "king":
303 self.king[taken.colour] = None
304 self.pieces[taken.colour].remove(taken)
305 self.grid[x2][y2] = piece
309 # If the piece is a pawn, and it reaches the final row, it becomes a queen
310 # I know you are supposed to get a choice
311 # But that would be effort
312 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
313 if self.style == "classical":
314 piece.types[0] = "queen"
315 piece.types[1] = "queen"
317 piece.types[piece.choice] = "queen"
318 piece.current_type = "queen"
320 piece.deselect() # Uncollapse (?) the wavefunction!
323 # All other pieces need to recalculate moves
324 for p in self.pieces["white"] + self.pieces["black"]:
325 p.possible_moves = None
329 # Update the board from a string
330 # Guesses what to do based on the format of the string
331 def update(self, result):
332 #print "Update called with \"" + str(result) + "\""
333 # String always starts with 'x y'
335 s = result.split(" ")
336 [x,y] = map(int, s[0:2])
338 raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
340 piece = self.grid[x][y]
342 raise Exception("EMPTY")
344 # If a piece is being moved, the third token is '->'
345 # We could get away with just using four integers, but that wouldn't look as cool
347 # Last two tokens are the destination
349 [x2,y2] = map(int, s[3:])
351 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
353 # Move the piece (take opponent if possible)
354 self.update_move(x, y, x2, y2)
357 # Otherwise we will just assume a piece has been selected
359 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
360 state = s[3] # The last token is a string identifying the type
362 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
365 self.update_select(x, y, type_index, state)
369 # Gets each piece that could reach the given square and the probability that it could reach that square
370 # Will include allied pieces that defend the attacker
371 def coverage(self, x, y, colour = None, reject_allied = True):
375 pieces = self.pieces["white"] + self.pieces["black"]
377 pieces = self.pieces[colour]
380 prob = self.probability_grid(p, reject_allied)[x][y]
382 result.update({p : prob})
391 # Associates each square with a probability that the piece could move into it
392 # Look, I'm doing all the hard work for you here...
393 def probability_grid(self, p, reject_allied = True):
395 result = [[0.0] * w for _ in range(h)]
396 if not isinstance(p, Piece):
399 if p.current_type != "unknown":
400 #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
401 for point in self.possible_moves(p, reject_allied):
402 result[point[0]][point[1]] = 1.0
406 for i in range(len(p.types)):
409 if t == "unknown" or p.types[i][0] == '?':
411 for t2 in self.unrevealed_types[p.colour].keys():
412 total_types += self.unrevealed_types[p.colour][t2]
414 for t2 in self.unrevealed_types[p.colour].keys():
415 prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
417 for point in self.possible_moves(p, reject_allied):
418 result[point[0]][point[1]] += prob2 * prob
422 for point in self.possible_moves(p, reject_allied):
423 result[point[0]][point[1]] += prob
426 p.current_type = "unknown"
429 def prob_is_type(self, p, state):
432 for i in range(len(p.types)):
437 if t == "unknown" or p.types[i][0] == '?':
439 for t2 in self.unrevealed_types[p.colour].keys():
440 total_prob += self.unrevealed_types[p.colour][t2]
441 for t2 in self.unrevealed_types[p.colour].keys():
443 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
447 # Get all squares that the piece could move into
448 # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
449 # reject_allied indicates whether squares occupied by allied pieces will be removed
450 # (set to false to check for defense)
451 def possible_moves(self, p, reject_allied = True, state=None):
453 raise Exception("SANITY: No piece")
457 if state != None and state != p.current_type:
458 old_type = p.current_type
459 p.current_type = state
460 result = self.possible_moves(p, reject_allied, state=None)
461 p.current_type = old_type
464 if p.possible_moves != None:
465 return p.possible_moves
472 if p.current_type == "unknown":
473 raise Exception("SANITY: Piece state unknown")
474 # The below commented out code causes things to break badly
479 # result += self.possible_moves(p)
480 #p.current_type = "unknown"
483 if p.current_type == "king":
484 result = [[p.x-1,p.y],[p.x+1,p.y],[p.x,p.y-1],[p.x,p.y+1], [p.x-1,p.y-1],[p.x-1,p.y+1],[p.x+1,p.y-1],[p.x+1,p.y+1]]
485 elif p.current_type == "queen":
486 for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
487 result += self.scan(p.x, p.y, d[0], d[1])
488 elif p.current_type == "bishop":
489 for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
490 result += self.scan(p.x, p.y, d[0], d[1])
491 elif p.current_type == "rook":
492 for d in [[-1,0],[1,0],[0,-1],[0,1]]:
493 result += self.scan(p.x, p.y, d[0], d[1])
494 elif p.current_type == "knight":
495 # I would use two lines, but I'm not sure how python likes that
496 result = [[p.x-2, p.y-1], [p.x-2, p.y+1], [p.x+2, p.y-1], [p.x+2,p.y+1], [p.x-1,p.y-2], [p.x-1, p.y+2],[p.x+1,p.y-2],[p.x+1,p.y+2]]
497 elif p.current_type == "pawn":
498 if p.colour == "white":
500 # Pawn can't move forward into occupied square
501 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
502 result = [[p.x,p.y-1]]
503 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
504 if not self.on_board(f[0], f[1]):
506 if self.grid[f[0]][f[1]] != None: # Pawn can take diagonally
509 # Slightly embarrassing if the pawn jumps over someone on its first move...
510 if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
511 result.append([p.x, p.y-2])
513 # Vice versa for the black pawn
514 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
515 result = [[p.x,p.y+1]]
517 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
518 if not self.on_board(f[0], f[1]):
520 if self.grid[f[0]][f[1]] != None:
521 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
524 if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
525 result.append([p.x, p.y+2])
527 #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
529 # Remove illegal moves
530 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
531 for point in result[:]:
533 if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
534 result.remove(point) # Remove locations outside the board
536 g = self.grid[point[0]][point[1]]
538 if g != None and (g.colour == p.colour and reject_allied == True):
539 result.remove(point) # Remove allied pieces
543 p.possible_moves = result
547 # Scans in a direction until it hits a piece, returns all squares in the line
548 # (includes the final square (which contains a piece), but not the original square)
549 def scan(self, x, y, vx, vy):
557 if not self.on_board(xx, yy):
561 g = self.grid[xx][yy]
567 # Returns "white", "black" or "DRAW" if the game should end
568 def end_condition(self):
569 if self.king["white"] == None:
570 if self.king["black"] == None:
571 return "DRAW" # This shouldn't happen
573 elif self.king["black"] == None:
575 elif len(self.pieces["white"]) == 1 and len(self.pieces["black"]) == 1:
577 elif self.max_moves != None and self.moves > self.max_moves:
582 # I typed the full statement about 30 times before writing this function...
583 def on_board(self, x, y):
584 return (x >= 0 and x < w) and (y >= 0 and y < h)
586 # Pushes a move temporarily
587 def push_move(self, piece, x, y):
588 target = self.grid[x][y]
589 self.move_stack.append([piece, target, piece.x, piece.y, x, y])
590 [piece.x, piece.y] = [x, y]
591 self.grid[x][y] = piece
592 self.grid[piece.x][piece.y] = None
594 for p in self.pieces["white"] + self.pieces["black"]:
595 p.possible_moves = None
599 #print str(self.move_stack)
600 [piece, target, x1, y1, x2, y2] = self.move_stack[len(self.move_stack)-1]
601 self.move_stack = self.move_stack[:-1]
604 self.grid[x1][y1] = piece
608 self.grid[x2][y2] = target
610 for p in self.pieces["white"] + self.pieces["black"]:
611 p.possible_moves = None
619 agent_timeout = -1.0 # Timeout in seconds for AI players to make moves
620 # WARNING: Won't work for windows based operating systems
622 if platform.system() == "Windows":
623 agent_timeout = -1 # Hence this
625 # A player who can't play
627 def __init__(self, name, colour):
631 def update(self, result):
634 def reset_board(self, s):
637 # Player that runs from another process
638 class ExternalAgent(Player):
641 def __init__(self, name, colour):
642 Player.__init__(self, name, colour)
643 self.p = subprocess.Popen(name,bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,universal_newlines=True)
645 self.send_message(colour)
647 def send_message(self, s):
648 if agent_timeout > 0.0:
649 ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
651 ready = [self.p.stdin]
652 if self.p.stdin in ready:
653 #sys.stderr.write("Writing \'" + s + "\' to " + str(self.p) + "\n")
655 self.p.stdin.write(s + "\n")
657 raise Exception("UNRESPONSIVE")
659 raise Exception("TIMEOUT")
661 def get_response(self):
662 if agent_timeout > 0.0:
663 ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
665 ready = [self.p.stdout]
666 if self.p.stdout in ready:
667 #sys.stderr.write("Reading from " + str(self.p) + " 's stdout...\n")
669 result = self.p.stdout.readline().strip("\r\n")
670 #sys.stderr.write("Read \'" + result + "\' from " + str(self.p) + "\n")
672 except: # Exception, e:
673 raise Exception("UNRESPONSIVE")
675 raise Exception("TIMEOUT")
679 self.send_message("SELECTION?")
680 line = self.get_response()
683 result = map(int, line.split(" "))
685 raise Exception("GIBBERISH \"" + str(line) + "\"")
688 def update(self, result):
689 #print "Update " + str(result) + " called for AgentPlayer"
690 self.send_message(result)
695 self.send_message("MOVE?")
696 line = self.get_response()
699 result = map(int, line.split(" "))
701 raise Exception("GIBBERISH \"" + str(line) + "\"")
704 def reset_board(self, s):
705 self.send_message("BOARD")
706 for line in s.split("\n"):
707 self.send_message(line.strip(" \r\n"))
708 self.send_message("END BOARD")
710 def quit(self, final_result):
712 self.send_message("QUIT " + final_result)
716 # So you want to be a player here?
717 class HumanPlayer(Player):
718 def __init__(self, name, colour):
719 Player.__init__(self, name, colour)
721 # Select your preferred account
723 if isinstance(graphics, GraphicsThread):
724 # Basically, we let the graphics thread do some shit and then return that information to the game thread
725 graphics.cond.acquire()
726 # We wait for the graphics thread to select a piece
727 while graphics.stopped() == False and graphics.state["select"] == None:
728 graphics.cond.wait() # The difference between humans and machines is that humans sleep
729 select = graphics.state["select"]
732 graphics.cond.release()
733 if graphics.stopped():
735 return [select.x, select.y]
737 # Since I don't display the board in this case, I'm not sure why I filled it in...
739 sys.stdout.write("SELECTION?\n")
741 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
743 sys.stderr.write("ILLEGAL GIBBERISH\n")
745 # It's your move captain
747 if isinstance(graphics, GraphicsThread):
748 graphics.cond.acquire()
749 while graphics.stopped() == False and graphics.state["dest"] == None:
751 graphics.cond.release()
753 return graphics.state["dest"]
757 sys.stdout.write("MOVE?\n")
759 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
761 sys.stderr.write("ILLEGAL GIBBERISH\n")
764 # Are you sure you want to quit?
765 def quit(self, final_result):
767 sys.stdout.write("QUIT " + final_result + "\n")
769 # Completely useless function
770 def update(self, result):
771 if isinstance(graphics, GraphicsThread):
774 sys.stdout.write(result + "\n")
777 # Default internal player (makes random moves)
778 class InternalAgent(Player):
779 def __init__(self, name, colour):
780 Player.__init__(self, name, colour)
783 self.board = Board(style = "agent")
787 def update(self, result):
789 self.board.update(result)
792 def reset_board(self, s):
793 self.board.reset_board(s)
795 def quit(self, final_result):
798 class AgentRandom(InternalAgent):
799 def __init__(self, name, colour):
800 InternalAgent.__init__(self, name, colour)
804 self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
806 # Check that the piece has some possibility to move
807 tmp = self.choice.current_type
808 if tmp == "unknown": # For unknown pieces, try both types
809 for t in self.choice.types:
812 self.choice.current_type = t
813 all_moves += self.board.possible_moves(self.choice)
815 all_moves = self.board.possible_moves(self.choice)
816 self.choice.current_type = tmp
817 if len(all_moves) > 0:
819 return [self.choice.x, self.choice.y]
822 moves = self.board.possible_moves(self.choice)
823 move = moves[random.randint(0, len(moves)-1)]
827 # Terrible, terrible hacks
829 def run_agent(agent):
830 #sys.stderr.write(sys.argv[0] + " : Running agent " + str(agent) + "\n")
832 line = sys.stdin.readline().strip(" \r\n")
833 if line == "SELECTION?":
834 #sys.stderr.write(sys.argv[0] + " : Make selection\n")
835 [x,y] = agent.select() # Gets your agent's selection
836 #sys.stderr.write(sys.argv[0] + " : Selection was " + str(agent.choice) + "\n")
837 sys.stdout.write(str(x) + " " + str(y) + "\n")
838 elif line == "MOVE?":
839 #sys.stderr.write(sys.argv[0] + " : Make move\n")
840 [x,y] = agent.get_move() # Gets your agent's move
841 sys.stdout.write(str(x) + " " + str(y) + "\n")
842 elif line.split(" ")[0] == "QUIT":
843 #sys.stderr.write(sys.argv[0] + " : Quitting\n")
844 agent.quit(" ".join(line.split(" ")[1:])) # Quits the game
846 elif line.split(" ")[0] == "BOARD":
848 line = sys.stdin.readline().strip(" \r\n")
849 while line != "END BOARD":
851 line = sys.stdin.readline().strip(" \r\n")
852 agent.board.reset_board(s)
855 agent.update(line) # Updates agent.board
861 class ExternalWrapper(ExternalAgent):
862 def __init__(self, agent):
863 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))\""
865 ExternalAgent.__init__(self, run, agent.colour)
869 # --- player.py --- #
873 class AgentBishop(AgentRandom): # Inherits from AgentRandom (in qchess)
874 def __init__(self, name, colour):
875 InternalAgent.__init__(self, name, colour)
876 self.value = {"pawn" : 1, "bishop" : 3, "knight" : 3, "rook" : 5, "queen" : 9, "king" : 100, "unknown" : 4}
878 self.aggression = 2.0 # Multiplier for scoring due to aggressive actions
879 self.defence = 1.0 # Multiplier for scoring due to defensive actions
881 self.depth = 0 # Current depth
882 self.max_depth = 2 # Recurse this many times (for some reason, makes more mistakes when this is increased???)
883 self.recurse_for = -1 # Recurse for the best few moves each times (less than 0 = all moves)
885 for p in self.board.pieces["white"] + self.board.pieces["black"]:
887 p.selected_moves = None
891 def get_value(self, piece):
894 return float(self.value[piece.types[0]] + self.value[piece.types[1]]) / 2.0
896 # Score possible moves for the piece
898 def prioritise_moves(self, piece):
900 #sys.stderr.write(sys.argv[0] + " : " + str(self) + " prioritise called for " + str(piece) + "\n")
904 grid = self.board.probability_grid(piece)
905 #sys.stderr.write("\t Probability grid " + str(grid) + "\n")
909 if grid[x][y] < 0.3: # Throw out moves with < 30% probability
910 #sys.stderr.write("\tReject " + str(x) + "," + str(y) + " (" + str(grid[x][y]) + ")\n")
913 target = self.board.grid[x][y]
918 # Get total probability that the move is protected
919 self.board.push_move(piece, x, y)
923 defenders = self.board.coverage(x, y, piece.colour, reject_allied = False)
925 for d in defenders.keys():
926 d_prob += defenders[d]
927 if len(defenders.keys()) > 0:
928 d_prob /= float(len(defenders.keys()))
933 # Get total probability that the move is threatened
934 attackers = self.board.coverage(x, y, opponent(piece.colour), reject_allied = False)
936 for a in attackers.keys():
937 a_prob += attackers[a]
938 if len(attackers.keys()) > 0:
939 a_prob /= float(len(attackers.keys()))
944 self.board.pop_move()
949 value = self.aggression * (1.0 + d_prob) * self.get_value(target) - self.defence * (1.0 - d_prob) * a_prob * self.get_value(piece)
951 # Adjust score based on movement of piece out of danger
952 attackers = self.board.coverage(piece.x, piece.y, opponent(piece.colour))
954 for a in attackers.keys():
955 s_prob += attackers[a]
956 if len(attackers.keys()) > 0:
957 s_prob /= float(len(attackers.keys()))
961 value += self.defence * s_prob * self.get_value(piece)
963 # Adjust score based on probability that the move is actually possible
964 moves.append([[x, y], grid[x][y] * value])
966 moves.sort(key = lambda e : e[1], reverse = True)
967 #sys.stderr.write(sys.argv[0] + ": Moves for " + str(piece) + " are " + str(moves) + "\n")
969 piece.last_moves = moves
970 piece.selected_moves = None
977 def select_best(self, colour):
981 for p in self.board.pieces[colour]:
982 self.choice = p # Temporarily pick that piece
983 m = self.prioritise_moves(p)
985 all_moves.update({p : m[0]})
987 if len(all_moves.items()) <= 0:
991 opts = all_moves.items()
992 opts.sort(key = lambda e : e[1][1], reverse = True)
994 if self.depth >= self.max_depth:
998 if self.recurse_for >= 0:
999 opts = opts[0:self.recurse_for]
1000 #sys.stderr.write(sys.argv[0] + " : Before recurse, options are " + str(opts) + "\n")
1002 # Take the best few moves, and recurse
1003 for choice in opts[0:self.recurse_for]:
1004 [xx,yy] = [choice[0].x, choice[0].y] # Remember position
1005 [nx,ny] = choice[1][0] # Target
1006 [choice[0].x, choice[0].y] = [nx, ny] # Set position
1007 target = self.board.grid[nx][ny] # Remember piece in spot
1008 self.board.grid[xx][yy] = None # Remove piece
1009 self.board.grid[nx][ny] = choice[0] # Replace with moving piece
1012 best_enemy_move = self.select_best(opponent(choice[0].colour))
1013 choice[1][1] -= best_enemy_move[1][1] / float(self.depth + 1.0)
1015 [choice[0].x, choice[0].y] = [xx, yy] # Restore position
1016 self.board.grid[nx][ny] = target # Restore taken piece
1017 self.board.grid[xx][yy] = choice[0] # Restore moved piece
1021 opts.sort(key = lambda e : e[1][1], reverse = True)
1022 #sys.stderr.write(sys.argv[0] + " : After recurse, options are " + str(opts) + "\n")
1025 return list(opts[0])
1029 # Returns [x,y] of selected piece
1031 #sys.stderr.write("Getting choice...")
1032 self.choice = self.select_best(self.colour)[0]
1034 #sys.stderr.write(" Done " + str(self.choice)+"\n")
1035 return [self.choice.x, self.choice.y]
1037 # Returns [x,y] of square to move selected piece into
1039 #sys.stderr.write("Choice is " + str(self.choice) + "\n")
1040 self.choice.selected_moves = self.choice.last_moves
1041 moves = self.prioritise_moves(self.choice)
1045 return AgentRandom.get_move(self)
1047 # --- agent_bishop.py --- #
1048 import multiprocessing
1050 # Hacky alternative to using select for timing out players
1052 # WARNING: Do not wrap around HumanPlayer or things breakify
1053 # WARNING: Do not use in general or things breakify
1055 class Sleeper(multiprocessing.Process):
1056 def __init__(self, timeout):
1057 multiprocessing.Process.__init__(self)
1058 self.timeout = timeout
1061 time.sleep(self.timeout)
1064 class Worker(multiprocessing.Process):
1065 def __init__(self, function, args, q):
1066 multiprocessing.Process.__init__(self)
1067 self.function = function
1072 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args)
1073 self.q.put(self.function(*self.args))
1077 def TimeoutFunction(function, args, timeout):
1078 q = multiprocessing.Queue()
1079 w = Worker(function, args, q)
1080 s = Sleeper(timeout)
1083 while True: # Busy loop of crappyness
1084 if not w.is_alive():
1088 #print "TimeoutFunction gets " + str(result)
1090 elif not s.is_alive():
1093 raise Exception("TIMEOUT")
1098 # A player that wraps another player and times out its moves
1100 # A (crappy) alternative to the use of select()
1101 class TimeoutPlayer(Player):
1102 def __init__(self, base_player, timeout):
1103 Player.__init__(self, base_player.name, base_player.colour)
1104 self.base_player = base_player
1105 self.timeout = timeout
1108 return TimeoutFunction(self.base_player.select, [], self.timeout)
1112 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
1114 def update(self, result):
1115 return TimeoutFunction(self.base_player.update, [result], self.timeout)
1117 def quit(self, final_result):
1118 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
1119 # --- timeout_player.py --- #
1123 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
1124 network_timeout_delay = 1.0 # Maximum time between two characters being received
1127 def __init__(self, colour, address = None):
1128 self.socket = socket.socket()
1129 #self.socket.setblocking(0)
1131 if colour == "white":
1138 # print str(self) + " listens on port " + str(self.port)
1141 self.host = socket.gethostname()
1142 self.socket.bind((self.host, self.port))
1143 self.socket.listen(5)
1145 self.src, self.address = self.socket.accept()
1146 self.src.send("ok\n")
1147 if self.get_response() == "QUIT":
1151 self.socket.connect((address, self.port))
1152 self.src = self.socket
1153 self.src.send("ok\n")
1154 if self.get_response() == "QUIT":
1157 def get_response(self):
1158 # Timeout the start of the message (first character)
1159 if network_timeout_start > 0.0:
1160 ready = select.select([self.src], [], [], network_timeout_start)[0]
1163 if self.src in ready:
1164 s = self.src.recv(1)
1166 raise Exception("UNRESPONSIVE")
1169 while s[len(s)-1] != '\n':
1170 # Timeout on each character in the message
1171 if network_timeout_delay > 0.0:
1172 ready = select.select([self.src], [], [], network_timeout_delay)[0]
1175 if self.src in ready:
1176 s += self.src.recv(1)
1178 raise Exception("UNRESPONSIVE")
1180 return s.strip(" \r\n")
1182 def send_message(self,s):
1183 if network_timeout_start > 0.0:
1184 ready = select.select([], [self.src], [], network_timeout_start)[1]
1188 if self.src in ready:
1189 self.src.send(s + "\n")
1191 raise Exception("UNRESPONSIVE")
1193 def check_quit(self, s):
1197 game.final_result = " ".join(s[1:]) + " " + str(opponent(self.colour))
1203 class NetworkSender(Player,Network):
1204 def __init__(self, base_player, address = None):
1205 self.base_player = base_player
1206 Player.__init__(self, base_player.name, base_player.colour)
1208 self.address = address
1211 Network.__init__(self, self.base_player.colour, self.address)
1216 [x,y] = self.base_player.select()
1217 choice = self.board.grid[x][y]
1218 s = str(x) + " " + str(y)
1219 #print str(self) + ".select sends " + s
1220 self.send_message(s)
1224 [x,y] = self.base_player.get_move()
1225 s = str(x) + " " + str(y)
1226 #print str(self) + ".get_move sends " + s
1227 self.send_message(s)
1230 def update(self, s):
1231 self.base_player.update(s)
1233 [x,y] = map(int, s[0:2])
1234 selected = self.board.grid[x][y]
1235 if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
1236 s = " ".join(s[0:3])
1238 if selected.types_revealed[i] == True:
1239 s += " " + str(selected.types[i])
1242 #print str(self) + ".update sends " + s
1243 self.send_message(s)
1246 def quit(self, final_result):
1247 self.base_player.quit(final_result)
1248 #self.src.send("QUIT " + str(final_result) + "\n")
1251 class NetworkReceiver(Player,Network):
1252 def __init__(self, colour, address=None):
1254 Player.__init__(self, address, colour)
1256 self.address = address
1261 Network.__init__(self, self.colour, self.address)
1266 s = self.get_response()
1267 #print str(self) + ".select gets " + s
1268 [x,y] = map(int,s.split(" "))
1269 if x == -1 and y == -1:
1270 #print str(self) + ".select quits the game"
1272 game.final_state = "network terminated " + self.colour
1276 s = self.get_response()
1277 #print str(self) + ".get_move gets " + s
1278 [x,y] = map(int,s.split(" "))
1279 if x == -1 and y == -1:
1280 #print str(self) + ".get_move quits the game"
1282 game.final_state = "network terminated " + self.colour
1286 def update(self, result):
1288 result = result.split(" ")
1289 [x,y] = map(int, result[0:2])
1290 selected = self.board.grid[x][y]
1291 if selected != None and selected.colour == self.colour and len(result) > 2 and not "->" in result:
1292 s = self.get_response()
1293 #print str(self) + ".update - receives " + str(s)
1295 selected.choice = int(s[2])
1297 selected.types[i] = str(s[3+i])
1298 if s[3+i] == "unknown":
1299 selected.types_revealed[i] = False
1301 selected.types_revealed[i] = True
1302 selected.current_type = selected.types[selected.choice]
1305 #print str(self) + ".update - ignore result " + str(result)
1308 def quit(self, final_result):
1311 # --- network.py --- #
1314 # A thread that can be stopped!
1315 # Except it can only be stopped if it checks self.stopped() periodically
1316 # So it can sort of be stopped
1317 class StoppableThread(threading.Thread):
1319 threading.Thread.__init__(self)
1320 self._stop = threading.Event()
1326 return self._stop.isSet()
1327 # --- thread_util.py --- #
1333 def __init__(self, log):
1337 self.log.write("# Log starts " + str(datetime.datetime.now()) + "\n")
1340 now = datetime.datetime.now()
1341 self.log.write(str(now) + " : " + s + "\n")
1342 self.logged.append((now, s))
1344 def setup(self, board, players):
1347 self.log.write("# " + p.colour + " : " + p.name + "\n")
1349 self.log.write("# Initial board\n")
1350 for x in range(0, w):
1351 for y in range(0, h):
1352 if board.grid[x][y] != None:
1353 self.log.write(str(board.grid[x][y]) + "\n")
1355 self.log.write("# Start game\n")
1358 self.log.write("# EOF\n")
1359 if self.log != sys.stdout:
1362 class ShortLog(LogFile):
1363 def __init__(self, file_name):
1365 self.log = sys.stdout
1367 self.log = open(file_name, "w", 0)
1368 LogFile.__init__(self, self.log)
1369 self.file_name = file_name
1373 now = datetime.datetime.now()
1374 self.logged.append((now, s))
1377 if self.log != sys.stdout:
1379 self.log = open(self.file_name, "w", 0)
1380 self.log.write("# Short log updated " + str(datetime.datetime.now()) + "\n")
1381 LogFile.setup(self, game.board, game.players)
1383 elif self.phase == 1:
1384 for message in self.logged[len(self.logged)-2:]:
1385 self.log.write(str(message[0]) + " : " + message[1] + "\n")
1387 self.phase = (self.phase + 1) % 2
1391 ending = self.logged[len(self.logged)-1]
1392 self.log.write(str(ending[0]) + " : " + ending[1] + "\n")
1393 self.log.write("# EOF\n")
1394 if self.log != sys.stdout:
1398 class HeadRequest(urllib2.Request):
1399 def get_method(self):
1402 class HttpGetter(StoppableThread):
1403 def __init__(self, address):
1404 StoppableThread.__init__(self)
1405 self.address = address
1406 self.log = urllib2.urlopen(address)
1408 self.lock = threading.RLock() #lock for access of self.state
1409 self.cond = threading.Condition() # conditional
1412 while not self.stopped():
1413 line = self.log.readline()
1415 date_mod = datetime.datetime.strptime(self.log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1418 next_log = urllib2.urlopen(HeadRequest(self.address))
1419 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1420 while date_new <= date_mod and not self.stopped():
1421 next_log = urllib2.urlopen(HeadRequest(self.address))
1422 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1426 self.log = urllib2.urlopen(self.address)
1427 line = self.log.readline()
1430 self.lines.append(line)
1431 self.cond.notifyAll()
1434 #sys.stderr.write(" HttpGetter got \'" + str(line) + "\'\n")
1443 def __init__(self, address):
1444 self.getter = HttpGetter(address)
1448 self.getter.cond.acquire()
1449 while len(self.getter.lines) == 0:
1450 self.getter.cond.wait()
1452 result = self.getter.lines[0]
1453 self.getter.lines = self.getter.lines[1:]
1454 self.getter.cond.release()
1463 def __init__(self, filename):
1464 self.f = open(filename, "r", 0)
1465 self.filename = filename
1466 self.mod = os.path.getmtime(filename)
1470 line = self.f.readline()
1473 mod2 = os.path.getmtime(self.filename)
1475 #sys.stderr.write("File changed!\n")
1478 self.f = open(self.filename, "r", 0)
1480 new_line = self.f.readline()
1482 if " ".join(new_line.split(" ")[0:3]) != "# Short log":
1483 for i in range(self.count):
1484 new_line = self.f.readline()
1485 #sys.stderr.write("Read back " + str(i) + ": " + str(new_line) + "\n")
1486 new_line = self.f.readline()
1504 def log_init(board, players):
1506 l.setup(board, players)
1514 # A thread that runs the game
1515 class GameThread(StoppableThread):
1516 def __init__(self, board, players):
1517 StoppableThread.__init__(self)
1519 self.players = players
1520 self.state = {"turn" : None} # The game state
1521 self.error = 0 # Whether the thread exits with an error
1522 self.lock = threading.RLock() #lock for access of self.state
1523 self.cond = threading.Condition() # conditional for some reason, I forgot
1524 self.final_result = ""
1528 # Run the game (run in new thread with start(), run in current thread with run())
1531 while not self.stopped():
1533 for p in self.players:
1535 if isinstance(p, NetworkSender):
1536 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
1538 self.state["turn"] = p
1541 [x,y] = p.select() # Player selects a square
1548 result = self.board.select(x, y, colour = p.colour)
1549 for p2 in self.players:
1550 p2.update(result) # Inform players of what happened
1555 target = self.board.grid[x][y]
1556 if isinstance(graphics, GraphicsThread):
1558 graphics.state["moves"] = self.board.possible_moves(target)
1559 graphics.state["select"] = target
1561 time.sleep(turn_delay)
1564 if len(self.board.possible_moves(target)) == 0:
1565 #print "Piece cannot move"
1567 if isinstance(graphics, GraphicsThread):
1569 graphics.state["moves"] = None
1570 graphics.state["select"] = None
1571 graphics.state["dest"] = None
1575 [x2,y2] = p.get_move() # Player selects a destination
1582 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1585 self.board.update_move(x, y, x2, y2)
1587 for p2 in self.players:
1588 p2.update(result) # Inform players of what happened
1592 if isinstance(graphics, GraphicsThread):
1594 graphics.state["moves"] = [[x2,y2]]
1596 time.sleep(turn_delay)
1598 if isinstance(graphics, GraphicsThread):
1600 graphics.state["select"] = None
1601 graphics.state["dest"] = None
1602 graphics.state["moves"] = None
1604 # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
1605 # except Exception,e:
1606 # result = e.message
1607 # #sys.stderr.write(result + "\n")
1611 # self.final_result = self.state["turn"].colour + " " + e.message
1613 end = self.board.end_condition()
1617 self.final_result = self.state["turn"].colour + " " + end
1619 self.final_result = end
1626 for p2 in self.players:
1627 p2.quit(self.final_result)
1629 log(self.final_result)
1631 if isinstance(graphics, GraphicsThread):
1635 # A thread that replays a log file
1636 class ReplayThread(GameThread):
1637 def __init__(self, players, src, end=False,max_moves=None):
1638 self.board = Board(style="empty")
1639 self.board.max_moves = max_moves
1640 GameThread.__init__(self, self.board, players)
1644 self.reset_board(self.src.readline())
1646 def reset_board(self, line):
1649 while line != "# Start game" and line != "# EOF":
1652 line = self.src.readline().strip(" \r\n")
1656 line = self.src.readline().strip(" \r\n")
1659 self_str += line + "\n"
1661 if self.players[0].name == "dummy" and self.players[1].name == "dummy":
1662 line = self.src.readline().strip(" \r\n")
1665 tokens = line.split(" ")
1666 types = map(lambda e : e.strip("[] ,'"), tokens[2:4])
1667 for i in range(len(types)):
1668 if types[i][0] == "?":
1669 types[i] = "unknown"
1671 agent_str += tokens[0] + " " + tokens[1] + " " + str(types) + " ".join(tokens[4:]) + "\n"
1672 line = self.src.readline().strip(" \r\n")
1674 for p in self.players:
1675 p.reset_board(agent_str)
1678 self.board.reset_board(self_str)
1684 line = self.src.readline().strip(" \r\n")
1685 while line != "# EOF":
1697 line = self.src.readline().strip(" \r\n")
1700 tokens = line.split(" ")
1701 if tokens[0] == "white" or tokens[0] == "black":
1702 self.reset_board(line)
1704 line = self.src.readline().strip(" \r\n")
1707 move = line.split(":")
1708 move = move[len(move)-1].strip(" \r\n")
1709 tokens = move.split(" ")
1713 [x,y] = map(int, tokens[0:2])
1721 target = self.board.grid[x][y]
1723 if target.colour == "white":
1724 self.state["turn"] = self.players[0]
1726 self.state["turn"] = self.players[1]
1728 move_piece = (tokens[2] == "->")
1730 [x2,y2] = map(int, tokens[len(tokens)-2:])
1732 if isinstance(graphics, GraphicsThread):
1734 graphics.state["select"] = target
1737 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
1738 if isinstance(graphics, GraphicsThread):
1740 if target.current_type != "unknown":
1741 graphics.state["moves"] = self.board.possible_moves(target)
1743 graphics.state["moves"] = None
1744 time.sleep(turn_delay)
1746 self.board.update_move(x, y, x2, y2)
1747 if isinstance(graphics, GraphicsThread):
1749 graphics.state["moves"] = [[x2,y2]]
1750 time.sleep(turn_delay)
1752 graphics.state["select"] = None
1753 graphics.state["moves"] = None
1754 graphics.state["dest"] = None
1760 for p in self.players:
1764 line = self.src.readline().strip(" \r\n")
1767 end = self.board.end_condition()
1769 self.final_result = end
1787 if self.end and isinstance(graphics, GraphicsThread):
1789 pass # Let the user stop the display
1790 elif not self.end and self.board.end_condition() == None:
1792 # Work out the last move
1794 t = last_line.split(" ")
1795 if t[len(t)-2] == "black":
1796 self.players.reverse()
1797 elif t[len(t)-2] == "white":
1799 elif self.state["turn"] != None and self.state["turn"].colour == "white":
1800 self.players.reverse()
1803 game = GameThread(self.board, self.players)
1810 def opponent(colour):
1811 if colour == "white":
1822 # Dictionary that stores the unicode character representations of the different pieces
1823 # Chess was clearly the reason why unicode was invented
1824 # For some reason none of the pygame chess implementations I found used them!
1825 piece_char = {"white" : {"king" : u'\u2654',
1826 "queen" : u'\u2655',
1828 "bishop" : u'\u2657',
1829 "knight" : u'\u2658',
1832 "black" : {"king" : u'\u265A',
1833 "queen" : u'\u265B',
1835 "bishop" : u'\u265D',
1836 "knight" : u'\u265E',
1840 images = {"white" : {}, "black" : {}}
1841 small_images = {"white" : {}, "black" : {}}
1843 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
1845 # Get the font sizes
1846 l_size = 5*(grid_sz[0] / 8)
1847 s_size = 3*(grid_sz[0] / 8)
1849 for c in piece_char.keys():
1852 for p in piece_char[c].keys():
1853 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
1854 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})
1856 for p in piece_char[c].keys():
1857 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1858 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1859 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1860 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1863 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
1864 if not os.path.exists(image_dir):
1865 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
1866 for c in piece_char.keys():
1867 for p in piece_char[c].keys():
1868 images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
1869 small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
1870 # --- images.py --- #
1871 graphics_enabled = True
1875 graphics_enabled = False
1880 # A thread to make things pretty
1881 class GraphicsThread(StoppableThread):
1882 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1883 StoppableThread.__init__(self)
1887 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1888 pygame.display.set_caption(title)
1890 #print "Initialised properly"
1892 self.grid_sz = grid_sz[:]
1893 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
1895 self.lock = threading.RLock()
1896 self.cond = threading.Condition()
1899 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
1901 #create_images(grid_sz)
1902 create_images(grid_sz)
1905 for c in images.keys():
1906 for p in images[c].keys():
1907 images[c][p] = images[c][p].convert(self.window)
1908 small_images[c][p] = small_images[c][p].convert(self.window)
1915 # On the run from the world
1918 while not self.stopped():
1920 #print "Display grid"
1921 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
1923 #print "Display overlay"
1926 #print "Display pieces"
1927 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
1929 pygame.display.flip()
1931 for event in pygame.event.get():
1932 if event.type == pygame.QUIT:
1933 if isinstance(game, GameThread):
1935 game.final_result = ""
1936 if game.state["turn"] != None:
1937 game.final_result = game.state["turn"].colour + " "
1938 game.final_result += "terminated"
1942 elif event.type == pygame.MOUSEBUTTONDOWN:
1943 self.mouse_down(event)
1944 elif event.type == pygame.MOUSEBUTTONUP:
1945 self.mouse_up(event)
1952 self.message("Game ends, result \""+str(game.final_result) + "\"")
1955 # Wake up anyone who is sleeping
1960 pygame.quit() # Time to say goodbye
1962 # Mouse release event handler
1963 def mouse_up(self, event):
1964 if event.button == 3:
1966 self.state["overlay"] = None
1967 elif event.button == 2:
1969 self.state["coverage"] = None
1971 # Mouse click event handler
1972 def mouse_down(self, event):
1973 if event.button == 1:
1974 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
1975 if isinstance(game, GameThread):
1977 p = game.state["turn"]
1982 if isinstance(p, HumanPlayer):
1984 s = self.board.grid[m[0]][m[1]]
1985 select = self.state["select"]
1987 if s != None and s.colour != p.colour:
1988 self.message("Wrong colour") # Look at all this user friendliness!
1991 # Notify human player of move
1994 self.state["select"] = s
1995 self.state["dest"] = None
2004 if self.state["moves"] == None:
2007 if not m in self.state["moves"]:
2008 self.message("Illegal Move") # I still think last year's mouse interface was adequate
2013 if self.state["dest"] == None:
2015 self.state["dest"] = m
2016 self.state["select"] = None
2017 self.state["moves"] = None
2020 elif event.button == 3:
2021 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2022 if isinstance(game, GameThread):
2024 p = game.state["turn"]
2029 if isinstance(p, HumanPlayer):
2031 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
2033 elif event.button == 2:
2034 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2035 if isinstance(game, GameThread):
2037 p = game.state["turn"]
2042 if isinstance(p, HumanPlayer):
2044 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
2049 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
2050 # Draw square over the selected piece
2052 select = self.state["select"]
2054 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
2055 square_img.fill(pygame.Color(0,255,0,64))
2056 self.window.blit(square_img, mp)
2057 # If a piece is selected, draw all reachable squares
2058 # (This quality user interface has been patented)
2060 m = self.state["moves"]
2062 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
2064 mp = [self.grid_sz[i] * move[i] for i in range(2)]
2065 self.window.blit(square_img, mp)
2066 # If a piece is overlayed, show all squares that it has a probability to reach
2068 m = self.state["overlay"]
2073 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
2074 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
2075 self.window.blit(square_img, mp)
2076 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2077 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
2078 self.window.blit(text, mp)
2080 # If a square is selected, highlight all pieces that have a probability to reach it
2082 m = self.state["coverage"]
2085 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
2086 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
2087 self.window.blit(square_img, mp)
2088 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2089 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
2090 self.window.blit(text, mp)
2091 # Draw a square where the mouse is
2092 # This also serves to indicate who's turn it is
2094 if isinstance(game, GameThread):
2096 turn = game.state["turn"]
2100 if isinstance(turn, HumanPlayer):
2101 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
2102 square_img.fill(pygame.Color(0,0,255,128))
2103 if turn.colour == "white":
2104 c = pygame.Color(255,255,255)
2106 c = pygame.Color(0,0,0)
2107 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
2108 self.window.blit(square_img, mp)
2110 # Message in a bottle
2111 def message(self, string, pos = None, colour = None, font_size = 20):
2112 #print "Drawing message..."
2113 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2115 colour = pygame.Color(0,0,0)
2117 text = font.render(string, 1, colour)
2120 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
2121 s.fill(pygame.Color(128,128,128))
2123 tmp = self.window.get_size()
2126 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
2128 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
2131 rect = (pos[0], pos[1], text.get_width(), text.get_height())
2133 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
2134 self.window.blit(s, pos)
2135 self.window.blit(text, pos)
2137 pygame.display.flip()
2139 def getstr(self, prompt = None):
2140 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
2141 s.blit(self.window, (0,0))
2147 self.message(prompt)
2148 self.message(result, pos = (0, 1))
2151 for event in pygame.event.get():
2152 if event.type == pygame.QUIT:
2154 if event.type == pygame.KEYDOWN:
2155 if event.key == pygame.K_BACKSPACE:
2156 result = result[0:len(result)-1]
2157 self.window.blit(s, (0,0)) # Revert the display
2162 if event.unicode == '\r':
2165 result += str(event.unicode)
2170 # Function to pick a button
2171 def SelectButton(self, choices, prompt = None, font_size=20):
2173 #print "Select button called!"
2174 self.board.display_grid(self.window, self.grid_sz)
2176 self.message(prompt)
2177 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2179 sz = self.window.get_size()
2182 for i in range(len(choices)):
2185 text = font.render(c, 1, pygame.Color(0,0,0))
2186 p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
2187 targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
2190 mp =pygame.mouse.get_pos()
2191 for i in range(len(choices)):
2193 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
2194 font_colour = pygame.Color(255,0,0)
2195 box_colour = pygame.Color(0,0,255,128)
2197 font_colour = pygame.Color(0,0,0)
2198 box_colour = pygame.Color(128,128,128)
2200 text = font.render(c, 1, font_colour)
2201 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
2203 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
2204 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
2205 self.window.blit(s, targets[i][0:2])
2208 pygame.display.flip()
2210 for event in pygame.event.get():
2211 if event.type == pygame.QUIT:
2213 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
2214 for i in range(len(targets)):
2216 if event.pos[0] > t[0] and event.pos[0] < t[2]:
2217 if event.pos[1] > t[1] and event.pos[1] < t[3]:
2219 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
2222 # Function to pick players in a nice GUI way
2223 def SelectPlayers(self, players = []):
2226 #print "SelectPlayers called"
2228 missing = ["white", "black"]
2230 missing.remove(p.colour)
2232 for colour in missing:
2235 choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
2237 players.append(HumanPlayer("human", colour))
2240 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2241 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2242 internal_agents.remove(('InternalAgent', InternalAgent))
2243 if len(internal_agents) > 0:
2244 choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
2249 agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
2250 players.append(agent[1](agent[0], colour))
2254 from tkFileDialog import askopenfilename
2255 root = Tkinter.Tk() # Need a root to make Tkinter behave
2256 root.withdraw() # Some sort of magic incantation
2257 path = askopenfilename(parent=root, initialdir="../agents",title=
2260 return self.SelectPlayers()
2261 players.append(make_player(path, colour))
2266 self.board.display_grid(self.window, self.grid_sz)
2267 pygame.display.flip()
2268 path = self.getstr(prompt = "Enter path:")
2273 return self.SelectPlayers()
2276 p = make_player(path, colour)
2278 self.board.display_grid(self.window, self.grid_sz)
2279 pygame.display.flip()
2280 self.message("Invalid path!")
2286 while address == "":
2287 self.board.display_grid(self.window, self.grid_sz)
2289 address = self.getstr(prompt = "Address? (leave blank for server)")
2296 map(int, address.split("."))
2298 self.board.display_grid(self.window, self.grid_sz)
2299 self.message("Invalid IPv4 address!")
2302 players.append(NetworkReceiver(colour, address))
2305 #print str(self) + ".SelectPlayers returns " + str(players)
2310 # --- graphics.py --- #
2311 #!/usr/bin/python -u
2313 # Do you know what the -u does? It unbuffers stdin and stdout
2314 # I can't remember why, but last year things broke without that
2317 UCC::Progcomp 2013 Quantum Chess game
2318 @author Sam Moore [SZM] "matches"
2319 @copyright The University Computer Club, Incorporated
2320 (ie: You can copy it for not for profit purposes)
2323 # system python modules or whatever they are called
2329 [game, graphics] = [None, None]
2331 def make_player(name, colour):
2333 if name[1:] == "human":
2334 return HumanPlayer(name, colour)
2335 s = name[1:].split(":")
2336 if s[0] == "network":
2340 return NetworkReceiver(colour, address)
2341 if s[0] == "internal":
2344 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2345 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2346 internal_agents.remove(('InternalAgent', InternalAgent))
2349 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
2350 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2353 for a in internal_agents:
2355 return a[1](name, colour)
2357 sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
2358 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2363 return ExternalAgent(name, colour)
2367 # The main function! It does the main stuff!
2370 # Apparently python will silently treat things as local unless you do this
2371 # Anyone who says "You should never use a global variable" can die in a fire
2376 global agent_timeout
2379 global graphics_enabled
2380 global always_reveal_states
2388 # Get the important warnings out of the way
2389 if platform.system() == "Windows":
2390 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
2391 if platform.release() == "Vista":
2392 sys.stderr.write(sys.argv[0] + " : God help you.\n")
2397 while i < len(argv)-1:
2401 p = make_player(arg, colour)
2402 if not isinstance(p, Player):
2403 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
2406 if colour == "white":
2408 elif colour == "black":
2411 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
2414 # Option parsing goes here
2415 if arg[1] == '-' and arg[2:] == "classical":
2417 elif arg[1] == '-' and arg[2:] == "quantum":
2419 elif arg[1] == '-' and arg[2:] == "reveal":
2420 always_reveal_states = True
2421 elif (arg[1] == '-' and arg[2:] == "graphics"):
2422 graphics_enabled = True
2423 elif (arg[1] == '-' and arg[2:] == "no-graphics"):
2424 graphics_enabled = False
2425 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
2426 # Load game from file
2427 if len(arg[2:].split("=")) == 1:
2428 src_file = sys.stdin
2430 f = arg[2:].split("=")[1]
2431 if f[0:7] == "http://":
2432 src_file = HttpReplay(f)
2434 src_file = FileReplay(f.split(":")[0])
2436 if len(f.split(":")) == 2:
2437 max_moves = int(f.split(":")[1])
2439 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
2441 if len(arg[2:].split("=")) == 1:
2442 log_files.append(LogFile(sys.stdout))
2444 f = arg[2:].split("=")[1]
2446 log_files.append(ShortLog(f[1:]))
2448 log_files.append(LogFile(open(f, "w", 0)))
2449 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
2451 if len(arg[2:].split("=")) == 1:
2454 turn_delay = float(arg[2:].split("=")[1])
2456 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
2458 if len(arg[2:].split("=")) == 1:
2461 agent_timeout = float(arg[2:].split("=")[1])
2463 elif (arg[1] == '-' and arg[2:] == "help"):
2465 os.system("less data/help.txt") # The best help function
2471 # Construct a GameThread! Make it global! Damn the consequences!
2473 if src_file != None:
2474 # Hack to stop ReplayThread from exiting
2475 #if len(players) == 0:
2476 # players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
2478 # Normally the ReplayThread exits if there are no players
2479 # TODO: Decide which behaviour to use, and fix it
2480 end = (len(players) == 0)
2482 players = [Player("dummy", "white"), Player("dummy", "black")]
2483 elif len(players) != 2:
2484 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2485 if graphics_enabled:
2486 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
2488 game = ReplayThread(players, src_file, end=end, max_moves=max_moves)
2490 board = Board(style)
2491 board.max_moves = max_moves
2492 game = GameThread(board, players)
2498 if graphics_enabled == True:
2500 graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
2504 sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
2505 graphics_enabled = False
2507 # If there are no players listed, display a nice pretty menu
2508 if len(players) != 2:
2509 if graphics != None:
2510 players = graphics.SelectPlayers(players)
2512 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2515 # If there are still no players, quit
2516 if players == None or len(players) != 2:
2517 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
2521 # Wrap NetworkSender players around original players if necessary
2522 for i in range(len(players)):
2523 if isinstance(players[i], NetworkReceiver):
2524 players[i].board = board # Network players need direct access to the board
2525 for j in range(len(players)):
2528 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
2530 players[j] = NetworkSender(players[j], players[i].address)
2531 players[j].board = board
2533 # Connect the networked players
2535 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
2536 if graphics != None:
2537 graphics.board.display_grid(graphics.window, graphics.grid_sz)
2538 graphics.message("Connecting to " + p.colour + " player...")
2542 # If using windows, select won't work; use horrible TimeoutPlayer hack
2543 if agent_timeout > 0:
2544 if platform.system() == "Windows":
2545 for i in range(len(players)):
2546 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
2547 players[i] = TimeoutPlayer(players[i], agent_timeout)
2551 # InternalAgents get wrapped to an ExternalAgent when there is a timeout
2552 # This is not confusing at all.
2553 for i in range(len(players)):
2554 if isinstance(players[i], InternalAgent):
2555 players[i] = ExternalWrapper(players[i])
2563 log_init(game.board, players)
2566 if graphics != None:
2567 game.start() # This runs in a new thread
2573 error = game.error + graphics.error
2582 if src_file != None and src_file != sys.stdin:
2585 sys.stdout.write(game.final_result + "\n")
2589 # This is how python does a main() function...
2590 if __name__ == "__main__":
2592 sys.exit(main(sys.argv))
2593 except KeyboardInterrupt:
2594 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
2595 if isinstance(graphics, StoppableThread):
2597 graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
2599 if isinstance(game, StoppableThread):
2607 # EOF - created from make on Thu Feb 28 23:49:16 WST 2013