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, sanity=True):
276 piece = self.grid[x][y]
277 if piece.types[type_index] == "unknown":
278 if not state in self.unrevealed_types[piece.colour].keys() and sanity == True:
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, sanity=True):
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) and sanity == True:
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, sanity=True):
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]
344 if piece == None and sanity == True:
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, sanity)
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
369 self.update_select(x, y, type_index, state, sanity)
373 # Gets each piece that could reach the given square and the probability that it could reach that square
374 # Will include allied pieces that defend the attacker
375 def coverage(self, x, y, colour = None, reject_allied = True):
379 pieces = self.pieces["white"] + self.pieces["black"]
381 pieces = self.pieces[colour]
384 prob = self.probability_grid(p, reject_allied)[x][y]
386 result.update({p : prob})
395 # Associates each square with a probability that the piece could move into it
396 # Look, I'm doing all the hard work for you here...
397 def probability_grid(self, p, reject_allied = True):
399 result = [[0.0] * w for _ in range(h)]
400 if not isinstance(p, Piece):
403 if p.current_type != "unknown":
404 #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
405 for point in self.possible_moves(p, reject_allied):
406 result[point[0]][point[1]] = 1.0
410 for i in range(len(p.types)):
412 prob = 1.0 / float(len(p.types))
413 if t == "unknown" or p.types[i][0] == '?':
415 for t2 in self.unrevealed_types[p.colour].keys():
416 total_types += self.unrevealed_types[p.colour][t2]
418 for t2 in self.unrevealed_types[p.colour].keys():
419 prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
421 for point in self.possible_moves(p, reject_allied, state=t2):
422 result[point[0]][point[1]] += prob2 * prob
426 for point in self.possible_moves(p, reject_allied, state=t):
427 result[point[0]][point[1]] += prob
430 #p.current_type = "unknown"
433 def prob_is_type(self, p, state):
436 for i in range(len(p.types)):
441 if t == "unknown" or p.types[i][0] == '?':
443 for t2 in self.unrevealed_types[p.colour].keys():
444 total_prob += self.unrevealed_types[p.colour][t2]
445 for t2 in self.unrevealed_types[p.colour].keys():
447 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
451 # Get all squares that the piece could move into
452 # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
453 # reject_allied indicates whether squares occupied by allied pieces will be removed
454 # (set to false to check for defense)
455 def possible_moves(self, p, reject_allied = True, state=None):
457 raise Exception("SANITY: No piece")
461 if state != None and state != p.current_type:
462 old_type = p.current_type
463 p.current_type = state
464 result = self.possible_moves(p, reject_allied, state=None)
465 p.current_type = old_type
475 if p.current_type == "unknown":
476 raise Exception("SANITY: Piece state unknown")
477 # The below commented out code causes things to break badly
482 # result += self.possible_moves(p)
483 #p.current_type = "unknown"
486 if p.current_type == "king":
487 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]]
488 elif p.current_type == "queen":
489 for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
490 result += self.scan(p.x, p.y, d[0], d[1])
491 elif p.current_type == "bishop":
492 for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
493 result += self.scan(p.x, p.y, d[0], d[1])
494 elif p.current_type == "rook":
495 for d in [[-1,0],[1,0],[0,-1],[0,1]]:
496 result += self.scan(p.x, p.y, d[0], d[1])
497 elif p.current_type == "knight":
498 # I would use two lines, but I'm not sure how python likes that
499 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]]
500 elif p.current_type == "pawn":
501 if p.colour == "white":
503 # Pawn can't move forward into occupied square
504 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
505 result = [[p.x,p.y-1]]
506 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
507 if not self.on_board(f[0], f[1]):
509 if self.grid[f[0]][f[1]] != None: # Pawn can take diagonally
512 # Slightly embarrassing if the pawn jumps over someone on its first move...
513 if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
514 result.append([p.x, p.y-2])
516 # Vice versa for the black pawn
517 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
518 result = [[p.x,p.y+1]]
520 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
521 if not self.on_board(f[0], f[1]):
523 if self.grid[f[0]][f[1]] != None:
524 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
527 if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
528 result.append([p.x, p.y+2])
530 #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
532 # Remove illegal moves
533 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
534 for point in result[:]:
536 if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
537 result.remove(point) # Remove locations outside the board
539 g = self.grid[point[0]][point[1]]
541 if g != None and (g.colour == p.colour and reject_allied == True):
542 result.remove(point) # Remove allied pieces
546 p.possible_moves = result
550 # Scans in a direction until it hits a piece, returns all squares in the line
551 # (includes the final square (which contains a piece), but not the original square)
552 def scan(self, x, y, vx, vy):
560 if not self.on_board(xx, yy):
564 g = self.grid[xx][yy]
570 # Returns "white", "black" or "DRAW" if the game should end
571 def end_condition(self):
572 if self.king["white"] == None:
573 if self.king["black"] == None:
574 return "DRAW" # This shouldn't happen
576 elif self.king["black"] == None:
578 elif len(self.pieces["white"]) == 1 and len(self.pieces["black"]) == 1:
580 elif self.max_moves != None and self.moves > self.max_moves:
585 # I typed the full statement about 30 times before writing this function...
586 def on_board(self, x, y):
587 return (x >= 0 and x < w) and (y >= 0 and y < h)
589 # Pushes a move temporarily
590 def push_move(self, piece, x, y):
591 target = self.grid[x][y]
592 self.move_stack.append([piece, target, piece.x, piece.y, x, y])
593 [piece.x, piece.y] = [x, y]
594 self.grid[x][y] = piece
595 self.grid[piece.x][piece.y] = None
597 for p in self.pieces["white"] + self.pieces["black"]:
598 p.possible_moves = None
602 #print str(self.move_stack)
603 [piece, target, x1, y1, x2, y2] = self.move_stack[len(self.move_stack)-1]
604 self.move_stack = self.move_stack[:-1]
607 self.grid[x1][y1] = piece
611 self.grid[x2][y2] = target
613 for p in self.pieces["white"] + self.pieces["black"]:
614 p.possible_moves = None
622 agent_timeout = -1.0 # Timeout in seconds for AI players to make moves
623 # WARNING: Won't work for windows based operating systems
625 if platform.system() == "Windows":
626 agent_timeout = -1 # Hence this
628 # A player who can't play
630 def __init__(self, name, colour):
634 def update(self, result):
637 def reset_board(self, s):
640 # Player that runs from another process
641 class ExternalAgent(Player):
644 def __init__(self, name, colour):
645 Player.__init__(self, name, colour)
646 self.p = subprocess.Popen(name,bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,universal_newlines=True)
648 self.send_message(colour)
650 def send_message(self, s):
651 if agent_timeout > 0.0:
652 ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
654 ready = [self.p.stdin]
655 if self.p.stdin in ready:
656 #sys.stderr.write("Writing \'" + s + "\' to " + str(self.p) + "\n")
658 self.p.stdin.write(s + "\n")
660 raise Exception("UNRESPONSIVE")
662 raise Exception("TIMEOUT")
664 def get_response(self):
665 if agent_timeout > 0.0:
666 ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
668 ready = [self.p.stdout]
669 if self.p.stdout in ready:
670 #sys.stderr.write("Reading from " + str(self.p) + " 's stdout...\n")
672 result = self.p.stdout.readline().strip(" \t\r\n")
673 #sys.stderr.write("Read \'" + result + "\' from " + str(self.p) + "\n")
675 except: # Exception, e:
676 raise Exception("UNRESPONSIVE")
678 raise Exception("TIMEOUT")
682 self.send_message("SELECTION?")
683 line = self.get_response()
686 m = re.match("\s*(\d+)\s+(\d+)\s*", line)
687 result = map(int, [m.group(1), m.group(2)])
689 raise Exception("GIBBERISH \"" + str(line) + "\"")
692 def update(self, result):
693 #print "Update " + str(result) + " called for AgentPlayer"
694 self.send_message(result)
699 self.send_message("MOVE?")
700 line = self.get_response()
703 m = re.match("\s*(\d+)\s+(\d+)\s*", line)
704 result = map(int, [m.group(1), m.group(2)])
707 raise Exception("GIBBERISH \"" + str(line) + "\"")
710 def reset_board(self, s):
711 self.send_message("BOARD")
712 for line in s.split("\n"):
713 self.send_message(line.strip(" \r\n"))
714 self.send_message("END BOARD")
716 def quit(self, final_result):
718 self.send_message("QUIT " + final_result)
722 # So you want to be a player here?
723 class HumanPlayer(Player):
724 def __init__(self, name, colour):
725 Player.__init__(self, name, colour)
727 # Select your preferred account
729 if isinstance(graphics, GraphicsThread):
730 # Basically, we let the graphics thread do some shit and then return that information to the game thread
731 graphics.cond.acquire()
732 # We wait for the graphics thread to select a piece
733 while graphics.stopped() == False and graphics.state["select"] == None:
734 graphics.cond.wait() # The difference between humans and machines is that humans sleep
735 select = graphics.state["select"]
738 graphics.cond.release()
739 if graphics.stopped():
741 return [select.x, select.y]
743 # Since I don't display the board in this case, I'm not sure why I filled it in...
745 sys.stdout.write("SELECTION?\n")
747 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
749 sys.stderr.write("ILLEGAL GIBBERISH\n")
751 # It's your move captain
753 if isinstance(graphics, GraphicsThread):
754 graphics.cond.acquire()
755 while graphics.stopped() == False and graphics.state["dest"] == None:
757 graphics.cond.release()
759 return graphics.state["dest"]
763 sys.stdout.write("MOVE?\n")
765 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
767 sys.stderr.write("ILLEGAL GIBBERISH\n")
770 # Are you sure you want to quit?
771 def quit(self, final_result):
773 sys.stdout.write("QUIT " + final_result + "\n")
775 # Completely useless function
776 def update(self, result):
777 if isinstance(graphics, GraphicsThread):
780 sys.stdout.write(result + "\n")
784 # Default internal player (makes random moves)
785 class InternalAgent(Player):
786 def __init__(self, name, colour):
787 Player.__init__(self, name, colour)
790 self.board = Board(style = "agent")
794 def update(self, result):
796 self.board.update(result)
800 def reset_board(self, s):
801 self.board.reset_board(s)
803 def quit(self, final_result):
806 class AgentRandom(InternalAgent):
807 def __init__(self, name, colour):
808 InternalAgent.__init__(self, name, colour)
812 self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
814 # Check that the piece has some possibility to move
815 tmp = self.choice.current_type
816 if tmp == "unknown": # For unknown pieces, try both types
817 for t in self.choice.types:
820 self.choice.current_type = t
821 all_moves += self.board.possible_moves(self.choice)
823 all_moves = self.board.possible_moves(self.choice)
824 self.choice.current_type = tmp
825 if len(all_moves) > 0:
827 return [self.choice.x, self.choice.y]
830 moves = self.board.possible_moves(self.choice)
831 move = moves[random.randint(0, len(moves)-1)]
835 # Terrible, terrible hacks
837 def run_agent(agent):
838 #sys.stderr.write(sys.argv[0] + " : Running agent " + str(agent) + "\n")
840 line = sys.stdin.readline().strip(" \r\n")
841 if line == "SELECTION?":
842 #sys.stderr.write(sys.argv[0] + " : Make selection\n")
843 [x,y] = agent.select() # Gets your agent's selection
844 #sys.stderr.write(sys.argv[0] + " : Selection was " + str(agent.choice) + "\n")
845 sys.stdout.write(str(x) + " " + str(y) + "\n")
846 elif line == "MOVE?":
847 #sys.stderr.write(sys.argv[0] + " : Make move\n")
848 [x,y] = agent.get_move() # Gets your agent's move
849 sys.stdout.write(str(x) + " " + str(y) + "\n")
850 elif line.split(" ")[0] == "QUIT":
851 #sys.stderr.write(sys.argv[0] + " : Quitting\n")
852 agent.quit(" ".join(line.split(" ")[1:])) # Quits the game
854 elif line.split(" ")[0] == "BOARD":
856 line = sys.stdin.readline().strip(" \r\n")
857 while line != "END BOARD":
859 line = sys.stdin.readline().strip(" \r\n")
860 agent.board.reset_board(s)
863 agent.update(line) # Updates agent.board
869 class ExternalWrapper(ExternalAgent):
870 def __init__(self, agent):
871 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))\""
873 ExternalAgent.__init__(self, run, agent.colour)
877 # --- player.py --- #
881 class AgentBishop(AgentRandom): # Inherits from AgentRandom (in qchess)
882 def __init__(self, name, colour):
883 InternalAgent.__init__(self, name, colour)
884 self.value = {"pawn" : 1, "bishop" : 3, "knight" : 3, "rook" : 5, "queen" : 9, "king" : 100, "unknown" : 4}
886 self.aggression = 2.0 # Multiplier for scoring due to aggressive actions
887 self.defence = 1.0 # Multiplier for scoring due to defensive actions
889 self.depth = 0 # Current depth
890 self.max_depth = 2 # Recurse this many times (for some reason, makes more mistakes when this is increased???)
891 self.recurse_for = -1 # Recurse for the best few moves each times (less than 0 = all moves)
893 for p in self.board.pieces["white"] + self.board.pieces["black"]:
895 p.selected_moves = None
899 def get_value(self, piece):
902 return float(self.value[piece.types[0]] + self.value[piece.types[1]]) / 2.0
904 # Score possible moves for the piece
906 def prioritise_moves(self, piece):
908 #sys.stderr.write(sys.argv[0] + " : " + str(self) + " prioritise called for " + str(piece) + "\n")
912 grid = self.board.probability_grid(piece)
913 #sys.stderr.write("\t Probability grid " + str(grid) + "\n")
917 if grid[x][y] < 0.3: # Throw out moves with < 30% probability
918 #sys.stderr.write("\tReject " + str(x) + "," + str(y) + " (" + str(grid[x][y]) + ")\n")
921 target = self.board.grid[x][y]
926 # Get total probability that the move is protected
927 self.board.push_move(piece, x, y)
931 defenders = self.board.coverage(x, y, piece.colour, reject_allied = False)
933 for d in defenders.keys():
934 d_prob += defenders[d]
935 if len(defenders.keys()) > 0:
936 d_prob /= float(len(defenders.keys()))
941 # Get total probability that the move is threatened
942 attackers = self.board.coverage(x, y, opponent(piece.colour), reject_allied = False)
944 for a in attackers.keys():
945 a_prob += attackers[a]
946 if len(attackers.keys()) > 0:
947 a_prob /= float(len(attackers.keys()))
952 self.board.pop_move()
957 value = self.aggression * (1.0 + d_prob) * self.get_value(target) - self.defence * (1.0 - d_prob) * a_prob * self.get_value(piece)
959 # Adjust score based on movement of piece out of danger
960 attackers = self.board.coverage(piece.x, piece.y, opponent(piece.colour))
962 for a in attackers.keys():
963 s_prob += attackers[a]
964 if len(attackers.keys()) > 0:
965 s_prob /= float(len(attackers.keys()))
969 value += self.defence * s_prob * self.get_value(piece)
971 # Adjust score based on probability that the move is actually possible
972 moves.append([[x, y], grid[x][y] * value])
974 moves.sort(key = lambda e : e[1], reverse = True)
975 #sys.stderr.write(sys.argv[0] + ": Moves for " + str(piece) + " are " + str(moves) + "\n")
977 piece.last_moves = moves
978 piece.selected_moves = None
985 def select_best(self, colour):
989 for p in self.board.pieces[colour]:
990 self.choice = p # Temporarily pick that piece
991 m = self.prioritise_moves(p)
993 all_moves.update({p : m[0]})
995 if len(all_moves.items()) <= 0:
999 opts = all_moves.items()
1000 opts.sort(key = lambda e : e[1][1], reverse = True)
1002 if self.depth >= self.max_depth:
1004 return list(opts[0])
1006 if self.recurse_for >= 0:
1007 opts = opts[0:self.recurse_for]
1008 #sys.stderr.write(sys.argv[0] + " : Before recurse, options are " + str(opts) + "\n")
1010 # Take the best few moves, and recurse
1011 for choice in opts[0:self.recurse_for]:
1012 [xx,yy] = [choice[0].x, choice[0].y] # Remember position
1013 [nx,ny] = choice[1][0] # Target
1014 [choice[0].x, choice[0].y] = [nx, ny] # Set position
1015 target = self.board.grid[nx][ny] # Remember piece in spot
1016 self.board.grid[xx][yy] = None # Remove piece
1017 self.board.grid[nx][ny] = choice[0] # Replace with moving piece
1020 best_enemy_move = self.select_best(opponent(choice[0].colour))
1021 choice[1][1] -= best_enemy_move[1][1] / float(self.depth + 1.0)
1023 [choice[0].x, choice[0].y] = [xx, yy] # Restore position
1024 self.board.grid[nx][ny] = target # Restore taken piece
1025 self.board.grid[xx][yy] = choice[0] # Restore moved piece
1029 opts.sort(key = lambda e : e[1][1], reverse = True)
1030 #sys.stderr.write(sys.argv[0] + " : After recurse, options are " + str(opts) + "\n")
1033 return list(opts[0])
1037 # Returns [x,y] of selected piece
1039 #sys.stderr.write("Getting choice...")
1040 self.choice = self.select_best(self.colour)[0]
1042 #sys.stderr.write(" Done " + str(self.choice)+"\n")
1043 return [self.choice.x, self.choice.y]
1045 # Returns [x,y] of square to move selected piece into
1047 #sys.stderr.write("Choice is " + str(self.choice) + "\n")
1048 self.choice.selected_moves = self.choice.last_moves
1049 moves = self.prioritise_moves(self.choice)
1053 return AgentRandom.get_move(self)
1055 # --- agent_bishop.py --- #
1056 import multiprocessing
1058 # Hacky alternative to using select for timing out players
1060 # WARNING: Do not wrap around HumanPlayer or things breakify
1061 # WARNING: Do not use in general or things breakify
1063 class Sleeper(multiprocessing.Process):
1064 def __init__(self, timeout):
1065 multiprocessing.Process.__init__(self)
1066 self.timeout = timeout
1069 time.sleep(self.timeout)
1072 class Worker(multiprocessing.Process):
1073 def __init__(self, function, args, q):
1074 multiprocessing.Process.__init__(self)
1075 self.function = function
1080 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args)
1081 self.q.put(self.function(*self.args))
1085 def TimeoutFunction(function, args, timeout):
1086 q = multiprocessing.Queue()
1087 w = Worker(function, args, q)
1088 s = Sleeper(timeout)
1091 while True: # Busy loop of crappyness
1092 if not w.is_alive():
1096 #print "TimeoutFunction gets " + str(result)
1098 elif not s.is_alive():
1101 raise Exception("TIMEOUT")
1106 # A player that wraps another player and times out its moves
1108 # A (crappy) alternative to the use of select()
1109 class TimeoutPlayer(Player):
1110 def __init__(self, base_player, timeout):
1111 Player.__init__(self, base_player.name, base_player.colour)
1112 self.base_player = base_player
1113 self.timeout = timeout
1116 return TimeoutFunction(self.base_player.select, [], self.timeout)
1120 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
1122 def update(self, result):
1123 return TimeoutFunction(self.base_player.update, [result], self.timeout)
1125 def quit(self, final_result):
1126 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
1127 # --- timeout_player.py --- #
1131 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
1132 network_timeout_delay = 1.0 # Maximum time between two characters being received
1135 def __init__(self, colour, address = None):
1136 self.socket = socket.socket()
1137 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1138 #self.socket.setblocking(0)
1140 self.server = (address == None)
1142 if colour == "white":
1149 # print str(self) + " listens on port " + str(self.port)
1152 self.host = "0.0.0.0" #socket.gethostname() # Breaks things???
1153 self.socket.bind((self.host, self.port))
1154 self.socket.listen(5)
1156 self.src, self.address = self.socket.accept()
1157 self.src.send("ok\n")
1158 if self.get_response() == "QUIT":
1162 self.socket.connect((address, self.port))
1163 self.src = self.socket
1164 self.src.send("ok\n")
1165 if self.get_response() == "QUIT":
1167 self.address = (address, self.port)
1169 def get_response(self):
1170 # Timeout the start of the message (first character)
1171 if network_timeout_start > 0.0:
1172 ready = select.select([self.src], [], [], network_timeout_start)[0]
1175 if self.src in ready:
1176 s = self.src.recv(1)
1178 raise Exception("UNRESPONSIVE")
1181 while s[len(s)-1] != '\n':
1182 # Timeout on each character in the message
1183 if network_timeout_delay > 0.0:
1184 ready = select.select([self.src], [], [], network_timeout_delay)[0]
1187 if self.src in ready:
1188 s += self.src.recv(1)
1190 raise Exception("UNRESPONSIVE")
1192 return s.strip(" \r\n")
1194 def send_message(self,s):
1195 if network_timeout_start > 0.0:
1196 ready = select.select([], [self.src], [], network_timeout_start)[1]
1200 if self.src in ready:
1201 self.src.send(s + "\n")
1203 raise Exception("UNRESPONSIVE")
1205 def check_quit(self, s):
1209 game.final_result = " ".join(s[1:]) + " " + str(opponent(self.colour))
1216 class NetworkSender(Player,Network):
1217 def __init__(self, base_player, address = None):
1218 self.base_player = base_player
1219 Player.__init__(self, base_player.name, base_player.colour)
1221 self.address = address
1225 for i in range(nAttempts):
1227 Network.__init__(self, self.colour, self.address)
1228 debug(str(self) +" connected to " + str(self.address))
1230 except Exception, e:
1231 debug(str(self) +" attempt " + str(i) + ": " + str(e.message))
1233 raise Exception("NETWORK - Can't connect to " + str(self.address))
1237 [x,y] = self.base_player.select()
1238 choice = self.board.grid[x][y]
1239 s = str(x) + " " + str(y)
1240 #debug(str(self) + " sends: " + str(s))
1241 self.send_message(s)
1245 [x,y] = self.base_player.get_move()
1246 s = str(x) + " " + str(y)
1247 #debug(str(self) + " sends: " + str(s))
1248 self.send_message(s)
1251 def update(self, s):
1253 self.base_player.update(s)
1254 if self.server == True:
1255 #debug(str(self) + " sends: " + str(s))
1256 self.send_message(s)
1260 [x,y] = map(int, s[0:2])
1261 selected = self.board.grid[x][y]
1262 if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
1263 s = " ".join(s[0:3])
1265 if selected.types[i][0] != '?':
1266 s += " " + str(selected.types[i])
1269 #debug(str(self) +" sending: " + str(s))
1270 self.send_message(s)
1273 def quit(self, final_result):
1274 self.base_player.quit(final_result)
1275 #self.src.send("QUIT " + str(final_result) + "\n")
1279 s = "NetworkSender:"
1284 s += ":"+str(self.address)
1288 class NetworkReceiver(Player,Network):
1289 def __init__(self, colour, address=None):
1293 s += ":"+str(address)
1294 Player.__init__(self, s, colour)
1296 self.address = address
1303 for i in range(nAttempts):
1305 Network.__init__(self, self.colour, self.address)
1306 debug(str(self) +" connected to " + str(self.address))
1308 except Exception, e:
1309 debug(str(self) +" attempt " + str(i) + ": " + str(e.message))
1311 raise Exception("NETWORK - Can't connect to " + str(self.address))
1317 s = self.get_response()
1318 #debug(str(self) +".select reads: " + str(s))
1319 [x,y] = map(int,s.split(" "))
1320 if x == -1 and y == -1:
1321 #print str(self) + ".select quits the game"
1323 game.final_state = "network terminated " + self.colour
1327 s = self.get_response()
1328 #debug(str(self) +".get_move reads: " + str(s))
1329 [x,y] = map(int,s.split(" "))
1330 if x == -1 and y == -1:
1331 #print str(self) + ".get_move quits the game"
1333 game.final_state = "network terminated " + self.colour
1337 def update(self, result):
1338 if self.server == True:
1340 s = self.get_response()
1341 #debug(str(self) + ".update reads: " + str(s))
1342 if not "->" in s.split(" "):
1343 self.board.update(s, sanity=False)
1347 def quit(self, final_result):
1351 s = "NetworkReceiver:"
1356 s += ":"+str(self.address)
1359 # --- network.py --- #
1362 # A thread that can be stopped!
1363 # Except it can only be stopped if it checks self.stopped() periodically
1364 # So it can sort of be stopped
1365 class StoppableThread(threading.Thread):
1367 threading.Thread.__init__(self)
1368 self._stop = threading.Event()
1374 return self._stop.isSet()
1375 # --- thread_util.py --- #
1381 def __init__(self, log):
1385 self.log.write("# Log starts " + str(datetime.datetime.now()) + "\n")
1388 now = datetime.datetime.now()
1389 self.log.write(str(now) + " : " + s + "\n")
1390 self.logged.append((now, s))
1392 def setup(self, board, players):
1395 self.log.write("# " + str(p.colour) + " : " + str(p.name) + "\n")
1397 self.log.write("# Initial board\n")
1398 for x in range(0, w):
1399 for y in range(0, h):
1400 if board.grid[x][y] != None:
1401 self.log.write(str(board.grid[x][y]) + "\n")
1403 self.log.write("# Start game\n")
1406 self.log.write("# EOF\n")
1407 if self.log != sys.stdout:
1410 class ShortLog(LogFile):
1411 def __init__(self, file_name):
1413 self.log = sys.stdout
1415 self.log = open(file_name, "w", 0)
1416 LogFile.__init__(self, self.log)
1417 self.file_name = file_name
1421 now = datetime.datetime.now()
1422 self.logged.append((now, s))
1425 if self.log != sys.stdout:
1427 self.log = open(self.file_name, "w", 0)
1428 self.log.write("# Short log updated " + str(datetime.datetime.now()) + "\n")
1429 LogFile.setup(self, game.board, game.players)
1431 elif self.phase == 1:
1432 for message in self.logged[len(self.logged)-2:]:
1433 self.log.write(str(message[0]) + " : " + message[1] + "\n")
1435 self.phase = (self.phase + 1) % 2
1439 ending = self.logged[len(self.logged)-1]
1440 self.log.write(str(ending[0]) + " : " + ending[1] + "\n")
1441 self.log.write("# EOF\n")
1442 if self.log != sys.stdout:
1446 class HeadRequest(urllib2.Request):
1447 def get_method(self):
1450 class HttpGetter(StoppableThread):
1451 def __init__(self, address):
1452 StoppableThread.__init__(self)
1453 self.address = address
1454 self.log = urllib2.urlopen(address)
1456 self.lock = threading.RLock() #lock for access of self.state
1457 self.cond = threading.Condition() # conditional
1460 while not self.stopped():
1461 line = self.log.readline()
1463 date_mod = datetime.datetime.strptime(self.log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1466 next_log = urllib2.urlopen(HeadRequest(self.address))
1467 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1468 while date_new <= date_mod and not self.stopped():
1469 next_log = urllib2.urlopen(HeadRequest(self.address))
1470 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1474 self.log = urllib2.urlopen(self.address)
1475 line = self.log.readline()
1478 self.lines.append(line)
1479 self.cond.notifyAll()
1482 #sys.stderr.write(" HttpGetter got \'" + str(line) + "\'\n")
1491 def __init__(self, address):
1492 self.getter = HttpGetter(address)
1496 self.getter.cond.acquire()
1497 while len(self.getter.lines) == 0:
1498 self.getter.cond.wait()
1500 result = self.getter.lines[0]
1501 self.getter.lines = self.getter.lines[1:]
1502 self.getter.cond.release()
1511 def __init__(self, filename):
1512 self.f = open(filename, "r", 0)
1513 self.filename = filename
1514 self.mod = os.path.getmtime(filename)
1518 line = self.f.readline()
1521 mod2 = os.path.getmtime(self.filename)
1523 #sys.stderr.write("File changed!\n")
1526 self.f = open(self.filename, "r", 0)
1528 new_line = self.f.readline()
1530 if " ".join(new_line.split(" ")[0:3]) != "# Short log":
1531 for i in range(self.count):
1532 new_line = self.f.readline()
1533 #sys.stderr.write("Read back " + str(i) + ": " + str(new_line) + "\n")
1534 new_line = self.f.readline()
1552 sys.stderr.write("# DEBUG: " + s + "\n")
1555 def log_init(board, players):
1557 l.setup(board, players)
1565 # A thread that runs the game
1566 class GameThread(StoppableThread):
1567 def __init__(self, board, players):
1568 StoppableThread.__init__(self)
1570 self.players = players
1571 self.state = {"turn" : None} # The game state
1572 self.error = 0 # Whether the thread exits with an error
1573 self.lock = threading.RLock() #lock for access of self.state
1574 self.cond = threading.Condition() # conditional for some reason, I forgot
1575 self.final_result = ""
1579 # Run the game (run in new thread with start(), run in current thread with run())
1582 while not self.stopped():
1584 for p in self.players:
1586 if isinstance(p, NetworkSender):
1587 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
1589 self.state["turn"] = p
1592 [x,y] = p.select() # Player selects a square
1596 if not (isinstance(p, Network) and p.server == False):
1597 result = self.board.select(x, y, colour = p.colour)
1599 #debug(str(self) + " don't update local board")
1602 result = p.update(result)
1603 for p2 in self.players:
1605 result = p2.update(result) # Inform players of what happened
1610 target = self.board.grid[x][y]
1611 if isinstance(graphics, GraphicsThread):
1613 graphics.state["moves"] = self.board.possible_moves(target)
1614 graphics.state["select"] = target
1616 time.sleep(turn_delay)
1619 if len(self.board.possible_moves(target)) == 0:
1620 #print "Piece cannot move"
1622 if isinstance(graphics, GraphicsThread):
1624 graphics.state["moves"] = None
1625 graphics.state["select"] = None
1626 graphics.state["dest"] = None
1630 [x2,y2] = p.get_move() # Player selects a destination
1637 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1640 self.board.update_move(x, y, x2, y2)
1642 for p2 in self.players:
1643 p2.update(result) # Inform players of what happened
1647 if isinstance(graphics, GraphicsThread):
1649 graphics.state["moves"] = [[x2,y2]]
1651 time.sleep(turn_delay)
1653 if isinstance(graphics, GraphicsThread):
1655 graphics.state["select"] = None
1656 graphics.state["dest"] = None
1657 graphics.state["moves"] = None
1659 # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
1660 # except Exception,e:
1661 # result = e.message
1662 # #sys.stderr.write(result + "\n")
1666 # self.final_result = self.state["turn"].colour + " " + e.message
1668 end = self.board.end_condition()
1672 self.final_result = self.state["turn"].colour + " " + end
1674 self.final_result = end
1681 for p2 in self.players:
1682 p2.quit(self.final_result)
1684 log(self.final_result)
1686 if isinstance(graphics, GraphicsThread):
1690 # A thread that replays a log file
1691 class ReplayThread(GameThread):
1692 def __init__(self, players, src, end=False,max_moves=None):
1693 self.board = Board(style="empty")
1694 self.board.max_moves = max_moves
1695 GameThread.__init__(self, self.board, players)
1699 self.reset_board(self.src.readline())
1701 def reset_board(self, line):
1704 while line != "# Start game" and line != "# EOF":
1707 line = self.src.readline().strip(" \r\n")
1711 line = self.src.readline().strip(" \r\n")
1714 self_str += line + "\n"
1716 if self.players[0].name == "dummy" and self.players[1].name == "dummy":
1717 line = self.src.readline().strip(" \r\n")
1720 tokens = line.split(" ")
1721 types = map(lambda e : e.strip("[] ,'"), tokens[2:4])
1722 for i in range(len(types)):
1723 if types[i][0] == "?":
1724 types[i] = "unknown"
1726 agent_str += tokens[0] + " " + tokens[1] + " " + str(types) + " ".join(tokens[4:]) + "\n"
1727 line = self.src.readline().strip(" \r\n")
1729 for p in self.players:
1730 p.reset_board(agent_str)
1733 self.board.reset_board(self_str)
1739 line = self.src.readline().strip(" \r\n")
1740 while line != "# EOF":
1752 line = self.src.readline().strip(" \r\n")
1755 tokens = line.split(" ")
1756 if tokens[0] == "white" or tokens[0] == "black":
1757 self.reset_board(line)
1759 line = self.src.readline().strip(" \r\n")
1762 move = line.split(":")
1763 move = move[len(move)-1].strip(" \r\n")
1764 tokens = move.split(" ")
1768 [x,y] = map(int, tokens[0:2])
1776 target = self.board.grid[x][y]
1778 if target.colour == "white":
1779 self.state["turn"] = self.players[0]
1781 self.state["turn"] = self.players[1]
1783 move_piece = (tokens[2] == "->")
1785 [x2,y2] = map(int, tokens[len(tokens)-2:])
1787 if isinstance(graphics, GraphicsThread):
1789 graphics.state["select"] = target
1792 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
1793 if isinstance(graphics, GraphicsThread):
1795 if target.current_type != "unknown":
1796 graphics.state["moves"] = self.board.possible_moves(target)
1798 graphics.state["moves"] = None
1799 time.sleep(turn_delay)
1801 self.board.update_move(x, y, x2, y2)
1802 if isinstance(graphics, GraphicsThread):
1804 graphics.state["moves"] = [[x2,y2]]
1805 time.sleep(turn_delay)
1807 graphics.state["select"] = None
1808 graphics.state["moves"] = None
1809 graphics.state["dest"] = None
1815 for p in self.players:
1819 line = self.src.readline().strip(" \r\n")
1822 end = self.board.end_condition()
1824 self.final_result = end
1842 if self.end and isinstance(graphics, GraphicsThread):
1844 pass # Let the user stop the display
1845 elif not self.end and self.board.end_condition() == None:
1847 # Work out the last move
1849 t = last_line.split(" ")
1850 if t[len(t)-2] == "black":
1851 self.players.reverse()
1852 elif t[len(t)-2] == "white":
1854 elif self.state["turn"] != None and self.state["turn"].colour == "white":
1855 self.players.reverse()
1858 game = GameThread(self.board, self.players)
1865 def opponent(colour):
1866 if colour == "white":
1877 # Dictionary that stores the unicode character representations of the different pieces
1878 # Chess was clearly the reason why unicode was invented
1879 # For some reason none of the pygame chess implementations I found used them!
1880 piece_char = {"white" : {"king" : u'\u2654',
1881 "queen" : u'\u2655',
1883 "bishop" : u'\u2657',
1884 "knight" : u'\u2658',
1887 "black" : {"king" : u'\u265A',
1888 "queen" : u'\u265B',
1890 "bishop" : u'\u265D',
1891 "knight" : u'\u265E',
1895 images = {"white" : {}, "black" : {}}
1896 small_images = {"white" : {}, "black" : {}}
1898 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
1900 # Get the font sizes
1901 l_size = 5*(grid_sz[0] / 8)
1902 s_size = 3*(grid_sz[0] / 8)
1904 for c in piece_char.keys():
1907 for p in piece_char[c].keys():
1908 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
1909 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})
1911 for p in piece_char[c].keys():
1912 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1913 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1914 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1915 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1918 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
1919 if not os.path.exists(image_dir):
1920 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
1921 for c in piece_char.keys():
1922 for p in piece_char[c].keys():
1923 images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
1924 small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
1925 # --- images.py --- #
1926 graphics_enabled = True
1930 os.environ["SDL_VIDEO_ALLOW_SCREENSAVER"] = "1"
1932 graphics_enabled = False
1938 # A thread to make things pretty
1939 class GraphicsThread(StoppableThread):
1940 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1941 StoppableThread.__init__(self)
1945 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1946 pygame.display.set_caption(title)
1948 #print "Initialised properly"
1950 self.grid_sz = grid_sz[:]
1951 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
1953 self.lock = threading.RLock()
1954 self.cond = threading.Condition()
1955 self.sleep_timeout = None
1956 self.last_event = time.time()
1957 self.blackout = False
1960 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
1963 create_images(grid_sz)
1966 for c in images.keys():
1967 for p in images[c].keys():
1968 images[c][p] = images[c][p].convert(self.window)
1969 small_images[c][p] = small_images[c][p].convert(self.window)
1976 # On the run from the world
1979 while not self.stopped():
1981 if self.sleep_timeout == None or (time.time() - self.last_event) < self.sleep_timeout:
1983 #print "Display grid"
1984 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
1986 #print "Display overlay"
1989 #print "Display pieces"
1990 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
1991 self.blackout = False
1993 elif pygame.mouse.get_focused() and not self.blackout:
1994 os.system("xset dpms force off")
1995 self.blackout = True
1996 self.window.fill((0,0,0))
1998 pygame.display.flip()
2000 for event in pygame.event.get():
2001 self.last_event = time.time()
2002 if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_q):
2003 if isinstance(game, GameThread):
2005 game.final_result = ""
2006 if game.state["turn"] != None:
2007 game.final_result = game.state["turn"].colour + " "
2008 game.final_result += "terminated"
2012 elif event.type == pygame.MOUSEBUTTONDOWN:
2013 self.mouse_down(event)
2015 elif event.type == pygame.MOUSEBUTTONUP:
2016 self.mouse_up(event)
2025 self.message("Game ends, result \""+str(game.final_result) + "\"")
2028 # Wake up anyone who is sleeping
2033 pygame.quit() # Time to say goodbye
2035 # Mouse release event handler
2036 def mouse_up(self, event):
2037 if event.button == 3:
2039 self.state["overlay"] = None
2040 elif event.button == 2:
2042 self.state["coverage"] = None
2044 # Mouse click event handler
2045 def mouse_down(self, event):
2046 if event.button == 1:
2047 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
2048 if isinstance(game, GameThread):
2050 p = game.state["turn"]
2055 if isinstance(p, HumanPlayer):
2057 s = self.board.grid[m[0]][m[1]]
2058 select = self.state["select"]
2060 if s != None and s.colour != p.colour:
2061 self.message("Wrong colour") # Look at all this user friendliness!
2064 # Notify human player of move
2067 self.state["select"] = s
2068 self.state["dest"] = None
2077 if self.state["moves"] == None:
2080 if not m in self.state["moves"]:
2081 self.message("Illegal Move") # I still think last year's mouse interface was adequate
2086 if self.state["dest"] == None:
2088 self.state["dest"] = m
2089 self.state["select"] = None
2090 self.state["moves"] = None
2093 elif event.button == 3:
2094 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2095 if isinstance(game, GameThread):
2097 p = game.state["turn"]
2102 if isinstance(p, HumanPlayer):
2104 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
2106 elif event.button == 2:
2107 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2108 if isinstance(game, GameThread):
2110 p = game.state["turn"]
2115 if isinstance(p, HumanPlayer):
2117 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
2122 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
2123 # Draw square over the selected piece
2125 select = self.state["select"]
2127 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
2128 square_img.fill(pygame.Color(0,255,0,64))
2129 self.window.blit(square_img, mp)
2130 # If a piece is selected, draw all reachable squares
2131 # (This quality user interface has been patented)
2133 m = self.state["moves"]
2135 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
2137 mp = [self.grid_sz[i] * move[i] for i in range(2)]
2138 self.window.blit(square_img, mp)
2139 # If a piece is overlayed, show all squares that it has a probability to reach
2141 m = self.state["overlay"]
2146 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
2147 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
2148 self.window.blit(square_img, mp)
2149 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2150 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
2151 self.window.blit(text, mp)
2153 # If a square is selected, highlight all pieces that have a probability to reach it
2155 m = self.state["coverage"]
2158 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
2159 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
2160 self.window.blit(square_img, mp)
2161 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2162 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
2163 self.window.blit(text, mp)
2164 # Draw a square where the mouse is
2165 # This also serves to indicate who's turn it is
2167 if isinstance(game, GameThread):
2169 turn = game.state["turn"]
2173 if isinstance(turn, HumanPlayer):
2174 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
2175 square_img.fill(pygame.Color(0,0,255,128))
2176 if turn.colour == "white":
2177 c = pygame.Color(255,255,255)
2179 c = pygame.Color(0,0,0)
2180 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
2181 self.window.blit(square_img, mp)
2183 # Message in a bottle
2184 def message(self, string, pos = None, colour = None, font_size = 20):
2185 #print "Drawing message..."
2186 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2188 colour = pygame.Color(0,0,0)
2190 text = font.render(string, 1, colour)
2193 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
2194 s.fill(pygame.Color(128,128,128))
2196 tmp = self.window.get_size()
2199 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
2201 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
2204 rect = (pos[0], pos[1], text.get_width(), text.get_height())
2206 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
2207 self.window.blit(s, pos)
2208 self.window.blit(text, pos)
2210 pygame.display.flip()
2212 def getstr(self, prompt = None):
2213 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
2214 s.blit(self.window, (0,0))
2220 self.message(prompt)
2221 self.message(result, pos = (0, 1))
2224 for event in pygame.event.get():
2225 if event.type == pygame.QUIT:
2227 if event.type == pygame.KEYDOWN:
2228 if event.key == pygame.K_BACKSPACE:
2229 result = result[0:len(result)-1]
2230 self.window.blit(s, (0,0)) # Revert the display
2235 if event.unicode == '\r':
2238 result += str(event.unicode)
2243 # Function to pick a button
2244 def SelectButton(self, choices, prompt = None, font_size=20):
2246 #print "Select button called!"
2247 self.board.display_grid(self.window, self.grid_sz)
2249 self.message(prompt)
2250 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2252 sz = self.window.get_size()
2255 for i in range(len(choices)):
2258 text = font.render(c, 1, pygame.Color(0,0,0))
2259 p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
2260 targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
2263 mp =pygame.mouse.get_pos()
2264 for i in range(len(choices)):
2266 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
2267 font_colour = pygame.Color(255,0,0)
2268 box_colour = pygame.Color(0,0,255,128)
2270 font_colour = pygame.Color(0,0,0)
2271 box_colour = pygame.Color(128,128,128)
2273 text = font.render(c, 1, font_colour)
2274 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
2276 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
2277 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
2278 self.window.blit(s, targets[i][0:2])
2281 pygame.display.flip()
2283 for event in pygame.event.get():
2284 if event.type == pygame.QUIT:
2286 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
2287 for i in range(len(targets)):
2289 if event.pos[0] > t[0] and event.pos[0] < t[2]:
2290 if event.pos[1] > t[1] and event.pos[1] < t[3]:
2292 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
2295 # Function to pick players in a nice GUI way
2296 def SelectPlayers(self, players = []):
2299 #print "SelectPlayers called"
2301 missing = ["white", "black"]
2303 missing.remove(p.colour)
2305 for colour in missing:
2308 choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
2310 players.append(HumanPlayer("human", colour))
2313 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2314 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2315 internal_agents.remove(('InternalAgent', InternalAgent))
2316 if len(internal_agents) > 0:
2317 choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
2322 agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
2323 players.append(agent[1](agent[0], colour))
2327 from tkFileDialog import askopenfilename
2328 root = Tkinter.Tk() # Need a root to make Tkinter behave
2329 root.withdraw() # Some sort of magic incantation
2330 path = askopenfilename(parent=root, initialdir="../agents",title=
2333 return self.SelectPlayers()
2334 players.append(make_player(path, colour))
2339 self.board.display_grid(self.window, self.grid_sz)
2340 pygame.display.flip()
2341 path = self.getstr(prompt = "Enter path:")
2346 return self.SelectPlayers()
2349 p = make_player(path, colour)
2351 self.board.display_grid(self.window, self.grid_sz)
2352 pygame.display.flip()
2353 self.message("Invalid path!")
2359 while address == "":
2360 self.board.display_grid(self.window, self.grid_sz)
2362 address = self.getstr(prompt = "Address? (leave blank for server)")
2369 map(int, address.split("."))
2371 self.board.display_grid(self.window, self.grid_sz)
2372 self.message("Invalid IPv4 address!")
2375 players.append(NetworkReceiver(colour, address))
2378 #print str(self) + ".SelectPlayers returns " + str(players)
2383 # --- graphics.py --- #
2384 #!/usr/bin/python -u
2386 # Do you know what the -u does? It unbuffers stdin and stdout
2387 # I can't remember why, but last year things broke without that
2390 UCC::Progcomp 2013 Quantum Chess game
2391 @author Sam Moore [SZM] "matches"
2392 @copyright The University Computer Club, Incorporated
2393 (ie: You can copy it for not for profit purposes)
2396 # system python modules or whatever they are called
2402 sleep_timeout = None
2403 [game, graphics] = [None, None]
2405 def make_player(name, colour):
2407 if name[1:] == "human":
2408 return HumanPlayer(name, colour)
2409 s = name[1:].split(":")
2410 if s[0] == "network":
2414 return NetworkReceiver(colour, address)
2415 if s[0] == "internal":
2418 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2419 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2420 internal_agents.remove(('InternalAgent', InternalAgent))
2423 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
2424 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2427 for a in internal_agents:
2429 return a[1](name, colour)
2431 sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
2432 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2437 return ExternalAgent(name, colour)
2441 # The main function! It does the main stuff!
2444 # Apparently python will silently treat things as local unless you do this
2445 # Anyone who says "You should never use a global variable" can die in a fire
2450 global agent_timeout
2453 global graphics_enabled
2454 global always_reveal_states
2455 global sleep_timeout
2463 # Get the important warnings out of the way
2464 if platform.system() == "Windows":
2465 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
2466 if platform.release() == "Vista":
2467 sys.stderr.write(sys.argv[0] + " : God help you.\n")
2472 while i < len(argv)-1:
2476 p = make_player(arg, colour)
2477 if not isinstance(p, Player):
2478 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
2481 if colour == "white":
2483 elif colour == "black":
2486 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
2489 # Option parsing goes here
2490 if arg[1] == '-' and arg[2:] == "classical":
2492 elif arg[1] == '-' and arg[2:] == "quantum":
2494 elif arg[1] == '-' and arg[2:] == "reveal":
2495 always_reveal_states = True
2496 elif (arg[1] == '-' and arg[2:] == "graphics"):
2497 graphics_enabled = True
2498 elif (arg[1] == '-' and arg[2:] == "no-graphics"):
2499 graphics_enabled = False
2500 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
2501 # Load game from file
2502 if len(arg[2:].split("=")) == 1:
2503 src_file = sys.stdin
2505 f = arg[2:].split("=")[1]
2506 if f[0:7] == "http://":
2507 src_file = HttpReplay(f)
2509 src_file = FileReplay(f.split(":")[0])
2511 if len(f.split(":")) == 2:
2512 max_moves = int(f.split(":")[1])
2514 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
2516 if len(arg[2:].split("=")) == 1:
2517 log_files.append(LogFile(sys.stdout))
2519 f = arg[2:].split("=")[1]
2521 log_files.append(ShortLog(f[1:]))
2523 log_files.append(LogFile(open(f, "w", 0)))
2524 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
2526 if len(arg[2:].split("=")) == 1:
2529 turn_delay = float(arg[2:].split("=")[1])
2531 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
2533 if len(arg[2:].split("=")) == 1:
2536 agent_timeout = float(arg[2:].split("=")[1])
2537 elif (arg[1] == '-' and arg[2:].split("=")[0] == "blackout"):
2538 # Screen saver delay
2539 if len(arg[2:].split("=")) == 1:
2542 sleep_timeout = float(arg[2:].split("=")[1])
2544 elif (arg[1] == '-' and arg[2:] == "help"):
2546 os.system("less data/help.txt") # The best help function
2552 # Construct a GameThread! Make it global! Damn the consequences!
2554 if src_file != None:
2555 # Hack to stop ReplayThread from exiting
2556 #if len(players) == 0:
2557 # players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
2559 # Normally the ReplayThread exits if there are no players
2560 # TODO: Decide which behaviour to use, and fix it
2561 end = (len(players) == 0)
2563 players = [Player("dummy", "white"), Player("dummy", "black")]
2564 elif len(players) != 2:
2565 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2566 if graphics_enabled:
2567 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
2569 game = ReplayThread(players, src_file, end=end, max_moves=max_moves)
2571 board = Board(style)
2572 board.max_moves = max_moves
2573 game = GameThread(board, players)
2579 if graphics_enabled == True:
2581 graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
2583 graphics.sleep_timeout = sleep_timeout
2587 sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
2588 graphics_enabled = False
2590 # If there are no players listed, display a nice pretty menu
2591 if len(players) != 2:
2592 if graphics != None:
2593 players = graphics.SelectPlayers(players)
2595 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2598 # If there are still no players, quit
2599 if players == None or len(players) != 2:
2600 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
2604 # Wrap NetworkSender players around original players if necessary
2605 for i in range(len(players)):
2606 if isinstance(players[i], NetworkReceiver):
2607 players[i].board = board # Network players need direct access to the board
2608 for j in range(len(players)):
2611 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
2613 players[j] = NetworkSender(players[j], players[i].address)
2614 players[j].board = board
2616 # Connect the networked players
2618 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
2619 if graphics != None:
2620 graphics.board.display_grid(graphics.window, graphics.grid_sz)
2621 graphics.message("Connecting to " + p.colour + " player...")
2623 # Handle race condition by having clients wait longer than servers to connect
2624 if p.address != None:
2629 # If using windows, select won't work; use horrible TimeoutPlayer hack
2630 if agent_timeout > 0:
2631 if platform.system() == "Windows":
2632 for i in range(len(players)):
2633 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
2634 players[i] = TimeoutPlayer(players[i], agent_timeout)
2638 # InternalAgents get wrapped to an ExternalAgent when there is a timeout
2639 # This is not confusing at all.
2640 for i in range(len(players)):
2641 if isinstance(players[i], InternalAgent):
2642 players[i] = ExternalWrapper(players[i])
2650 log_init(game.board, players)
2653 if graphics != None:
2654 game.start() # This runs in a new thread
2660 error = game.error + graphics.error
2669 if src_file != None and src_file != sys.stdin:
2672 sys.stdout.write(game.final_result + "\n")
2676 # This is how python does a main() function...
2677 if __name__ == "__main__":
2679 sys.exit(main(sys.argv))
2680 except KeyboardInterrupt:
2681 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
2682 if isinstance(graphics, StoppableThread):
2684 graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
2686 if isinstance(game, StoppableThread):
2694 # EOF - created from make on Tue Apr 2 15:05:07 WST 2013