5 # I know using non-abreviated strings is inefficient, but this is python, who cares?
6 # Oh, yeah, this stores the number of pieces of each type in a normal chess game
7 piece_types = {"pawn" : 8, "bishop" : 2, "knight" : 2, "rook" : 2, "queen" : 1, "king" : 1, "unknown" : 0}
9 # Class to represent a quantum chess piece
11 def __init__(self, colour, x, y, types):
12 self.colour = colour # Colour (string) either "white" or "black"
13 self.x = x # x coordinate (0 - 8), none of this fancy 'a', 'b' shit here
14 self.y = y # y coordinate (0 - 8)
15 self.types = types # List of possible types the piece can be (should just be two)
16 self.current_type = "unknown" # Current type
17 self.choice = -1 # Index of the current type in self.types (-1 = unknown type)
18 self.types_revealed = [True, False] # Whether the types are known (by default the first type is always known at game start)
22 self.last_state = None
23 self.move_pattern = None
27 def init_from_copy(self, c):
28 self.colour = c.colour
31 self.types = c.types[:]
32 self.current_type = c.current_type
33 self.choice = c.choice
34 self.types_revealed = c.types_revealed[:]
36 self.last_state = None
37 self.move_pattern = None
41 # Make a string for the piece (used for debug)
43 return str(self.current_type) + " " + str(self.types) + " at " + str(self.x) + ","+str(self.y)
45 # Draw the piece in a pygame surface
46 def draw(self, window, grid_sz = [80,80], style="quantum"):
48 # First draw the image corresponding to self.current_type
49 img = images[self.colour][self.current_type]
51 if style == "classical":
52 offset = [-rect.width/2, -rect.height/2]
54 offset = [-rect.width/2,-3*rect.height/4]
55 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]))
58 if style == "classical":
61 # Draw the two possible types underneath the current_type image
62 for i in range(len(self.types)):
63 if self.types_revealed[i] == True:
64 img = small_images[self.colour][self.types[i]]
66 img = small_images[self.colour]["unknown"] # If the type hasn't been revealed, show a placeholder
70 offset = [-rect.width/2,-rect.height/2]
73 target = (self.x * grid_sz[0] + grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])
75 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])
77 window.blit(img, target) # Blit shit
79 # Collapses the wave function!
81 if self.current_type == "unknown":
82 self.choice = random.randint(0,1)
83 self.current_type = self.types[self.choice]
84 self.types_revealed[self.choice] = True
87 # Uncollapses (?) the wave function!
89 #print "Deselect called"
90 if (self.x + self.y) % 2 != 0:
91 if (self.types[0] != self.types[1]) or (self.types_revealed[0] == False or self.types_revealed[1] == False):
92 self.current_type = "unknown"
95 self.choice = 0 # Both the two types are the same
97 # The sad moment when you realise that you do not understand anything about a subject you studied for 4 years...
100 [w,h] = [8,8] # Width and height of board(s)
102 # Class to represent a quantum chess board
104 # Initialise; if master=True then the secondary piece types are assigned
105 # Otherwise, they are left as unknown
106 # So you can use this class in Agent programs, and fill in the types as they are revealed
107 def __init__(self, style="agent"):
109 self.pieces = {"white" : [], "black" : []}
110 self.grid = [[None] * w for _ in range(h)] # 2D List (you can get arrays in python, somehow, but they scare me)
111 self.unrevealed_types = {"white" : piece_types.copy(), "black" : piece_types.copy()}
112 self.king = {"white" : None, "black" : None} # We need to keep track of the king, because he is important
113 for c in ["black", "white"]:
114 del self.unrevealed_types[c]["unknown"]
116 # Add all the pieces with known primary types
117 for i in range(0, 2):
119 s = ["black", "white"][i]
123 c.append(Piece(s, 0, y, ["rook"]))
124 c.append(Piece(s, 1, y, ["knight"]))
125 c.append(Piece(s, 2, y, ["bishop"]))
126 k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
127 k.types_revealed[1] = True
128 k.current_type = "king"
131 c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
132 c.append(Piece(s, 5, y, ["bishop"]))
133 c.append(Piece(s, 6, y, ["knight"]))
134 c.append(Piece(s, 7, y, ["rook"]))
142 for x in range(0, w):
143 c.append(Piece(s, x, y, ["pawn"]))
146 types_left.update(piece_types)
147 del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
148 del types_left["unknown"] # We certainly don't want these!
151 self.grid[piece.x][piece.y] = piece
153 if len(piece.types) > 1:
155 if style == "agent": # Assign placeholder "unknown" secondary type
156 piece.types.append("unknown")
159 elif style == "quantum":
160 # The master allocates the secondary types
161 choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
162 types_left[choice] -= 1
163 if types_left[choice] <= 0:
164 del types_left[choice]
165 piece.types.append(choice)
166 elif style == "classical":
167 piece.types.append(piece.types[0])
168 piece.current_type = piece.types[0]
169 piece.types_revealed[1] = True
173 newboard = Board(master = False)
174 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
175 mypieces = self.pieces["white"] + self.pieces["black"]
177 for i in range(len(mypieces)):
178 newpieces[i].init_from_copy(mypieces[i])
181 def display_grid(self, window = None, grid_sz = [80,80]):
183 return # I was considering implementing a text only display, then I thought "Fuck that"
185 # The indentation is getting seriously out of hand...
186 for x in range(0, w):
187 for y in range(0, h):
189 c = pygame.Color(200,200,200)
191 c = pygame.Color(64,64,64)
192 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
194 def display_pieces(self, window = None, grid_sz = [80,80]):
197 for p in self.pieces["white"] + self.pieces["black"]:
198 p.draw(window, grid_sz, self.style)
200 # Draw the board in a pygame window
201 def display(self, window = None):
202 self.display_grid(window)
203 self.display_pieces(window)
211 if self.grid[x][y] == None:
213 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
214 raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
216 # Select a piece on the board (colour is the colour of whoever is doing the selecting)
217 def select(self, x,y, colour=None):
218 if not self.on_board(x, y): # Get on board everyone!
219 raise Exception("BOUNDS")
221 piece = self.grid[x][y]
223 raise Exception("EMPTY")
225 if colour != None and piece.colour != colour:
226 raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
228 # I'm not quite sure why I made this return a string, but screw logical design
229 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
232 # Update the board when a piece has been selected
233 # "type" is apparently reserved, so I'll use "state"
234 def update_select(self, x, y, type_index, state):
235 piece = self.grid[x][y]
236 if piece.types[type_index] == "unknown":
237 if not state in self.unrevealed_types[piece.colour].keys():
238 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
239 self.unrevealed_types[piece.colour][state] -= 1
240 if self.unrevealed_types[piece.colour][state] <= 0:
241 del self.unrevealed_types[piece.colour][state]
243 piece.types[type_index] = state
244 piece.types_revealed[type_index] = True
245 piece.current_type = state
247 if len(self.possible_moves(piece)) <= 0:
248 piece.deselect() # Piece can't move; deselect it
250 # Update the board when a piece has been moved
251 def update_move(self, x, y, x2, y2):
252 piece = self.grid[x][y]
253 self.grid[x][y] = None
254 taken = self.grid[x2][y2]
256 if taken.current_type == "king":
257 self.king[taken.colour] = None
258 self.pieces[taken.colour].remove(taken)
259 self.grid[x2][y2] = piece
263 # If the piece is a pawn, and it reaches the final row, it becomes a queen
264 # I know you are supposed to get a choice
265 # But that would be effort
266 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
267 if self.style == "classical":
268 piece.types[0] = "queen"
269 piece.types[1] = "queen"
271 piece.types[piece.choice] = "queen"
272 piece.current_type = "queen"
274 piece.deselect() # Uncollapse (?) the wavefunction!
277 # Update the board from a string
278 # Guesses what to do based on the format of the string
279 def update(self, result):
280 #print "Update called with \"" + str(result) + "\""
281 # String always starts with 'x y'
283 s = result.split(" ")
284 [x,y] = map(int, s[0:2])
286 raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
288 piece = self.grid[x][y]
290 raise Exception("EMPTY")
292 # If a piece is being moved, the third token is '->'
293 # We could get away with just using four integers, but that wouldn't look as cool
295 # Last two tokens are the destination
297 [x2,y2] = map(int, s[3:])
299 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
301 # Move the piece (take opponent if possible)
302 self.update_move(x, y, x2, y2)
305 # Otherwise we will just assume a piece has been selected
307 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
308 state = s[3] # The last token is a string identifying the type
310 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
313 self.update_select(x, y, type_index, state)
317 # Gets each piece that could reach the given square and the probability that it could reach that square
318 # Will include allied pieces that defend the attacker
319 def coverage(self, x, y, colour = None, reject_allied = True):
323 pieces = self.pieces["white"] + self.pieces["black"]
325 pieces = self.pieces[colour]
328 prob = self.probability_grid(p, reject_allied)[x][y]
330 result.update({p : prob})
339 # Associates each square with a probability that the piece could move into it
340 # Look, I'm doing all the hard work for you here...
341 def probability_grid(self, p, reject_allied = True):
343 result = [[0.0] * w for _ in range(h)]
344 if not isinstance(p, Piece):
347 if p.current_type != "unknown":
348 #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
349 for point in self.possible_moves(p, reject_allied):
350 result[point[0]][point[1]] = 1.0
354 for i in range(len(p.types)):
357 if t == "unknown" or p.types_revealed[i] == False:
359 for t2 in self.unrevealed_types[p.colour].keys():
360 total_types += self.unrevealed_types[p.colour][t2]
362 for t2 in self.unrevealed_types[p.colour].keys():
363 prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
365 for point in self.possible_moves(p, reject_allied):
366 result[point[0]][point[1]] += prob2 * prob
370 for point in self.possible_moves(p, reject_allied):
371 result[point[0]][point[1]] += prob
374 p.current_type = "unknown"
377 def prob_is_type(self, p, state):
380 for i in range(len(p.types)):
385 if t == "unknown" or p.types_revealed[i] == False:
387 for t2 in self.unrevealed_types[p.colour].keys():
388 total_prob += self.unrevealed_types[p.colour][t2]
389 for t2 in self.unrevealed_types[p.colour].keys():
391 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
395 # Get all squares that the piece could move into
396 # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
397 # reject_allied indicates whether squares occupied by allied pieces will be removed
398 # (set to false to check for defense)
399 def possible_moves(self, p, reject_allied = True):
405 if p.current_type == "unknown":
406 raise Exception("SANITY: Piece state unknown")
407 # The below commented out code causes things to break badly
412 # result += self.possible_moves(p)
413 #p.current_type = "unknown"
416 if p.current_type == "king":
417 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]]
418 elif p.current_type == "queen":
419 for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
420 result += self.scan(p.x, p.y, d[0], d[1])
421 elif p.current_type == "bishop":
422 for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
423 result += self.scan(p.x, p.y, d[0], d[1])
424 elif p.current_type == "rook":
425 for d in [[-1,0],[1,0],[0,-1],[0,1]]:
426 result += self.scan(p.x, p.y, d[0], d[1])
427 elif p.current_type == "knight":
428 # I would use two lines, but I'm not sure how python likes that
429 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]]
430 elif p.current_type == "pawn":
431 if p.colour == "white":
433 # Pawn can't move forward into occupied square
434 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
435 result = [[p.x,p.y-1]]
436 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
437 if not self.on_board(f[0], f[1]):
439 if self.grid[f[0]][f[1]] != None: # Pawn can take diagonally
442 # Slightly embarrassing if the pawn jumps over someone on its first move...
443 if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
444 result.append([p.x, p.y-2])
446 # Vice versa for the black pawn
447 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
448 result = [[p.x,p.y+1]]
450 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
451 if not self.on_board(f[0], f[1]):
453 if self.grid[f[0]][f[1]] != None:
454 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
457 if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
458 result.append([p.x, p.y+2])
460 #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
462 # Remove illegal moves
463 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
464 for point in result[:]:
466 if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
467 result.remove(point) # Remove locations outside the board
469 g = self.grid[point[0]][point[1]]
471 if g != None and (g.colour == p.colour and reject_allied == True):
472 result.remove(point) # Remove allied pieces
478 # Scans in a direction until it hits a piece, returns all squares in the line
479 # (includes the final square (which contains a piece), but not the original square)
480 def scan(self, x, y, vx, vy):
488 if not self.on_board(xx, yy):
492 g = self.grid[xx][yy]
500 # I typed the full statement about 30 times before writing this function...
501 def on_board(self, x, y):
502 return (x >= 0 and x < w) and (y >= 0 and y < h)
504 # +++ player.py +++ #
509 agent_timeout = -1.0 # Timeout in seconds for AI players to make moves
510 # WARNING: Won't work for windows based operating systems
512 if platform.system() == "Windows":
513 agent_timeout = -1 # Hence this
515 # A player who can't play
517 def __init__(self, name, colour):
521 # Player that runs from another process
522 class AgentPlayer(Player):
525 def __init__(self, name, colour):
526 Player.__init__(self, name, colour)
527 self.p = subprocess.Popen(name, stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
529 self.send_message(colour)
531 def send_message(self, s):
532 if agent_timeout > 0.0:
533 ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
535 ready = [self.p.stdin]
536 if self.p.stdin in ready:
537 #print "Writing to p.stdin"
539 self.p.stdin.write(s + "\n")
541 raise Exception("UNRESPONSIVE")
543 raise Exception("UNRESPONSIVE")
545 def get_response(self):
546 if agent_timeout > 0.0:
547 ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
549 ready = [self.p.stdout]
550 if self.p.stdout in ready:
551 #print "Reading from p.stdout"
553 return self.p.stdout.readline().strip("\r\n")
554 except: # Exception, e:
555 raise Exception("UNRESPONSIVE")
557 raise Exception("UNRESPONSIVE")
561 self.send_message("SELECTION?")
562 line = self.get_response()
565 result = map(int, line.split(" "))
567 raise Exception("GIBBERISH \"" + str(line) + "\"")
570 def update(self, result):
571 #print "Update " + str(result) + " called for AgentPlayer"
572 self.send_message(result)
577 self.send_message("MOVE?")
578 line = self.get_response()
581 result = map(int, line.split(" "))
583 raise Exception("GIBBERISH \"" + str(line) + "\"")
586 def quit(self, final_result):
588 self.send_message("QUIT " + final_result)
592 # So you want to be a player here?
593 class HumanPlayer(Player):
594 def __init__(self, name, colour):
595 Player.__init__(self, name, colour)
597 # Select your preferred account
599 if isinstance(graphics, GraphicsThread):
600 # Basically, we let the graphics thread do some shit and then return that information to the game thread
601 graphics.cond.acquire()
602 # We wait for the graphics thread to select a piece
603 while graphics.stopped() == False and graphics.state["select"] == None:
604 graphics.cond.wait() # The difference between humans and machines is that humans sleep
605 select = graphics.state["select"]
608 graphics.cond.release()
609 if graphics.stopped():
611 return [select.x, select.y]
613 # Since I don't display the board in this case, I'm not sure why I filled it in...
615 sys.stdout.write("SELECTION?\n")
617 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
619 sys.stderr.write("ILLEGAL GIBBERISH\n")
621 # It's your move captain
623 if isinstance(graphics, GraphicsThread):
624 graphics.cond.acquire()
625 while graphics.stopped() == False and graphics.state["dest"] == None:
627 graphics.cond.release()
629 return graphics.state["dest"]
633 sys.stdout.write("MOVE?\n")
635 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
637 sys.stderr.write("ILLEGAL GIBBERISH\n")
640 # Are you sure you want to quit?
641 def quit(self, final_result):
643 sys.stdout.write("QUIT " + final_result + "\n")
645 # Completely useless function
646 def update(self, result):
647 if isinstance(graphics, GraphicsThread):
650 sys.stdout.write(result + "\n")
653 # Player that makes random moves
654 class AgentRandom(Player):
655 def __init__(self, name, colour):
656 Player.__init__(self, name, colour)
659 self.board = Board(style = "agent")
663 self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
665 # Check that the piece has some possibility to move
666 tmp = self.choice.current_type
667 if tmp == "unknown": # For unknown pieces, try both types
668 for t in self.choice.types:
671 self.choice.current_type = t
672 all_moves += self.board.possible_moves(self.choice)
674 all_moves = self.board.possible_moves(self.choice)
675 self.choice.current_type = tmp
676 if len(all_moves) > 0:
678 return [self.choice.x, self.choice.y]
681 moves = self.board.possible_moves(self.choice)
682 move = moves[random.randint(0, len(moves)-1)]
685 def update(self, result):
686 #sys.stderr.write(sys.argv[0] + " : Update board for AgentRandom\n")
687 self.board.update(result)
690 def quit(self, final_result):
692 # --- player.py --- #
693 # +++ network.py +++ #
697 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
698 network_timeout_delay = 1.0 # Maximum time between two characters being received
701 def __init__(self, colour, address = None):
702 self.socket = socket.socket()
703 #self.socket.setblocking(0)
705 if colour == "white":
712 # print str(self) + " listens on port " + str(self.port)
715 self.host = socket.gethostname()
716 self.socket.bind((self.host, self.port))
717 self.socket.listen(5)
719 self.src, self.address = self.socket.accept()
720 self.src.send("ok\n")
721 if self.get_response() == "QUIT":
725 self.socket.connect((address, self.port))
726 self.src = self.socket
727 self.src.send("ok\n")
728 if self.get_response() == "QUIT":
731 def get_response(self):
732 # Timeout the start of the message (first character)
733 if network_timeout_start > 0.0:
734 ready = select.select([self.src], [], [], network_timeout_start)[0]
737 if self.src in ready:
740 raise Exception("UNRESPONSIVE")
743 while s[len(s)-1] != '\n':
744 # Timeout on each character in the message
745 if network_timeout_delay > 0.0:
746 ready = select.select([self.src], [], [], network_timeout_delay)[0]
749 if self.src in ready:
750 s += self.src.recv(1)
752 raise Exception("UNRESPONSIVE")
754 return s.strip(" \r\n")
756 def send_message(self,s):
757 if network_timeout_start > 0.0:
758 ready = select.select([], [self.src], [], network_timeout_start)[1]
762 if self.src in ready:
763 self.src.send(s + "\n")
765 raise Exception("UNRESPONSIVE")
767 def check_quit(self, s):
771 game.final_result = " ".join(s[1:]) + " " + str(opponent(self.colour))
777 class NetworkSender(Player,Network):
778 def __init__(self, base_player, address = None):
779 self.base_player = base_player
780 Player.__init__(self, base_player.name, base_player.colour)
782 self.address = address
785 Network.__init__(self, self.base_player.colour, self.address)
790 [x,y] = self.base_player.select()
791 choice = self.board.grid[x][y]
792 s = str(x) + " " + str(y)
793 #print str(self) + ".select sends " + s
798 [x,y] = self.base_player.get_move()
799 s = str(x) + " " + str(y)
800 #print str(self) + ".get_move sends " + s
805 self.base_player.update(s)
807 [x,y] = map(int, s[0:2])
808 selected = self.board.grid[x][y]
809 if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
812 if selected.types_revealed[i] == True:
813 s += " " + str(selected.types[i])
816 #print str(self) + ".update sends " + s
820 def quit(self, final_result):
821 self.base_player.quit(final_result)
822 #self.src.send("QUIT " + str(final_result) + "\n")
825 class NetworkReceiver(Player,Network):
826 def __init__(self, colour, address=None):
828 Player.__init__(self, address, colour)
830 self.address = address
835 Network.__init__(self, self.colour, self.address)
840 s = self.get_response()
841 #print str(self) + ".select gets " + s
842 [x,y] = map(int,s.split(" "))
843 if x == -1 and y == -1:
844 #print str(self) + ".select quits the game"
846 game.final_state = "network terminated " + self.colour
850 s = self.get_response()
851 #print str(self) + ".get_move gets " + s
852 [x,y] = map(int,s.split(" "))
853 if x == -1 and y == -1:
854 #print str(self) + ".get_move quits the game"
856 game.final_state = "network terminated " + self.colour
860 def update(self, result):
862 result = result.split(" ")
863 [x,y] = map(int, result[0:2])
864 selected = self.board.grid[x][y]
865 if selected != None and selected.colour == self.colour and len(result) > 2 and not "->" in result:
866 s = self.get_response()
867 #print str(self) + ".update - receives " + str(s)
869 selected.choice = int(s[2])
871 selected.types[i] = str(s[3+i])
872 if s[3+i] == "unknown":
873 selected.types_revealed[i] = False
875 selected.types_revealed[i] = True
876 selected.current_type = selected.types[selected.choice]
879 #print str(self) + ".update - ignore result " + str(result)
882 def quit(self, final_result):
885 # --- network.py --- #
886 # +++ thread_util.py +++ #
889 # A thread that can be stopped!
890 # Except it can only be stopped if it checks self.stopped() periodically
891 # So it can sort of be stopped
892 class StoppableThread(threading.Thread):
894 threading.Thread.__init__(self)
895 self._stop = threading.Event()
901 return self._stop.isSet()
902 # --- thread_util.py --- #
905 # A thread that runs the game
906 class GameThread(StoppableThread):
907 def __init__(self, board, players):
908 StoppableThread.__init__(self)
910 self.players = players
911 self.state = {"turn" : None} # The game state
912 self.error = 0 # Whether the thread exits with an error
913 self.lock = threading.RLock() #lock for access of self.state
914 self.cond = threading.Condition() # conditional for some reason, I forgot
915 self.final_result = ""
917 # Run the game (run in new thread with start(), run in current thread with run())
920 while not self.stopped():
922 for p in self.players:
924 if isinstance(p, NetworkSender):
925 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
927 self.state["turn"] = p
929 [x,y] = p.select() # Player selects a square
936 result = self.board.select(x, y, colour = p.colour)
937 for p2 in self.players:
938 p2.update(result) # Inform players of what happened
942 target = self.board.grid[x][y]
943 if isinstance(graphics, GraphicsThread):
945 graphics.state["moves"] = self.board.possible_moves(target)
946 graphics.state["select"] = target
948 time.sleep(turn_delay)
951 if len(self.board.possible_moves(target)) == 0:
952 #print "Piece cannot move"
954 if isinstance(graphics, GraphicsThread):
956 graphics.state["moves"] = None
957 graphics.state["select"] = None
958 graphics.state["dest"] = None
962 [x2,y2] = p.get_move() # Player selects a destination
969 result = self.board.update_move(x, y, x2, y2)
970 for p2 in self.players:
971 p2.update(str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)) # Inform players of what happened
973 if isinstance(graphics, GraphicsThread):
975 graphics.state["moves"] = [[x2,y2]]
977 time.sleep(turn_delay)
979 if isinstance(graphics, GraphicsThread):
981 graphics.state["select"] = None
982 graphics.state["dest"] = None
983 graphics.state["moves"] = None
985 # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
988 #sys.stderr.write(result + "\n")
992 self.final_result = self.state["turn"].colour + " " + e.message
994 if self.board.king["black"] == None:
995 if self.board.king["white"] == None:
997 self.final_result = self.state["turn"].colour + " DRAW"
1000 self.final_result = "white"
1002 elif self.board.king["white"] == None:
1004 self.final_result = "black"
1012 for p2 in self.players:
1013 p2.quit(self.final_result)
1020 def opponent(colour):
1021 if colour == "white":
1026 # +++ graphics.py +++ #
1029 # Dictionary that stores the unicode character representations of the different pieces
1030 # Chess was clearly the reason why unicode was invented
1031 # For some reason none of the pygame chess implementations I found used them!
1032 piece_char = {"white" : {"king" : u'\u2654',
1033 "queen" : u'\u2655',
1035 "bishop" : u'\u2657',
1036 "knight" : u'\u2658',
1039 "black" : {"king" : u'\u265A',
1040 "queen" : u'\u265B',
1042 "bishop" : u'\u265D',
1043 "knight" : u'\u265E',
1047 images = {"white" : {}, "black" : {}}
1048 small_images = {"white" : {}, "black" : {}}
1050 # A thread to make things pretty
1051 class GraphicsThread(StoppableThread):
1052 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1053 StoppableThread.__init__(self)
1057 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1058 pygame.display.set_caption(title)
1059 self.grid_sz = grid_sz[:]
1060 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
1062 self.lock = threading.RLock()
1063 self.cond = threading.Condition()
1065 # Get the font sizes
1066 l_size = 5*(self.grid_sz[0] / 8)
1067 s_size = 3*(self.grid_sz[0] / 8)
1068 for p in piece_types.keys():
1070 images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", l_size).render(piece_char[c][p], True,(0,0,0))})
1071 small_images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", s_size).render(piece_char[c][p],True,(0,0,0))})
1074 images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1075 images[c][p].blit(pygame.font.Font("data/DejaVuSans.ttf", l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1076 small_images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1077 small_images[c][p].blit(pygame.font.Font("data/DejaVuSans.ttf", s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1083 # On the run from the world
1086 while not self.stopped():
1088 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
1092 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
1094 pygame.display.flip()
1096 for event in pygame.event.get():
1097 if event.type == pygame.QUIT:
1098 if isinstance(game, GameThread):
1100 game.final_result = ""
1101 if game.state["turn"] != None:
1102 game.final_result = game.state["turn"].colour + " "
1103 game.final_result += "terminated"
1107 elif event.type == pygame.MOUSEBUTTONDOWN:
1108 self.mouse_down(event)
1109 elif event.type == pygame.MOUSEBUTTONUP:
1110 self.mouse_up(event)
1117 self.message("Game ends, result \""+str(game.final_result) + "\"")
1120 # Wake up anyone who is sleeping
1125 pygame.quit() # Time to say goodbye
1127 # Mouse release event handler
1128 def mouse_up(self, event):
1129 if event.button == 3:
1131 self.state["overlay"] = None
1132 elif event.button == 2:
1134 self.state["coverage"] = None
1136 # Mouse click event handler
1137 def mouse_down(self, event):
1138 if event.button == 1:
1139 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
1140 if isinstance(game, GameThread):
1142 p = game.state["turn"]
1147 if isinstance(p, HumanPlayer):
1149 s = self.board.grid[m[0]][m[1]]
1150 select = self.state["select"]
1152 if s != None and s.colour != p.colour:
1153 self.message("Wrong colour") # Look at all this user friendliness!
1156 # Notify human player of move
1159 self.state["select"] = s
1160 self.state["dest"] = None
1169 if self.state["moves"] == None:
1172 if not m in self.state["moves"]:
1173 self.message("Illegal Move") # I still think last year's mouse interface was adequate
1178 if self.state["dest"] == None:
1180 self.state["dest"] = m
1181 self.state["select"] = None
1182 self.state["moves"] = None
1185 elif event.button == 3:
1186 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1187 if isinstance(game, GameThread):
1189 p = game.state["turn"]
1194 if isinstance(p, HumanPlayer):
1196 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
1198 elif event.button == 2:
1199 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1200 if isinstance(game, GameThread):
1202 p = game.state["turn"]
1207 if isinstance(p, HumanPlayer):
1209 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
1214 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
1215 # Draw square over the selected piece
1217 select = self.state["select"]
1219 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
1220 square_img.fill(pygame.Color(0,255,0,64))
1221 self.window.blit(square_img, mp)
1222 # If a piece is selected, draw all reachable squares
1223 # (This quality user interface has been patented)
1225 m = self.state["moves"]
1227 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
1229 mp = [self.grid_sz[i] * move[i] for i in range(2)]
1230 self.window.blit(square_img, mp)
1231 # If a piece is overlayed, show all squares that it has a probability to reach
1233 m = self.state["overlay"]
1238 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
1239 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
1240 self.window.blit(square_img, mp)
1241 font = pygame.font.Font(None, 14)
1242 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
1243 self.window.blit(text, mp)
1245 # If a square is selected, highlight all pieces that have a probability to reach it
1247 m = self.state["coverage"]
1250 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
1251 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
1252 self.window.blit(square_img, mp)
1253 font = pygame.font.Font(None, 14)
1254 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
1255 self.window.blit(text, mp)
1256 # Draw a square where the mouse is
1257 # This also serves to indicate who's turn it is
1259 if isinstance(game, GameThread):
1261 turn = game.state["turn"]
1265 if isinstance(turn, HumanPlayer):
1266 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
1267 square_img.fill(pygame.Color(0,0,255,128))
1268 if turn.colour == "white":
1269 c = pygame.Color(255,255,255)
1271 c = pygame.Color(0,0,0)
1272 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
1273 self.window.blit(square_img, mp)
1275 # Message in a bottle
1276 def message(self, string, pos = None, colour = None, font_size = 32):
1277 font = pygame.font.Font(None, font_size)
1279 colour = pygame.Color(0,0,0)
1281 text = font.render(string, 1, colour)
1284 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
1285 s.fill(pygame.Color(128,128,128))
1287 tmp = self.window.get_size()
1290 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
1292 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
1295 rect = (pos[0], pos[1], text.get_width(), text.get_height())
1297 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
1298 self.window.blit(s, pos)
1299 self.window.blit(text, pos)
1301 pygame.display.flip()
1303 def getstr(self, prompt = None):
1304 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
1305 s.blit(self.window, (0,0))
1311 self.message(prompt)
1312 self.message(result, pos = (0, 1))
1315 for event in pygame.event.get():
1316 if event.type == pygame.QUIT:
1318 if event.type == pygame.KEYDOWN:
1319 if event.key == pygame.K_BACKSPACE:
1320 result = result[0:len(result)-1]
1321 self.window.blit(s, (0,0)) # Revert the display
1326 if event.unicode == '\r':
1329 result += str(event.unicode)
1334 # Function to pick a button
1335 def SelectButton(self, choices, prompt = None, font_size=32):
1336 self.board.display_grid(self.window, self.grid_sz)
1338 self.message(prompt)
1339 font = pygame.font.Font(None, font_size)
1341 sz = self.window.get_size()
1344 for i in range(len(choices)):
1347 text = font.render(c, 1, pygame.Color(0,0,0))
1348 p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
1349 targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
1352 mp =pygame.mouse.get_pos()
1353 for i in range(len(choices)):
1355 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
1356 font_colour = pygame.Color(255,0,0)
1357 box_colour = pygame.Color(0,0,255,128)
1359 font_colour = pygame.Color(0,0,0)
1360 box_colour = pygame.Color(128,128,128)
1362 text = font.render(c, 1, font_colour)
1363 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
1365 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
1366 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
1367 self.window.blit(s, targets[i][0:2])
1370 pygame.display.flip()
1372 for event in pygame.event.get():
1373 if event.type == pygame.QUIT:
1375 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
1376 for i in range(len(targets)):
1378 if event.pos[0] > t[0] and event.pos[0] < t[2]:
1379 if event.pos[1] > t[1] and event.pos[1] < t[3]:
1381 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
1384 # Function to pick players in a nice GUI way
1385 def SelectPlayers(self, players = []):
1389 missing = ["white", "black"]
1391 missing.remove(p.colour)
1393 for colour in missing:
1396 choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player", font_size=32)
1398 players.append(HumanPlayer("human", colour))
1402 from tkFileDialog import askopenfilename
1403 root = Tkinter.Tk() # Need a root to make Tkinter behave
1404 root.withdraw() # Some sort of magic incantation
1405 path = askopenfilename(parent=root, initialdir="../agents",title=
1408 return self.SelectPlayers()
1409 players.append(make_player(path, colour))
1411 print "Exception was " + str(e.message)
1414 self.board.display_grid(self.window, self.grid_sz)
1415 pygame.display.flip()
1416 path = self.getstr(prompt = "Enter path:")
1421 return self.SelectPlayers()
1424 p = make_player(path, colour)
1426 self.board.display_grid(self.window, self.grid_sz)
1427 pygame.display.flip()
1428 self.message("Invalid path!")
1434 while address == "":
1435 self.board.display_grid(self.window, self.grid_sz)
1437 address = self.getstr(prompt = "Address? (leave blank for server)")
1444 map(int, address.split("."))
1446 self.board.display_grid(self.window, self.grid_sz)
1447 self.message("Invalid IPv4 address!")
1450 players.append(NetworkReceiver(colour, address))
1453 #print str(self) + ".SelectPlayers returns " + str(players)
1458 # --- graphics.py --- #
1460 #!/usr/bin/python -u
1462 # Do you know what the -u does? It unbuffers stdin and stdout
1463 # I can't remember why, but last year things broke without that
1466 UCC::Progcomp 2013 Quantum Chess game
1467 @author Sam Moore [SZM] "matches"
1468 @copyright The University Computer Club, Incorporated
1469 (ie: You can copy it for not for profit purposes)
1472 # system python modules or whatever they are called
1478 [game, graphics] = [None, None]
1480 def make_player(name, colour):
1482 if name[1:] == "human":
1483 return HumanPlayer(name, colour)
1484 s = name[1:].split(":")
1485 if s[0] == "network":
1489 return NetworkReceiver(colour, address)
1492 return AgentPlayer(name, colour)
1496 # The main function! It does the main stuff!
1499 # Apparently python will silently treat things as local unless you do this
1500 # Anyone who says "You should never use a global variable" can die in a fire
1505 global agent_timeout
1514 graphics_enabled = True
1518 while i < len(argv)-1:
1522 players.append(make_player(arg, colour))
1523 if colour == "white":
1525 elif colour == "black":
1528 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
1531 # Option parsing goes here
1532 if arg[1] == '-' and arg[2:] == "classical":
1534 elif arg[1] == '-' and arg[2:] == "quantum":
1536 elif (arg[1] == '-' and arg[2:] == "graphics"):
1537 graphics_enabled = not graphics_enabled
1538 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
1539 # Load game from file
1540 if len(arg[2:].split("=")) == 1:
1541 src_file = sys.stdout
1543 src_file = arg[2:].split("=")[1]
1544 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
1546 if len(arg[2:].split("=")) == 1:
1547 log_file = sys.stdout
1549 log_file = arg[2:].split("=")[1]
1550 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
1552 if len(arg[2:].split("=")) == 1:
1555 turn_delay = float(arg[2:].split("=")[1])
1557 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
1559 if len(arg[2:].split("=")) == 1:
1561 elif platform.system() != "Windows": # Windows breaks this option
1562 agent_timeout = float(arg[2:].split("=")[1])
1564 sys.stderr.write(sys.argv[0] + " : Warning - You are using Windows\n")
1567 elif (arg[1] == '-' and arg[2:] == "help"):
1569 os.system("less data/help.txt") # The best help function
1574 board = Board(style)
1578 if graphics_enabled == True:
1580 graphics = GraphicsThread(board, grid_sz = [64,64]) # Construct a GraphicsThread!
1583 sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
1584 graphics_enabled = False
1586 # If there are no players listed, display a nice pretty menu
1587 if len(players) != 2:
1588 if graphics != None:
1589 players = graphics.SelectPlayers(players)
1591 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
1594 # If there are still no players, quit
1595 if players == None or len(players) != 2:
1596 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
1600 # Wrap NetworkSender players around original players if necessary
1601 for i in range(len(players)):
1602 if isinstance(players[i], NetworkReceiver):
1603 players[i].board = board # Network players need direct access to the board
1604 for j in range(len(players)):
1607 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
1609 players[j] = NetworkSender(players[j], players[i].address)
1610 players[j].board = board
1612 # Connect the networked players
1614 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
1615 if graphics != None:
1616 graphics.board.display_grid(graphics.window, graphics.grid_sz)
1617 graphics.message("Connecting to " + p.colour + " player...")
1621 # Construct a GameThread! Make it global! Damn the consequences!
1622 game = GameThread(board, players)
1626 if graphics != None:
1627 game.start() # This runs in a new thread
1630 return game.error + graphics.error
1635 # This is how python does a main() function...
1636 if __name__ == "__main__":
1637 sys.exit(main(sys.argv))
1639 # EOF - created from make on Thu Jan 24 17:04:54 WST 2013