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 = {}
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 if self.types[i][0] == '?':
63 img = small_images[self.colour][self.types[i][1:]]
65 img = small_images[self.colour][self.types[i]]
67 img = small_images[self.colour]["unknown"] # If the type hasn't been revealed, show a placeholder
71 offset = [-rect.width/2,-rect.height/2]
74 target = (self.x * grid_sz[0] + grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])
76 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])
78 window.blit(img, target) # Blit shit
80 # Collapses the wave function!
82 if self.current_type == "unknown" or not self.choice in [0,1]:
83 self.choice = random.randint(0,1)
84 if self.types[self.choice][0] == '?':
85 self.types[self.choice] = self.types[self.choice][1:]
86 self.current_type = self.types[self.choice]
89 # Uncollapses (?) the wave function!
91 #print "Deselect called"
92 if (self.x + self.y) % 2 != 0:
93 if (self.types[0] != self.types[1]) or (self.types[0][0] == '?' or self.types[1][0] == '?'):
94 self.current_type = "unknown"
97 self.choice = 0 # Both the two types are the same
99 # The sad moment when you realise that you do not understand anything about a subject you studied for 4 years...
101 [w,h] = [8,8] # Width and height of board(s)
103 always_reveal_states = False
105 # Class to represent a quantum chess board
107 # Initialise; if master=True then the secondary piece types are assigned
108 # Otherwise, they are left as unknown
109 # So you can use this class in Agent programs, and fill in the types as they are revealed
110 def __init__(self, style="agent"):
112 self.pieces = {"white" : [], "black" : []}
113 self.grid = [[None] * w for _ in range(h)] # 2D List (you can get arrays in python, somehow, but they scare me)
114 self.unrevealed_types = {"white" : piece_types.copy(), "black" : piece_types.copy()}
115 self.king = {"white" : None, "black" : None} # We need to keep track of the king, because he is important
116 self.max_moves = None
119 for c in ["black", "white"]:
120 del self.unrevealed_types[c]["unknown"]
125 # Add all the pieces with known primary types
126 for i in range(0, 2):
128 s = ["black", "white"][i]
132 c.append(Piece(s, 0, y, ["rook"]))
133 c.append(Piece(s, 1, y, ["knight"]))
134 c.append(Piece(s, 2, y, ["bishop"]))
135 k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
136 k.current_type = "king"
139 c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
140 c.append(Piece(s, 5, y, ["bishop"]))
141 c.append(Piece(s, 6, y, ["knight"]))
142 c.append(Piece(s, 7, y, ["rook"]))
150 for x in range(0, w):
151 c.append(Piece(s, x, y, ["pawn"]))
154 types_left.update(piece_types)
155 del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
156 del types_left["unknown"] # We certainly don't want these!
159 self.grid[piece.x][piece.y] = piece
161 if len(piece.types) > 1:
163 if style == "agent": # Assign placeholder "unknown" secondary type
164 piece.types.append("unknown")
167 elif style == "quantum":
168 # The master allocates the secondary types
169 choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
170 types_left[choice] -= 1
171 if types_left[choice] <= 0:
172 del types_left[choice]
173 piece.types.append('?' + choice)
174 elif style == "classical":
175 piece.types.append(piece.types[0])
176 piece.current_type = piece.types[0]
180 newboard = Board(master = False)
181 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
182 mypieces = self.pieces["white"] + self.pieces["black"]
184 for i in range(len(mypieces)):
185 newpieces[i].init_from_copy(mypieces[i])
187 # Reset the board from a string
188 def reset_board(self, s):
189 self.pieces = {"white" : [], "black" : []}
190 self.king = {"white" : None, "black" : None}
191 self.grid = [[None] * w for _ in range(h)]
194 self.grid[x][y] = None
196 for line in s.split("\n"):
202 tokens = line.split(" ")
203 [x, y] = map(int, tokens[len(tokens)-1].split(","))
204 current_type = tokens[1]
205 types = map(lambda e : e.strip(" '[],"), line.split('[')[1].split(']')[0].split(','))
207 target = Piece(tokens[0], x, y, types)
208 target.current_type = current_type
211 target.choice = types.index(current_type)
215 self.pieces[tokens[0]].append(target)
216 if target.current_type == "king":
217 self.king[tokens[0]] = target
219 self.grid[x][y] = target
222 def display_grid(self, window = None, grid_sz = [80,80]):
224 return # I was considering implementing a text only display, then I thought "Fuck that"
226 # The indentation is getting seriously out of hand...
227 for x in range(0, w):
228 for y in range(0, h):
230 c = pygame.Color(200,200,200)
232 c = pygame.Color(64,64,64)
233 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
235 def display_pieces(self, window = None, grid_sz = [80,80]):
238 for p in self.pieces["white"] + self.pieces["black"]:
239 p.draw(window, grid_sz, self.style)
241 # Draw the board in a pygame window
242 def display(self, window = None):
243 self.display_grid(window)
244 self.display_pieces(window)
252 if self.grid[x][y] == None:
254 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
255 raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
257 # Select a piece on the board (colour is the colour of whoever is doing the selecting)
258 def select(self, x,y, colour=None):
259 if not self.on_board(x, y): # Get on board everyone!
260 raise Exception("BOUNDS")
262 piece = self.grid[x][y]
264 raise Exception("EMPTY")
266 if colour != None and piece.colour != colour:
267 raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
269 # I'm not quite sure why I made this return a string, but screw logical design
270 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
273 # Update the board when a piece has been selected
274 # "type" is apparently reserved, so I'll use "state"
275 def update_select(self, x, y, type_index, state):
276 piece = self.grid[x][y]
277 if piece.types[type_index] == "unknown":
278 if not state in self.unrevealed_types[piece.colour].keys():
279 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
280 self.unrevealed_types[piece.colour][state] -= 1
281 if self.unrevealed_types[piece.colour][state] <= 0:
282 del self.unrevealed_types[piece.colour][state]
284 piece.types[type_index] = state
285 piece.current_type = state
287 if len(self.possible_moves(piece)) <= 0:
288 piece.deselect() # Piece can't move; deselect it
290 # Piece needs to recalculate moves
291 piece.possible_moves = None
293 # Update the board when a piece has been moved
294 def update_move(self, x, y, x2, y2):
296 piece = self.grid[x][y]
297 #print "Moving " + str(x) + "," + str(y) + " to " + str(x2) + "," + str(y2) + "; possible_moves are " + str(self.possible_moves(piece))
299 if not [x2,y2] in self.possible_moves(piece):
300 raise Exception("ILLEGAL move " + str(x2)+","+str(y2))
302 self.grid[x][y] = None
303 taken = self.grid[x2][y2]
305 if taken.current_type == "king":
306 self.king[taken.colour] = None
307 self.pieces[taken.colour].remove(taken)
308 self.grid[x2][y2] = piece
312 # If the piece is a pawn, and it reaches the final row, it becomes a queen
313 # I know you are supposed to get a choice
314 # But that would be effort
315 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
316 if self.style == "classical":
317 piece.types[0] = "queen"
318 piece.types[1] = "queen"
320 piece.types[piece.choice] = "queen"
321 piece.current_type = "queen"
323 piece.deselect() # Uncollapse (?) the wavefunction!
326 # All other pieces need to recalculate moves
327 for p in self.pieces["white"] + self.pieces["black"]:
328 p.possible_moves = None
332 # Update the board from a string
333 # Guesses what to do based on the format of the string
334 def update(self, result):
335 #print "Update called with \"" + str(result) + "\""
336 # String always starts with 'x y'
338 s = result.split(" ")
339 [x,y] = map(int, s[0:2])
341 raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
343 piece = self.grid[x][y]
345 raise Exception("EMPTY")
347 # If a piece is being moved, the third token is '->'
348 # We could get away with just using four integers, but that wouldn't look as cool
350 # Last two tokens are the destination
352 [x2,y2] = map(int, s[3:])
354 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
356 # Move the piece (take opponent if possible)
357 self.update_move(x, y, x2, y2)
360 # Otherwise we will just assume a piece has been selected
362 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
363 state = s[3] # The last token is a string identifying the type
365 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
368 self.update_select(x, y, type_index, state)
372 # Gets each piece that could reach the given square and the probability that it could reach that square
373 # Will include allied pieces that defend the attacker
374 def coverage(self, x, y, colour = None, reject_allied = True):
378 pieces = self.pieces["white"] + self.pieces["black"]
380 pieces = self.pieces[colour]
383 prob = self.probability_grid(p, reject_allied)[x][y]
385 result.update({p : prob})
394 # Associates each square with a probability that the piece could move into it
395 # Look, I'm doing all the hard work for you here...
396 def probability_grid(self, p, reject_allied = True):
398 result = [[0.0] * w for _ in range(h)]
399 if not isinstance(p, Piece):
402 if p.current_type != "unknown":
403 #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
404 for point in self.possible_moves(p, reject_allied):
405 result[point[0]][point[1]] = 1.0
409 for i in range(len(p.types)):
411 prob = 1.0 / float(len(p.types))
412 if t == "unknown" or p.types[i][0] == '?':
414 for t2 in self.unrevealed_types[p.colour].keys():
415 total_types += self.unrevealed_types[p.colour][t2]
417 for t2 in self.unrevealed_types[p.colour].keys():
418 prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
420 for point in self.possible_moves(p, reject_allied, state=t2):
421 result[point[0]][point[1]] += prob2 * prob
425 for point in self.possible_moves(p, reject_allied, state=t):
426 result[point[0]][point[1]] += prob
429 #p.current_type = "unknown"
432 def prob_is_type(self, p, state):
435 for i in range(len(p.types)):
440 if t == "unknown" or p.types[i][0] == '?':
442 for t2 in self.unrevealed_types[p.colour].keys():
443 total_prob += self.unrevealed_types[p.colour][t2]
444 for t2 in self.unrevealed_types[p.colour].keys():
446 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
450 # Get all squares that the piece could move into
451 # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
452 # reject_allied indicates whether squares occupied by allied pieces will be removed
453 # (set to false to check for defense)
454 def possible_moves(self, p, reject_allied = True, state=None):
456 raise Exception("SANITY: No piece")
460 if state != None and state != p.current_type:
461 old_type = p.current_type
462 p.current_type = state
463 result = self.possible_moves(p, reject_allied, state=None)
464 p.current_type = old_type
474 if p.current_type == "unknown":
475 raise Exception("SANITY: Piece state unknown")
476 # The below commented out code causes things to break badly
481 # result += self.possible_moves(p)
482 #p.current_type = "unknown"
485 if p.current_type == "king":
486 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]]
487 elif p.current_type == "queen":
488 for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
489 result += self.scan(p.x, p.y, d[0], d[1])
490 elif p.current_type == "bishop":
491 for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
492 result += self.scan(p.x, p.y, d[0], d[1])
493 elif p.current_type == "rook":
494 for d in [[-1,0],[1,0],[0,-1],[0,1]]:
495 result += self.scan(p.x, p.y, d[0], d[1])
496 elif p.current_type == "knight":
497 # I would use two lines, but I'm not sure how python likes that
498 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]]
499 elif p.current_type == "pawn":
500 if p.colour == "white":
502 # Pawn can't move forward into occupied square
503 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
504 result = [[p.x,p.y-1]]
505 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
506 if not self.on_board(f[0], f[1]):
508 if self.grid[f[0]][f[1]] != None: # Pawn can take diagonally
511 # Slightly embarrassing if the pawn jumps over someone on its first move...
512 if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
513 result.append([p.x, p.y-2])
515 # Vice versa for the black pawn
516 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
517 result = [[p.x,p.y+1]]
519 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
520 if not self.on_board(f[0], f[1]):
522 if self.grid[f[0]][f[1]] != None:
523 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
526 if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
527 result.append([p.x, p.y+2])
529 #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
531 # Remove illegal moves
532 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
533 for point in result[:]:
535 if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
536 result.remove(point) # Remove locations outside the board
538 g = self.grid[point[0]][point[1]]
540 if g != None and (g.colour == p.colour and reject_allied == True):
541 result.remove(point) # Remove allied pieces
545 p.possible_moves = result
549 # Scans in a direction until it hits a piece, returns all squares in the line
550 # (includes the final square (which contains a piece), but not the original square)
551 def scan(self, x, y, vx, vy):
559 if not self.on_board(xx, yy):
563 g = self.grid[xx][yy]
569 # Returns "white", "black" or "DRAW" if the game should end
570 def end_condition(self):
571 if self.king["white"] == None:
572 if self.king["black"] == None:
573 return "DRAW" # This shouldn't happen
575 elif self.king["black"] == None:
577 elif len(self.pieces["white"]) == 1 and len(self.pieces["black"]) == 1:
579 elif self.max_moves != None and self.moves > self.max_moves:
584 # I typed the full statement about 30 times before writing this function...
585 def on_board(self, x, y):
586 return (x >= 0 and x < w) and (y >= 0 and y < h)
588 # Pushes a move temporarily
589 def push_move(self, piece, x, y):
590 target = self.grid[x][y]
591 self.move_stack.append([piece, target, piece.x, piece.y, x, y])
592 [piece.x, piece.y] = [x, y]
593 self.grid[x][y] = piece
594 self.grid[piece.x][piece.y] = None
596 for p in self.pieces["white"] + self.pieces["black"]:
597 p.possible_moves = None
601 #print str(self.move_stack)
602 [piece, target, x1, y1, x2, y2] = self.move_stack[len(self.move_stack)-1]
603 self.move_stack = self.move_stack[:-1]
606 self.grid[x1][y1] = piece
610 self.grid[x2][y2] = target
612 for p in self.pieces["white"] + self.pieces["black"]:
613 p.possible_moves = None
621 agent_timeout = -1.0 # Timeout in seconds for AI players to make moves
622 # WARNING: Won't work for windows based operating systems
624 if platform.system() == "Windows":
625 agent_timeout = -1 # Hence this
627 # A player who can't play
629 def __init__(self, name, colour):
633 def update(self, result):
636 def reset_board(self, s):
639 # Player that runs from another process
640 class ExternalAgent(Player):
643 def __init__(self, name, colour):
644 Player.__init__(self, name, colour)
645 self.p = subprocess.Popen(name,bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,universal_newlines=True)
647 self.send_message(colour)
649 def send_message(self, s):
650 if agent_timeout > 0.0:
651 ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
653 ready = [self.p.stdin]
654 if self.p.stdin in ready:
655 #sys.stderr.write("Writing \'" + s + "\' to " + str(self.p) + "\n")
657 self.p.stdin.write(s + "\n")
659 raise Exception("UNRESPONSIVE")
661 raise Exception("TIMEOUT")
663 def get_response(self):
664 if agent_timeout > 0.0:
665 ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
667 ready = [self.p.stdout]
668 if self.p.stdout in ready:
669 #sys.stderr.write("Reading from " + str(self.p) + " 's stdout...\n")
671 result = self.p.stdout.readline().strip(" \t\r\n")
672 #sys.stderr.write("Read \'" + result + "\' from " + str(self.p) + "\n")
674 except: # Exception, e:
675 raise Exception("UNRESPONSIVE")
677 raise Exception("TIMEOUT")
681 self.send_message("SELECTION?")
682 line = self.get_response()
685 m = re.match("\s*(\d+)\s+(\d+)\s*", line)
686 result = map(int, [m.group(1), m.group(2)])
688 raise Exception("GIBBERISH \"" + str(line) + "\"")
691 def update(self, result):
692 #print "Update " + str(result) + " called for AgentPlayer"
693 self.send_message(result)
698 self.send_message("MOVE?")
699 line = self.get_response()
702 m = re.match("\s*(\d+)\s+(\d+)\s*", line)
703 result = map(int, [m.group(1), m.group(2)])
706 raise Exception("GIBBERISH \"" + str(line) + "\"")
709 def reset_board(self, s):
710 self.send_message("BOARD")
711 for line in s.split("\n"):
712 self.send_message(line.strip(" \r\n"))
713 self.send_message("END BOARD")
715 def quit(self, final_result):
717 self.send_message("QUIT " + final_result)
721 # So you want to be a player here?
722 class HumanPlayer(Player):
723 def __init__(self, name, colour):
724 Player.__init__(self, name, colour)
726 # Select your preferred account
728 if isinstance(graphics, GraphicsThread):
729 # Basically, we let the graphics thread do some shit and then return that information to the game thread
730 graphics.cond.acquire()
731 # We wait for the graphics thread to select a piece
732 while graphics.stopped() == False and graphics.state["select"] == None:
733 graphics.cond.wait() # The difference between humans and machines is that humans sleep
734 select = graphics.state["select"]
737 graphics.cond.release()
738 if graphics.stopped():
740 return [select.x, select.y]
742 # Since I don't display the board in this case, I'm not sure why I filled it in...
744 sys.stdout.write("SELECTION?\n")
746 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
748 sys.stderr.write("ILLEGAL GIBBERISH\n")
750 # It's your move captain
752 if isinstance(graphics, GraphicsThread):
753 graphics.cond.acquire()
754 while graphics.stopped() == False and graphics.state["dest"] == None:
756 graphics.cond.release()
758 return graphics.state["dest"]
762 sys.stdout.write("MOVE?\n")
764 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
766 sys.stderr.write("ILLEGAL GIBBERISH\n")
769 # Are you sure you want to quit?
770 def quit(self, final_result):
772 sys.stdout.write("QUIT " + final_result + "\n")
774 # Completely useless function
775 def update(self, result):
776 if isinstance(graphics, GraphicsThread):
779 sys.stdout.write(result + "\n")
782 # Default internal player (makes random moves)
783 class InternalAgent(Player):
784 def __init__(self, name, colour):
785 Player.__init__(self, name, colour)
788 self.board = Board(style = "agent")
792 def update(self, result):
794 self.board.update(result)
797 def reset_board(self, s):
798 self.board.reset_board(s)
800 def quit(self, final_result):
803 class AgentRandom(InternalAgent):
804 def __init__(self, name, colour):
805 InternalAgent.__init__(self, name, colour)
809 self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
811 # Check that the piece has some possibility to move
812 tmp = self.choice.current_type
813 if tmp == "unknown": # For unknown pieces, try both types
814 for t in self.choice.types:
817 self.choice.current_type = t
818 all_moves += self.board.possible_moves(self.choice)
820 all_moves = self.board.possible_moves(self.choice)
821 self.choice.current_type = tmp
822 if len(all_moves) > 0:
824 return [self.choice.x, self.choice.y]
827 moves = self.board.possible_moves(self.choice)
828 move = moves[random.randint(0, len(moves)-1)]
832 # Terrible, terrible hacks
834 def run_agent(agent):
835 #sys.stderr.write(sys.argv[0] + " : Running agent " + str(agent) + "\n")
837 line = sys.stdin.readline().strip(" \r\n")
838 if line == "SELECTION?":
839 #sys.stderr.write(sys.argv[0] + " : Make selection\n")
840 [x,y] = agent.select() # Gets your agent's selection
841 #sys.stderr.write(sys.argv[0] + " : Selection was " + str(agent.choice) + "\n")
842 sys.stdout.write(str(x) + " " + str(y) + "\n")
843 elif line == "MOVE?":
844 #sys.stderr.write(sys.argv[0] + " : Make move\n")
845 [x,y] = agent.get_move() # Gets your agent's move
846 sys.stdout.write(str(x) + " " + str(y) + "\n")
847 elif line.split(" ")[0] == "QUIT":
848 #sys.stderr.write(sys.argv[0] + " : Quitting\n")
849 agent.quit(" ".join(line.split(" ")[1:])) # Quits the game
851 elif line.split(" ")[0] == "BOARD":
853 line = sys.stdin.readline().strip(" \r\n")
854 while line != "END BOARD":
856 line = sys.stdin.readline().strip(" \r\n")
857 agent.board.reset_board(s)
860 agent.update(line) # Updates agent.board
866 class ExternalWrapper(ExternalAgent):
867 def __init__(self, agent):
868 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))\""
870 ExternalAgent.__init__(self, run, agent.colour)
874 # --- player.py --- #
878 class AgentBishop(AgentRandom): # Inherits from AgentRandom (in qchess)
879 def __init__(self, name, colour):
880 InternalAgent.__init__(self, name, colour)
881 self.value = {"pawn" : 1, "bishop" : 3, "knight" : 3, "rook" : 5, "queen" : 9, "king" : 100, "unknown" : 4}
883 self.aggression = 2.0 # Multiplier for scoring due to aggressive actions
884 self.defence = 1.0 # Multiplier for scoring due to defensive actions
886 self.depth = 0 # Current depth
887 self.max_depth = 2 # Recurse this many times (for some reason, makes more mistakes when this is increased???)
888 self.recurse_for = -1 # Recurse for the best few moves each times (less than 0 = all moves)
890 for p in self.board.pieces["white"] + self.board.pieces["black"]:
892 p.selected_moves = None
896 def get_value(self, piece):
899 return float(self.value[piece.types[0]] + self.value[piece.types[1]]) / 2.0
901 # Score possible moves for the piece
903 def prioritise_moves(self, piece):
905 #sys.stderr.write(sys.argv[0] + " : " + str(self) + " prioritise called for " + str(piece) + "\n")
909 grid = self.board.probability_grid(piece)
910 #sys.stderr.write("\t Probability grid " + str(grid) + "\n")
914 if grid[x][y] < 0.3: # Throw out moves with < 30% probability
915 #sys.stderr.write("\tReject " + str(x) + "," + str(y) + " (" + str(grid[x][y]) + ")\n")
918 target = self.board.grid[x][y]
923 # Get total probability that the move is protected
924 self.board.push_move(piece, x, y)
928 defenders = self.board.coverage(x, y, piece.colour, reject_allied = False)
930 for d in defenders.keys():
931 d_prob += defenders[d]
932 if len(defenders.keys()) > 0:
933 d_prob /= float(len(defenders.keys()))
938 # Get total probability that the move is threatened
939 attackers = self.board.coverage(x, y, opponent(piece.colour), reject_allied = False)
941 for a in attackers.keys():
942 a_prob += attackers[a]
943 if len(attackers.keys()) > 0:
944 a_prob /= float(len(attackers.keys()))
949 self.board.pop_move()
954 value = self.aggression * (1.0 + d_prob) * self.get_value(target) - self.defence * (1.0 - d_prob) * a_prob * self.get_value(piece)
956 # Adjust score based on movement of piece out of danger
957 attackers = self.board.coverage(piece.x, piece.y, opponent(piece.colour))
959 for a in attackers.keys():
960 s_prob += attackers[a]
961 if len(attackers.keys()) > 0:
962 s_prob /= float(len(attackers.keys()))
966 value += self.defence * s_prob * self.get_value(piece)
968 # Adjust score based on probability that the move is actually possible
969 moves.append([[x, y], grid[x][y] * value])
971 moves.sort(key = lambda e : e[1], reverse = True)
972 #sys.stderr.write(sys.argv[0] + ": Moves for " + str(piece) + " are " + str(moves) + "\n")
974 piece.last_moves = moves
975 piece.selected_moves = None
982 def select_best(self, colour):
986 for p in self.board.pieces[colour]:
987 self.choice = p # Temporarily pick that piece
988 m = self.prioritise_moves(p)
990 all_moves.update({p : m[0]})
992 if len(all_moves.items()) <= 0:
996 opts = all_moves.items()
997 opts.sort(key = lambda e : e[1][1], reverse = True)
999 if self.depth >= self.max_depth:
1001 return list(opts[0])
1003 if self.recurse_for >= 0:
1004 opts = opts[0:self.recurse_for]
1005 #sys.stderr.write(sys.argv[0] + " : Before recurse, options are " + str(opts) + "\n")
1007 # Take the best few moves, and recurse
1008 for choice in opts[0:self.recurse_for]:
1009 [xx,yy] = [choice[0].x, choice[0].y] # Remember position
1010 [nx,ny] = choice[1][0] # Target
1011 [choice[0].x, choice[0].y] = [nx, ny] # Set position
1012 target = self.board.grid[nx][ny] # Remember piece in spot
1013 self.board.grid[xx][yy] = None # Remove piece
1014 self.board.grid[nx][ny] = choice[0] # Replace with moving piece
1017 best_enemy_move = self.select_best(opponent(choice[0].colour))
1018 choice[1][1] -= best_enemy_move[1][1] / float(self.depth + 1.0)
1020 [choice[0].x, choice[0].y] = [xx, yy] # Restore position
1021 self.board.grid[nx][ny] = target # Restore taken piece
1022 self.board.grid[xx][yy] = choice[0] # Restore moved piece
1026 opts.sort(key = lambda e : e[1][1], reverse = True)
1027 #sys.stderr.write(sys.argv[0] + " : After recurse, options are " + str(opts) + "\n")
1030 return list(opts[0])
1034 # Returns [x,y] of selected piece
1036 #sys.stderr.write("Getting choice...")
1037 self.choice = self.select_best(self.colour)[0]
1039 #sys.stderr.write(" Done " + str(self.choice)+"\n")
1040 return [self.choice.x, self.choice.y]
1042 # Returns [x,y] of square to move selected piece into
1044 #sys.stderr.write("Choice is " + str(self.choice) + "\n")
1045 self.choice.selected_moves = self.choice.last_moves
1046 moves = self.prioritise_moves(self.choice)
1050 return AgentRandom.get_move(self)
1052 # --- agent_bishop.py --- #
1053 import multiprocessing
1055 # Hacky alternative to using select for timing out players
1057 # WARNING: Do not wrap around HumanPlayer or things breakify
1058 # WARNING: Do not use in general or things breakify
1060 class Sleeper(multiprocessing.Process):
1061 def __init__(self, timeout):
1062 multiprocessing.Process.__init__(self)
1063 self.timeout = timeout
1066 time.sleep(self.timeout)
1069 class Worker(multiprocessing.Process):
1070 def __init__(self, function, args, q):
1071 multiprocessing.Process.__init__(self)
1072 self.function = function
1077 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args)
1078 self.q.put(self.function(*self.args))
1082 def TimeoutFunction(function, args, timeout):
1083 q = multiprocessing.Queue()
1084 w = Worker(function, args, q)
1085 s = Sleeper(timeout)
1088 while True: # Busy loop of crappyness
1089 if not w.is_alive():
1093 #print "TimeoutFunction gets " + str(result)
1095 elif not s.is_alive():
1098 raise Exception("TIMEOUT")
1103 # A player that wraps another player and times out its moves
1105 # A (crappy) alternative to the use of select()
1106 class TimeoutPlayer(Player):
1107 def __init__(self, base_player, timeout):
1108 Player.__init__(self, base_player.name, base_player.colour)
1109 self.base_player = base_player
1110 self.timeout = timeout
1113 return TimeoutFunction(self.base_player.select, [], self.timeout)
1117 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
1119 def update(self, result):
1120 return TimeoutFunction(self.base_player.update, [result], self.timeout)
1122 def quit(self, final_result):
1123 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
1124 # --- timeout_player.py --- #
1128 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
1129 network_timeout_delay = 1.0 # Maximum time between two characters being received
1132 def __init__(self, colour, address = None):
1133 self.socket = socket.socket()
1134 #self.socket.setblocking(0)
1136 if colour == "white":
1143 # print str(self) + " listens on port " + str(self.port)
1146 self.host = socket.gethostname()
1147 self.socket.bind((self.host, self.port))
1148 self.socket.listen(5)
1150 self.src, self.address = self.socket.accept()
1151 self.src.send("ok\n")
1152 if self.get_response() == "QUIT":
1156 self.socket.connect((address, self.port))
1157 self.src = self.socket
1158 self.src.send("ok\n")
1159 if self.get_response() == "QUIT":
1162 def get_response(self):
1163 # Timeout the start of the message (first character)
1164 if network_timeout_start > 0.0:
1165 ready = select.select([self.src], [], [], network_timeout_start)[0]
1168 if self.src in ready:
1169 s = self.src.recv(1)
1171 raise Exception("UNRESPONSIVE")
1174 while s[len(s)-1] != '\n':
1175 # Timeout on each character in the message
1176 if network_timeout_delay > 0.0:
1177 ready = select.select([self.src], [], [], network_timeout_delay)[0]
1180 if self.src in ready:
1181 s += self.src.recv(1)
1183 raise Exception("UNRESPONSIVE")
1185 return s.strip(" \r\n")
1187 def send_message(self,s):
1188 if network_timeout_start > 0.0:
1189 ready = select.select([], [self.src], [], network_timeout_start)[1]
1193 if self.src in ready:
1194 self.src.send(s + "\n")
1196 raise Exception("UNRESPONSIVE")
1198 def check_quit(self, s):
1202 game.final_result = " ".join(s[1:]) + " " + str(opponent(self.colour))
1208 class NetworkSender(Player,Network):
1209 def __init__(self, base_player, address = None):
1210 self.base_player = base_player
1211 Player.__init__(self, base_player.name, base_player.colour)
1213 self.address = address
1216 Network.__init__(self, self.base_player.colour, self.address)
1221 [x,y] = self.base_player.select()
1222 choice = self.board.grid[x][y]
1223 s = str(x) + " " + str(y)
1224 #print str(self) + ".select sends " + s
1225 self.send_message(s)
1229 [x,y] = self.base_player.get_move()
1230 s = str(x) + " " + str(y)
1231 #print str(self) + ".get_move sends " + s
1232 self.send_message(s)
1235 def update(self, s):
1236 self.base_player.update(s)
1238 [x,y] = map(int, s[0:2])
1239 selected = self.board.grid[x][y]
1240 if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
1241 s = " ".join(s[0:3])
1243 if selected.types[i][0] == '?':
1244 s += " " + str(selected.types[i])
1247 #print str(self) + ".update sends " + s
1248 self.send_message(s)
1251 def quit(self, final_result):
1252 self.base_player.quit(final_result)
1253 #self.src.send("QUIT " + str(final_result) + "\n")
1256 class NetworkReceiver(Player,Network):
1257 def __init__(self, colour, address=None):
1259 Player.__init__(self, "NetworkReceiver", colour)
1261 self.address = address
1266 Network.__init__(self, self.colour, self.address)
1271 s = self.get_response()
1272 #print str(self) + ".select gets " + s
1273 [x,y] = map(int,s.split(" "))
1274 if x == -1 and y == -1:
1275 #print str(self) + ".select quits the game"
1277 game.final_state = "network terminated " + self.colour
1281 s = self.get_response()
1282 #print str(self) + ".get_move gets " + s
1283 [x,y] = map(int,s.split(" "))
1284 if x == -1 and y == -1:
1285 #print str(self) + ".get_move quits the game"
1287 game.final_state = "network terminated " + self.colour
1291 def update(self, result):
1293 result = result.split(" ")
1294 [x,y] = map(int, result[0:2])
1295 selected = self.board.grid[x][y]
1296 if selected != None and selected.colour == self.colour and len(result) > 2 and not "->" in result:
1297 s = self.get_response()
1298 #print str(self) + ".update - receives " + str(s)
1300 selected.choice = int(s[2])
1302 selected.types[i] = str(s[3+i])
1303 if s[3+i] == "unknown":
1304 selected.types[i] = '?'+selected.types[i]
1306 selected.types[i] = selected.types[i][1:]
1307 selected.current_type = selected.types[selected.choice]
1310 #print str(self) + ".update - ignore result " + str(result)
1313 def quit(self, final_result):
1316 # --- network.py --- #
1319 # A thread that can be stopped!
1320 # Except it can only be stopped if it checks self.stopped() periodically
1321 # So it can sort of be stopped
1322 class StoppableThread(threading.Thread):
1324 threading.Thread.__init__(self)
1325 self._stop = threading.Event()
1331 return self._stop.isSet()
1332 # --- thread_util.py --- #
1338 def __init__(self, log):
1342 self.log.write("# Log starts " + str(datetime.datetime.now()) + "\n")
1345 now = datetime.datetime.now()
1346 self.log.write(str(now) + " : " + s + "\n")
1347 self.logged.append((now, s))
1349 def setup(self, board, players):
1352 self.log.write("# " + str(p.colour) + " : " + str(p.name) + "\n")
1354 self.log.write("# Initial board\n")
1355 for x in range(0, w):
1356 for y in range(0, h):
1357 if board.grid[x][y] != None:
1358 self.log.write(str(board.grid[x][y]) + "\n")
1360 self.log.write("# Start game\n")
1363 self.log.write("# EOF\n")
1364 if self.log != sys.stdout:
1367 class ShortLog(LogFile):
1368 def __init__(self, file_name):
1370 self.log = sys.stdout
1372 self.log = open(file_name, "w", 0)
1373 LogFile.__init__(self, self.log)
1374 self.file_name = file_name
1378 now = datetime.datetime.now()
1379 self.logged.append((now, s))
1382 if self.log != sys.stdout:
1384 self.log = open(self.file_name, "w", 0)
1385 self.log.write("# Short log updated " + str(datetime.datetime.now()) + "\n")
1386 LogFile.setup(self, game.board, game.players)
1388 elif self.phase == 1:
1389 for message in self.logged[len(self.logged)-2:]:
1390 self.log.write(str(message[0]) + " : " + message[1] + "\n")
1392 self.phase = (self.phase + 1) % 2
1396 ending = self.logged[len(self.logged)-1]
1397 self.log.write(str(ending[0]) + " : " + ending[1] + "\n")
1398 self.log.write("# EOF\n")
1399 if self.log != sys.stdout:
1403 class HeadRequest(urllib2.Request):
1404 def get_method(self):
1407 class HttpGetter(StoppableThread):
1408 def __init__(self, address):
1409 StoppableThread.__init__(self)
1410 self.address = address
1411 self.log = urllib2.urlopen(address)
1413 self.lock = threading.RLock() #lock for access of self.state
1414 self.cond = threading.Condition() # conditional
1417 while not self.stopped():
1418 line = self.log.readline()
1420 date_mod = datetime.datetime.strptime(self.log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1423 next_log = urllib2.urlopen(HeadRequest(self.address))
1424 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1425 while date_new <= date_mod and not self.stopped():
1426 next_log = urllib2.urlopen(HeadRequest(self.address))
1427 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1431 self.log = urllib2.urlopen(self.address)
1432 line = self.log.readline()
1435 self.lines.append(line)
1436 self.cond.notifyAll()
1439 #sys.stderr.write(" HttpGetter got \'" + str(line) + "\'\n")
1448 def __init__(self, address):
1449 self.getter = HttpGetter(address)
1453 self.getter.cond.acquire()
1454 while len(self.getter.lines) == 0:
1455 self.getter.cond.wait()
1457 result = self.getter.lines[0]
1458 self.getter.lines = self.getter.lines[1:]
1459 self.getter.cond.release()
1468 def __init__(self, filename):
1469 self.f = open(filename, "r", 0)
1470 self.filename = filename
1471 self.mod = os.path.getmtime(filename)
1475 line = self.f.readline()
1478 mod2 = os.path.getmtime(self.filename)
1480 #sys.stderr.write("File changed!\n")
1483 self.f = open(self.filename, "r", 0)
1485 new_line = self.f.readline()
1487 if " ".join(new_line.split(" ")[0:3]) != "# Short log":
1488 for i in range(self.count):
1489 new_line = self.f.readline()
1490 #sys.stderr.write("Read back " + str(i) + ": " + str(new_line) + "\n")
1491 new_line = self.f.readline()
1509 def log_init(board, players):
1511 l.setup(board, players)
1519 # A thread that runs the game
1520 class GameThread(StoppableThread):
1521 def __init__(self, board, players):
1522 StoppableThread.__init__(self)
1524 self.players = players
1525 self.state = {"turn" : None} # The game state
1526 self.error = 0 # Whether the thread exits with an error
1527 self.lock = threading.RLock() #lock for access of self.state
1528 self.cond = threading.Condition() # conditional for some reason, I forgot
1529 self.final_result = ""
1533 # Run the game (run in new thread with start(), run in current thread with run())
1536 while not self.stopped():
1538 for p in self.players:
1540 if isinstance(p, NetworkSender):
1541 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
1543 self.state["turn"] = p
1546 [x,y] = p.select() # Player selects a square
1553 result = self.board.select(x, y, colour = p.colour)
1554 for p2 in self.players:
1555 p2.update(result) # Inform players of what happened
1560 target = self.board.grid[x][y]
1561 if isinstance(graphics, GraphicsThread):
1563 graphics.state["moves"] = self.board.possible_moves(target)
1564 graphics.state["select"] = target
1566 time.sleep(turn_delay)
1569 if len(self.board.possible_moves(target)) == 0:
1570 #print "Piece cannot move"
1572 if isinstance(graphics, GraphicsThread):
1574 graphics.state["moves"] = None
1575 graphics.state["select"] = None
1576 graphics.state["dest"] = None
1580 [x2,y2] = p.get_move() # Player selects a destination
1587 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1590 self.board.update_move(x, y, x2, y2)
1592 for p2 in self.players:
1593 p2.update(result) # Inform players of what happened
1597 if isinstance(graphics, GraphicsThread):
1599 graphics.state["moves"] = [[x2,y2]]
1601 time.sleep(turn_delay)
1603 if isinstance(graphics, GraphicsThread):
1605 graphics.state["select"] = None
1606 graphics.state["dest"] = None
1607 graphics.state["moves"] = None
1609 # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
1610 # except Exception,e:
1611 # result = e.message
1612 # #sys.stderr.write(result + "\n")
1616 # self.final_result = self.state["turn"].colour + " " + e.message
1618 end = self.board.end_condition()
1622 self.final_result = self.state["turn"].colour + " " + end
1624 self.final_result = end
1631 for p2 in self.players:
1632 p2.quit(self.final_result)
1634 log(self.final_result)
1636 if isinstance(graphics, GraphicsThread):
1640 # A thread that replays a log file
1641 class ReplayThread(GameThread):
1642 def __init__(self, players, src, end=False,max_moves=None):
1643 self.board = Board(style="empty")
1644 self.board.max_moves = max_moves
1645 GameThread.__init__(self, self.board, players)
1649 self.reset_board(self.src.readline())
1651 def reset_board(self, line):
1654 while line != "# Start game" and line != "# EOF":
1657 line = self.src.readline().strip(" \r\n")
1661 line = self.src.readline().strip(" \r\n")
1664 self_str += line + "\n"
1666 if self.players[0].name == "dummy" and self.players[1].name == "dummy":
1667 line = self.src.readline().strip(" \r\n")
1670 tokens = line.split(" ")
1671 types = map(lambda e : e.strip("[] ,'"), tokens[2:4])
1672 for i in range(len(types)):
1673 if types[i][0] == "?":
1674 types[i] = "unknown"
1676 agent_str += tokens[0] + " " + tokens[1] + " " + str(types) + " ".join(tokens[4:]) + "\n"
1677 line = self.src.readline().strip(" \r\n")
1679 for p in self.players:
1680 p.reset_board(agent_str)
1683 self.board.reset_board(self_str)
1689 line = self.src.readline().strip(" \r\n")
1690 while line != "# EOF":
1702 line = self.src.readline().strip(" \r\n")
1705 tokens = line.split(" ")
1706 if tokens[0] == "white" or tokens[0] == "black":
1707 self.reset_board(line)
1709 line = self.src.readline().strip(" \r\n")
1712 move = line.split(":")
1713 move = move[len(move)-1].strip(" \r\n")
1714 tokens = move.split(" ")
1718 [x,y] = map(int, tokens[0:2])
1726 target = self.board.grid[x][y]
1728 if target.colour == "white":
1729 self.state["turn"] = self.players[0]
1731 self.state["turn"] = self.players[1]
1733 move_piece = (tokens[2] == "->")
1735 [x2,y2] = map(int, tokens[len(tokens)-2:])
1737 if isinstance(graphics, GraphicsThread):
1739 graphics.state["select"] = target
1742 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
1743 if isinstance(graphics, GraphicsThread):
1745 if target.current_type != "unknown":
1746 graphics.state["moves"] = self.board.possible_moves(target)
1748 graphics.state["moves"] = None
1749 time.sleep(turn_delay)
1751 self.board.update_move(x, y, x2, y2)
1752 if isinstance(graphics, GraphicsThread):
1754 graphics.state["moves"] = [[x2,y2]]
1755 time.sleep(turn_delay)
1757 graphics.state["select"] = None
1758 graphics.state["moves"] = None
1759 graphics.state["dest"] = None
1765 for p in self.players:
1769 line = self.src.readline().strip(" \r\n")
1772 end = self.board.end_condition()
1774 self.final_result = end
1792 if self.end and isinstance(graphics, GraphicsThread):
1794 pass # Let the user stop the display
1795 elif not self.end and self.board.end_condition() == None:
1797 # Work out the last move
1799 t = last_line.split(" ")
1800 if t[len(t)-2] == "black":
1801 self.players.reverse()
1802 elif t[len(t)-2] == "white":
1804 elif self.state["turn"] != None and self.state["turn"].colour == "white":
1805 self.players.reverse()
1808 game = GameThread(self.board, self.players)
1815 def opponent(colour):
1816 if colour == "white":
1827 # Dictionary that stores the unicode character representations of the different pieces
1828 # Chess was clearly the reason why unicode was invented
1829 # For some reason none of the pygame chess implementations I found used them!
1830 piece_char = {"white" : {"king" : u'\u2654',
1831 "queen" : u'\u2655',
1833 "bishop" : u'\u2657',
1834 "knight" : u'\u2658',
1837 "black" : {"king" : u'\u265A',
1838 "queen" : u'\u265B',
1840 "bishop" : u'\u265D',
1841 "knight" : u'\u265E',
1845 images = {"white" : {}, "black" : {}}
1846 small_images = {"white" : {}, "black" : {}}
1848 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
1850 # Get the font sizes
1851 l_size = 5*(grid_sz[0] / 8)
1852 s_size = 3*(grid_sz[0] / 8)
1854 for c in piece_char.keys():
1857 for p in piece_char[c].keys():
1858 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
1859 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})
1861 for p in piece_char[c].keys():
1862 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1863 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1864 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1865 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1868 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
1869 if not os.path.exists(image_dir):
1870 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
1871 for c in piece_char.keys():
1872 for p in piece_char[c].keys():
1873 images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
1874 small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
1875 # --- images.py --- #
1876 graphics_enabled = True
1880 os.environ["SDL_VIDEO_ALLOW_SCREENSAVER"] = "1"
1882 graphics_enabled = False
1888 # A thread to make things pretty
1889 class GraphicsThread(StoppableThread):
1890 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1891 StoppableThread.__init__(self)
1895 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1896 pygame.display.set_caption(title)
1898 #print "Initialised properly"
1900 self.grid_sz = grid_sz[:]
1901 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
1903 self.lock = threading.RLock()
1904 self.cond = threading.Condition()
1905 self.sleep_timeout = None
1906 self.last_event = time.time()
1909 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
1912 create_images(grid_sz)
1915 for c in images.keys():
1916 for p in images[c].keys():
1917 images[c][p] = images[c][p].convert(self.window)
1918 small_images[c][p] = small_images[c][p].convert(self.window)
1925 # On the run from the world
1928 while not self.stopped():
1930 if self.sleep_timeout == None or (time.time() - self.last_event) < self.sleep_timeout:
1932 #print "Display grid"
1933 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
1935 #print "Display overlay"
1938 #print "Display pieces"
1939 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
1942 self.window.fill((0,0,0))
1944 pygame.display.flip()
1946 for event in pygame.event.get():
1947 self.last_event = time.time()
1948 if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_q):
1949 if isinstance(game, GameThread):
1951 game.final_result = ""
1952 if game.state["turn"] != None:
1953 game.final_result = game.state["turn"].colour + " "
1954 game.final_result += "terminated"
1958 elif event.type == pygame.MOUSEBUTTONDOWN:
1959 self.mouse_down(event)
1961 elif event.type == pygame.MOUSEBUTTONUP:
1962 self.mouse_up(event)
1971 self.message("Game ends, result \""+str(game.final_result) + "\"")
1974 # Wake up anyone who is sleeping
1979 pygame.quit() # Time to say goodbye
1981 # Mouse release event handler
1982 def mouse_up(self, event):
1983 if event.button == 3:
1985 self.state["overlay"] = None
1986 elif event.button == 2:
1988 self.state["coverage"] = None
1990 # Mouse click event handler
1991 def mouse_down(self, event):
1992 if event.button == 1:
1993 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
1994 if isinstance(game, GameThread):
1996 p = game.state["turn"]
2001 if isinstance(p, HumanPlayer):
2003 s = self.board.grid[m[0]][m[1]]
2004 select = self.state["select"]
2006 if s != None and s.colour != p.colour:
2007 self.message("Wrong colour") # Look at all this user friendliness!
2010 # Notify human player of move
2013 self.state["select"] = s
2014 self.state["dest"] = None
2023 if self.state["moves"] == None:
2026 if not m in self.state["moves"]:
2027 self.message("Illegal Move") # I still think last year's mouse interface was adequate
2032 if self.state["dest"] == None:
2034 self.state["dest"] = m
2035 self.state["select"] = None
2036 self.state["moves"] = None
2039 elif event.button == 3:
2040 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2041 if isinstance(game, GameThread):
2043 p = game.state["turn"]
2048 if isinstance(p, HumanPlayer):
2050 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
2052 elif event.button == 2:
2053 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2054 if isinstance(game, GameThread):
2056 p = game.state["turn"]
2061 if isinstance(p, HumanPlayer):
2063 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
2068 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
2069 # Draw square over the selected piece
2071 select = self.state["select"]
2073 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
2074 square_img.fill(pygame.Color(0,255,0,64))
2075 self.window.blit(square_img, mp)
2076 # If a piece is selected, draw all reachable squares
2077 # (This quality user interface has been patented)
2079 m = self.state["moves"]
2081 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
2083 mp = [self.grid_sz[i] * move[i] for i in range(2)]
2084 self.window.blit(square_img, mp)
2085 # If a piece is overlayed, show all squares that it has a probability to reach
2087 m = self.state["overlay"]
2092 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
2093 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
2094 self.window.blit(square_img, mp)
2095 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2096 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
2097 self.window.blit(text, mp)
2099 # If a square is selected, highlight all pieces that have a probability to reach it
2101 m = self.state["coverage"]
2104 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
2105 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
2106 self.window.blit(square_img, mp)
2107 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2108 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
2109 self.window.blit(text, mp)
2110 # Draw a square where the mouse is
2111 # This also serves to indicate who's turn it is
2113 if isinstance(game, GameThread):
2115 turn = game.state["turn"]
2119 if isinstance(turn, HumanPlayer):
2120 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
2121 square_img.fill(pygame.Color(0,0,255,128))
2122 if turn.colour == "white":
2123 c = pygame.Color(255,255,255)
2125 c = pygame.Color(0,0,0)
2126 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
2127 self.window.blit(square_img, mp)
2129 # Message in a bottle
2130 def message(self, string, pos = None, colour = None, font_size = 20):
2131 #print "Drawing message..."
2132 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2134 colour = pygame.Color(0,0,0)
2136 text = font.render(string, 1, colour)
2139 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
2140 s.fill(pygame.Color(128,128,128))
2142 tmp = self.window.get_size()
2145 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
2147 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
2150 rect = (pos[0], pos[1], text.get_width(), text.get_height())
2152 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
2153 self.window.blit(s, pos)
2154 self.window.blit(text, pos)
2156 pygame.display.flip()
2158 def getstr(self, prompt = None):
2159 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
2160 s.blit(self.window, (0,0))
2166 self.message(prompt)
2167 self.message(result, pos = (0, 1))
2170 for event in pygame.event.get():
2171 if event.type == pygame.QUIT:
2173 if event.type == pygame.KEYDOWN:
2174 if event.key == pygame.K_BACKSPACE:
2175 result = result[0:len(result)-1]
2176 self.window.blit(s, (0,0)) # Revert the display
2181 if event.unicode == '\r':
2184 result += str(event.unicode)
2189 # Function to pick a button
2190 def SelectButton(self, choices, prompt = None, font_size=20):
2192 #print "Select button called!"
2193 self.board.display_grid(self.window, self.grid_sz)
2195 self.message(prompt)
2196 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2198 sz = self.window.get_size()
2201 for i in range(len(choices)):
2204 text = font.render(c, 1, pygame.Color(0,0,0))
2205 p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
2206 targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
2209 mp =pygame.mouse.get_pos()
2210 for i in range(len(choices)):
2212 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
2213 font_colour = pygame.Color(255,0,0)
2214 box_colour = pygame.Color(0,0,255,128)
2216 font_colour = pygame.Color(0,0,0)
2217 box_colour = pygame.Color(128,128,128)
2219 text = font.render(c, 1, font_colour)
2220 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
2222 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
2223 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
2224 self.window.blit(s, targets[i][0:2])
2227 pygame.display.flip()
2229 for event in pygame.event.get():
2230 if event.type == pygame.QUIT:
2232 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
2233 for i in range(len(targets)):
2235 if event.pos[0] > t[0] and event.pos[0] < t[2]:
2236 if event.pos[1] > t[1] and event.pos[1] < t[3]:
2238 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
2241 # Function to pick players in a nice GUI way
2242 def SelectPlayers(self, players = []):
2245 #print "SelectPlayers called"
2247 missing = ["white", "black"]
2249 missing.remove(p.colour)
2251 for colour in missing:
2254 choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
2256 players.append(HumanPlayer("human", colour))
2259 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2260 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2261 internal_agents.remove(('InternalAgent', InternalAgent))
2262 if len(internal_agents) > 0:
2263 choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
2268 agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
2269 players.append(agent[1](agent[0], colour))
2273 from tkFileDialog import askopenfilename
2274 root = Tkinter.Tk() # Need a root to make Tkinter behave
2275 root.withdraw() # Some sort of magic incantation
2276 path = askopenfilename(parent=root, initialdir="../agents",title=
2279 return self.SelectPlayers()
2280 players.append(make_player(path, colour))
2285 self.board.display_grid(self.window, self.grid_sz)
2286 pygame.display.flip()
2287 path = self.getstr(prompt = "Enter path:")
2292 return self.SelectPlayers()
2295 p = make_player(path, colour)
2297 self.board.display_grid(self.window, self.grid_sz)
2298 pygame.display.flip()
2299 self.message("Invalid path!")
2305 while address == "":
2306 self.board.display_grid(self.window, self.grid_sz)
2308 address = self.getstr(prompt = "Address? (leave blank for server)")
2315 map(int, address.split("."))
2317 self.board.display_grid(self.window, self.grid_sz)
2318 self.message("Invalid IPv4 address!")
2321 players.append(NetworkReceiver(colour, address))
2324 #print str(self) + ".SelectPlayers returns " + str(players)
2329 # --- graphics.py --- #
2330 #!/usr/bin/python -u
2332 # Do you know what the -u does? It unbuffers stdin and stdout
2333 # I can't remember why, but last year things broke without that
2336 UCC::Progcomp 2013 Quantum Chess game
2337 @author Sam Moore [SZM] "matches"
2338 @copyright The University Computer Club, Incorporated
2339 (ie: You can copy it for not for profit purposes)
2342 # system python modules or whatever they are called
2348 sleep_timeout = None
2349 [game, graphics] = [None, None]
2351 def make_player(name, colour):
2353 if name[1:] == "human":
2354 return HumanPlayer(name, colour)
2355 s = name[1:].split(":")
2356 if s[0] == "network":
2360 return NetworkReceiver(colour, address)
2361 if s[0] == "internal":
2364 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2365 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2366 internal_agents.remove(('InternalAgent', InternalAgent))
2369 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
2370 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2373 for a in internal_agents:
2375 return a[1](name, colour)
2377 sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
2378 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2383 return ExternalAgent(name, colour)
2387 # The main function! It does the main stuff!
2390 # Apparently python will silently treat things as local unless you do this
2391 # Anyone who says "You should never use a global variable" can die in a fire
2396 global agent_timeout
2399 global graphics_enabled
2400 global always_reveal_states
2401 global sleep_timeout
2409 # Get the important warnings out of the way
2410 if platform.system() == "Windows":
2411 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
2412 if platform.release() == "Vista":
2413 sys.stderr.write(sys.argv[0] + " : God help you.\n")
2418 while i < len(argv)-1:
2422 p = make_player(arg, colour)
2423 if not isinstance(p, Player):
2424 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
2427 if colour == "white":
2429 elif colour == "black":
2432 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
2435 # Option parsing goes here
2436 if arg[1] == '-' and arg[2:] == "classical":
2438 elif arg[1] == '-' and arg[2:] == "quantum":
2440 elif arg[1] == '-' and arg[2:] == "reveal":
2441 always_reveal_states = True
2442 elif (arg[1] == '-' and arg[2:] == "graphics"):
2443 graphics_enabled = True
2444 elif (arg[1] == '-' and arg[2:] == "no-graphics"):
2445 graphics_enabled = False
2446 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
2447 # Load game from file
2448 if len(arg[2:].split("=")) == 1:
2449 src_file = sys.stdin
2451 f = arg[2:].split("=")[1]
2452 if f[0:7] == "http://":
2453 src_file = HttpReplay(f)
2455 src_file = FileReplay(f.split(":")[0])
2457 if len(f.split(":")) == 2:
2458 max_moves = int(f.split(":")[1])
2460 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
2462 if len(arg[2:].split("=")) == 1:
2463 log_files.append(LogFile(sys.stdout))
2465 f = arg[2:].split("=")[1]
2467 log_files.append(ShortLog(f[1:]))
2469 log_files.append(LogFile(open(f, "w", 0)))
2470 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
2472 if len(arg[2:].split("=")) == 1:
2475 turn_delay = float(arg[2:].split("=")[1])
2477 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
2479 if len(arg[2:].split("=")) == 1:
2482 agent_timeout = float(arg[2:].split("=")[1])
2483 elif (arg[1] == '-' and arg[2:].split("=")[0] == "blackout"):
2484 # Screen saver delay
2485 if len(arg[2:].split("=")) == 1:
2488 sleep_timeout = float(arg[2:].split("=")[1])
2490 elif (arg[1] == '-' and arg[2:] == "help"):
2492 os.system("less data/help.txt") # The best help function
2498 # Construct a GameThread! Make it global! Damn the consequences!
2500 if src_file != None:
2501 # Hack to stop ReplayThread from exiting
2502 #if len(players) == 0:
2503 # players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
2505 # Normally the ReplayThread exits if there are no players
2506 # TODO: Decide which behaviour to use, and fix it
2507 end = (len(players) == 0)
2509 players = [Player("dummy", "white"), Player("dummy", "black")]
2510 elif len(players) != 2:
2511 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2512 if graphics_enabled:
2513 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
2515 game = ReplayThread(players, src_file, end=end, max_moves=max_moves)
2517 board = Board(style)
2518 board.max_moves = max_moves
2519 game = GameThread(board, players)
2525 if graphics_enabled == True:
2527 graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
2529 graphics.sleep_timeout = sleep_timeout
2533 sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
2534 graphics_enabled = False
2536 # If there are no players listed, display a nice pretty menu
2537 if len(players) != 2:
2538 if graphics != None:
2539 players = graphics.SelectPlayers(players)
2541 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2544 # If there are still no players, quit
2545 if players == None or len(players) != 2:
2546 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
2550 # Wrap NetworkSender players around original players if necessary
2551 for i in range(len(players)):
2552 if isinstance(players[i], NetworkReceiver):
2553 players[i].board = board # Network players need direct access to the board
2554 for j in range(len(players)):
2557 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
2559 players[j] = NetworkSender(players[j], players[i].address)
2560 players[j].board = board
2562 # Connect the networked players
2564 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
2565 if graphics != None:
2566 graphics.board.display_grid(graphics.window, graphics.grid_sz)
2567 graphics.message("Connecting to " + p.colour + " player...")
2571 # If using windows, select won't work; use horrible TimeoutPlayer hack
2572 if agent_timeout > 0:
2573 if platform.system() == "Windows":
2574 for i in range(len(players)):
2575 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
2576 players[i] = TimeoutPlayer(players[i], agent_timeout)
2580 # InternalAgents get wrapped to an ExternalAgent when there is a timeout
2581 # This is not confusing at all.
2582 for i in range(len(players)):
2583 if isinstance(players[i], InternalAgent):
2584 players[i] = ExternalWrapper(players[i])
2592 log_init(game.board, players)
2595 if graphics != None:
2596 game.start() # This runs in a new thread
2602 error = game.error + graphics.error
2611 if src_file != None and src_file != sys.stdin:
2614 sys.stdout.write(game.final_result + "\n")
2618 # This is how python does a main() function...
2619 if __name__ == "__main__":
2621 sys.exit(main(sys.argv))
2622 except KeyboardInterrupt:
2623 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
2624 if isinstance(graphics, StoppableThread):
2626 graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
2628 if isinstance(game, StoppableThread):
2636 # EOF - created from make on Wed Mar 27 13:05:44 WST 2013