4 # I know using non-abreviated strings is inefficient, but this is python, who cares?
5 # Oh, yeah, this stores the number of pieces of each type in a normal chess game
6 piece_types = {"pawn" : 8, "bishop" : 2, "knight" : 2, "rook" : 2, "queen" : 1, "king" : 1, "unknown" : 0}
8 # Class to represent a quantum chess piece
10 def __init__(self, colour, x, y, types):
11 self.colour = colour # Colour (string) either "white" or "black"
12 self.x = x # x coordinate (0 - 8), none of this fancy 'a', 'b' shit here
13 self.y = y # y coordinate (0 - 8)
14 self.types = types # List of possible types the piece can be (should just be two)
15 self.current_type = "unknown" # Current type
16 self.choice = -1 # Index of the current type in self.types (-1 = unknown type)
17 self.types_revealed = [True, False] # Whether the types are known (by default the first type is always known at game start)
21 self.last_state = None
22 self.move_pattern = None
26 def init_from_copy(self, c):
27 self.colour = c.colour
30 self.types = c.types[:]
31 self.current_type = c.current_type
32 self.choice = c.choice
33 self.types_revealed = c.types_revealed[:]
35 self.last_state = None
36 self.move_pattern = None
40 # Make a string for the piece (used for debug)
42 return str(self.current_type) + " " + str(self.types) + " at " + str(self.x) + ","+str(self.y)
44 # Draw the piece in a pygame surface
45 def draw(self, window, grid_sz = [80,80], style="quantum"):
47 # First draw the image corresponding to self.current_type
48 img = images[self.colour][self.current_type]
50 if style == "classical":
51 offset = [-rect.width/2, -rect.height/2]
53 offset = [-rect.width/2,-3*rect.height/4]
54 window.blit(img, (self.x * grid_sz[0] + grid_sz[0]/2 + offset[0], self.y * grid_sz[1] + grid_sz[1]/2 + offset[1]))
57 if style == "classical":
60 # Draw the two possible types underneath the current_type image
61 for i in range(len(self.types)):
62 if self.types_revealed[i] == True:
63 img = small_images[self.colour][self.types[i]]
65 img = small_images[self.colour]["unknown"] # If the type hasn't been revealed, show a placeholder
69 offset = [-rect.width/2,-rect.height/2]
72 target = (self.x * grid_sz[0] + grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])
74 target = (self.x * grid_sz[0] + 4*grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])
76 window.blit(img, target) # Blit shit
78 # Collapses the wave function!
80 if self.current_type == "unknown":
81 self.choice = random.randint(0,1)
82 self.current_type = self.types[self.choice]
83 self.types_revealed[self.choice] = True
86 # Uncollapses (?) the wave function!
88 #print "Deselect called"
89 if (self.x + self.y) % 2 != 0:
90 if (self.types[0] != self.types[1]) or (self.types_revealed[0] == False or self.types_revealed[1] == False):
91 self.current_type = "unknown"
94 self.choice = 0 # Both the two types are the same
96 # The sad moment when you realise that you do not understand anything about a subject you studied for 4 years...
98 [w,h] = [8,8] # Width and height of board(s)
100 # Class to represent a quantum chess board
102 # Initialise; if master=True then the secondary piece types are assigned
103 # Otherwise, they are left as unknown
104 # So you can use this class in Agent programs, and fill in the types as they are revealed
105 def __init__(self, style="agent"):
107 self.pieces = {"white" : [], "black" : []}
108 self.grid = [[None] * w for _ in range(h)] # 2D List (you can get arrays in python, somehow, but they scare me)
109 self.unrevealed_types = {"white" : piece_types.copy(), "black" : piece_types.copy()}
110 self.king = {"white" : None, "black" : None} # We need to keep track of the king, because he is important
111 for c in ["black", "white"]:
112 del self.unrevealed_types[c]["unknown"]
114 # Add all the pieces with known primary types
115 for i in range(0, 2):
117 s = ["black", "white"][i]
121 c.append(Piece(s, 0, y, ["rook"]))
122 c.append(Piece(s, 1, y, ["knight"]))
123 c.append(Piece(s, 2, y, ["bishop"]))
124 k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
125 k.types_revealed[1] = True
126 k.current_type = "king"
129 c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
130 c.append(Piece(s, 5, y, ["bishop"]))
131 c.append(Piece(s, 6, y, ["knight"]))
132 c.append(Piece(s, 7, y, ["rook"]))
140 for x in range(0, w):
141 c.append(Piece(s, x, y, ["pawn"]))
144 types_left.update(piece_types)
145 del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
146 del types_left["unknown"] # We certainly don't want these!
149 self.grid[piece.x][piece.y] = piece
151 if len(piece.types) > 1:
153 if style == "agent": # Assign placeholder "unknown" secondary type
154 piece.types.append("unknown")
157 elif style == "quantum":
158 # The master allocates the secondary types
159 choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
160 types_left[choice] -= 1
161 if types_left[choice] <= 0:
162 del types_left[choice]
163 piece.types.append(choice)
164 elif style == "classical":
165 piece.types.append(piece.types[0])
166 piece.current_type = piece.types[0]
167 piece.types_revealed[1] = True
171 newboard = Board(master = False)
172 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
173 mypieces = self.pieces["white"] + self.pieces["black"]
175 for i in range(len(mypieces)):
176 newpieces[i].init_from_copy(mypieces[i])
179 def display_grid(self, window = None, grid_sz = [80,80]):
181 return # I was considering implementing a text only display, then I thought "Fuck that"
183 # The indentation is getting seriously out of hand...
184 for x in range(0, w):
185 for y in range(0, h):
187 c = pygame.Color(200,200,200)
189 c = pygame.Color(64,64,64)
190 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
192 def display_pieces(self, window = None, grid_sz = [80,80]):
195 for p in self.pieces["white"] + self.pieces["black"]:
196 p.draw(window, grid_sz, self.style)
198 # Draw the board in a pygame window
199 def display(self, window = None):
200 self.display_grid(window)
201 self.display_pieces(window)
209 if self.grid[x][y] == None:
211 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
212 raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
214 # Select a piece on the board (colour is the colour of whoever is doing the selecting)
215 def select(self, x,y, colour=None):
216 if not self.on_board(x, y): # Get on board everyone!
217 raise Exception("BOUNDS")
219 piece = self.grid[x][y]
221 raise Exception("EMPTY")
223 if colour != None and piece.colour != colour:
224 raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
226 # I'm not quite sure why I made this return a string, but screw logical design
227 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
230 # Update the board when a piece has been selected
231 # "type" is apparently reserved, so I'll use "state"
232 def update_select(self, x, y, type_index, state):
233 piece = self.grid[x][y]
234 if piece.types[type_index] == "unknown":
235 if not state in self.unrevealed_types[piece.colour].keys():
236 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
237 self.unrevealed_types[piece.colour][state] -= 1
238 if self.unrevealed_types[piece.colour][state] <= 0:
239 del self.unrevealed_types[piece.colour][state]
241 piece.types[type_index] = state
242 piece.types_revealed[type_index] = True
243 piece.current_type = state
245 if len(self.possible_moves(piece)) <= 0:
246 piece.deselect() # Piece can't move; deselect it
248 # Update the board when a piece has been moved
249 def update_move(self, x, y, x2, y2):
250 piece = self.grid[x][y]
251 self.grid[x][y] = None
252 taken = self.grid[x2][y2]
254 if taken.current_type == "king":
255 self.king[taken.colour] = None
256 self.pieces[taken.colour].remove(taken)
257 self.grid[x2][y2] = piece
261 # If the piece is a pawn, and it reaches the final row, it becomes a queen
262 # I know you are supposed to get a choice
263 # But that would be effort
264 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
265 if self.style == "classical":
266 piece.types[0] = "queen"
267 piece.types[1] = "queen"
269 piece.types[piece.choice] = "queen"
270 piece.current_type = "queen"
272 piece.deselect() # Uncollapse (?) the wavefunction!
275 # Update the board from a string
276 # Guesses what to do based on the format of the string
277 def update(self, result):
278 #print "Update called with \"" + str(result) + "\""
279 # String always starts with 'x y'
281 s = result.split(" ")
282 [x,y] = map(int, s[0:2])
284 raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
286 piece = self.grid[x][y]
288 raise Exception("EMPTY")
290 # If a piece is being moved, the third token is '->'
291 # We could get away with just using four integers, but that wouldn't look as cool
293 # Last two tokens are the destination
295 [x2,y2] = map(int, s[3:])
297 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
299 # Move the piece (take opponent if possible)
300 self.update_move(x, y, x2, y2)
303 # Otherwise we will just assume a piece has been selected
305 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
306 state = s[3] # The last token is a string identifying the type
308 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
311 self.update_select(x, y, type_index, state)
315 # Gets each piece that could reach the given square and the probability that it could reach that square
316 # Will include allied pieces that defend the attacker
317 def coverage(self, x, y, colour = None, reject_allied = True):
321 pieces = self.pieces["white"] + self.pieces["black"]
323 pieces = self.pieces[colour]
326 prob = self.probability_grid(p, reject_allied)[x][y]
328 result.update({p : prob})
337 # Associates each square with a probability that the piece could move into it
338 # Look, I'm doing all the hard work for you here...
339 def probability_grid(self, p, reject_allied = True):
341 result = [[0.0] * w for _ in range(h)]
342 if not isinstance(p, Piece):
345 if p.current_type != "unknown":
346 #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
347 for point in self.possible_moves(p, reject_allied):
348 result[point[0]][point[1]] = 1.0
352 for i in range(len(p.types)):
355 if t == "unknown" or p.types_revealed[i] == False:
357 for t2 in self.unrevealed_types[p.colour].keys():
358 total_types += self.unrevealed_types[p.colour][t2]
360 for t2 in self.unrevealed_types[p.colour].keys():
361 prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
363 for point in self.possible_moves(p, reject_allied):
364 result[point[0]][point[1]] += prob2 * prob
368 for point in self.possible_moves(p, reject_allied):
369 result[point[0]][point[1]] += prob
372 p.current_type = "unknown"
375 def prob_is_type(self, p, state):
378 for i in range(len(p.types)):
383 if t == "unknown" or p.types_revealed[i] == False:
385 for t2 in self.unrevealed_types[p.colour].keys():
386 total_prob += self.unrevealed_types[p.colour][t2]
387 for t2 in self.unrevealed_types[p.colour].keys():
389 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
393 # Get all squares that the piece could move into
394 # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
395 # reject_allied indicates whether squares occupied by allied pieces will be removed
396 # (set to false to check for defense)
397 def possible_moves(self, p, reject_allied = True):
403 if p.current_type == "unknown":
404 raise Exception("SANITY: Piece state unknown")
405 # The below commented out code causes things to break badly
410 # result += self.possible_moves(p)
411 #p.current_type = "unknown"
414 if p.current_type == "king":
415 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]]
416 elif p.current_type == "queen":
417 for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
418 result += self.scan(p.x, p.y, d[0], d[1])
419 elif p.current_type == "bishop":
420 for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
421 result += self.scan(p.x, p.y, d[0], d[1])
422 elif p.current_type == "rook":
423 for d in [[-1,0],[1,0],[0,-1],[0,1]]:
424 result += self.scan(p.x, p.y, d[0], d[1])
425 elif p.current_type == "knight":
426 # I would use two lines, but I'm not sure how python likes that
427 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]]
428 elif p.current_type == "pawn":
429 if p.colour == "white":
431 # Pawn can't move forward into occupied square
432 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
433 result = [[p.x,p.y-1]]
434 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
435 if not self.on_board(f[0], f[1]):
437 if self.grid[f[0]][f[1]] != None: # Pawn can take diagonally
440 # Slightly embarrassing if the pawn jumps over someone on its first move...
441 if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
442 result.append([p.x, p.y-2])
444 # Vice versa for the black pawn
445 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
446 result = [[p.x,p.y+1]]
448 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
449 if not self.on_board(f[0], f[1]):
451 if self.grid[f[0]][f[1]] != None:
452 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
455 if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
456 result.append([p.x, p.y+2])
458 #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
460 # Remove illegal moves
461 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
462 for point in result[:]:
464 if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
465 result.remove(point) # Remove locations outside the board
467 g = self.grid[point[0]][point[1]]
469 if g != None and (g.colour == p.colour and reject_allied == True):
470 result.remove(point) # Remove allied pieces
476 # Scans in a direction until it hits a piece, returns all squares in the line
477 # (includes the final square (which contains a piece), but not the original square)
478 def scan(self, x, y, vx, vy):
486 if not self.on_board(xx, yy):
490 g = self.grid[xx][yy]
498 # I typed the full statement about 30 times before writing this function...
499 def on_board(self, x, y):
500 return (x >= 0 and x < w) and (y >= 0 and y < h)
507 agent_timeout = -1.0 # Timeout in seconds for AI players to make moves
508 # WARNING: Won't work for windows based operating systems
510 if platform.system() == "Windows":
511 agent_timeout = -1 # Hence this
513 # A player who can't play
515 def __init__(self, name, colour):
519 # Player that runs from another process
520 class AgentPlayer(Player):
523 def __init__(self, name, colour):
524 Player.__init__(self, name, colour)
525 self.p = subprocess.Popen(name, stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
527 self.send_message(colour)
529 def send_message(self, s):
530 if agent_timeout > 0.0:
531 ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
533 ready = [self.p.stdin]
534 if self.p.stdin in ready:
535 #print "Writing to p.stdin"
537 self.p.stdin.write(s + "\n")
539 raise Exception("UNRESPONSIVE")
541 raise Exception("UNRESPONSIVE")
543 def get_response(self):
544 if agent_timeout > 0.0:
545 ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
547 ready = [self.p.stdout]
548 if self.p.stdout in ready:
549 #print "Reading from p.stdout"
551 return self.p.stdout.readline().strip("\r\n")
552 except: # Exception, e:
553 raise Exception("UNRESPONSIVE")
555 raise Exception("UNRESPONSIVE")
559 self.send_message("SELECTION?")
560 line = self.get_response()
563 result = map(int, line.split(" "))
565 raise Exception("GIBBERISH \"" + str(line) + "\"")
568 def update(self, result):
569 #print "Update " + str(result) + " called for AgentPlayer"
570 self.send_message(result)
575 self.send_message("MOVE?")
576 line = self.get_response()
579 result = map(int, line.split(" "))
581 raise Exception("GIBBERISH \"" + str(line) + "\"")
584 def quit(self, final_result):
586 self.send_message("QUIT " + final_result)
590 # So you want to be a player here?
591 class HumanPlayer(Player):
592 def __init__(self, name, colour):
593 Player.__init__(self, name, colour)
595 # Select your preferred account
597 if isinstance(graphics, GraphicsThread):
598 # Basically, we let the graphics thread do some shit and then return that information to the game thread
599 graphics.cond.acquire()
600 # We wait for the graphics thread to select a piece
601 while graphics.stopped() == False and graphics.state["select"] == None:
602 graphics.cond.wait() # The difference between humans and machines is that humans sleep
603 select = graphics.state["select"]
606 graphics.cond.release()
607 if graphics.stopped():
609 return [select.x, select.y]
611 # Since I don't display the board in this case, I'm not sure why I filled it in...
613 sys.stdout.write("SELECTION?\n")
615 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
617 sys.stderr.write("ILLEGAL GIBBERISH\n")
619 # It's your move captain
621 if isinstance(graphics, GraphicsThread):
622 graphics.cond.acquire()
623 while graphics.stopped() == False and graphics.state["dest"] == None:
625 graphics.cond.release()
627 return graphics.state["dest"]
631 sys.stdout.write("MOVE?\n")
633 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
635 sys.stderr.write("ILLEGAL GIBBERISH\n")
638 # Are you sure you want to quit?
639 def quit(self, final_result):
641 sys.stdout.write("QUIT " + final_result + "\n")
643 # Completely useless function
644 def update(self, result):
645 if isinstance(graphics, GraphicsThread):
648 sys.stdout.write(result + "\n")
651 # Player that makes random moves
652 class AgentRandom(Player):
653 def __init__(self, name, colour):
654 Player.__init__(self, name, colour)
657 self.board = Board(style = "agent")
661 self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
663 # Check that the piece has some possibility to move
664 tmp = self.choice.current_type
665 if tmp == "unknown": # For unknown pieces, try both types
666 for t in self.choice.types:
669 self.choice.current_type = t
670 all_moves += self.board.possible_moves(self.choice)
672 all_moves = self.board.possible_moves(self.choice)
673 self.choice.current_type = tmp
674 if len(all_moves) > 0:
676 return [self.choice.x, self.choice.y]
679 moves = self.board.possible_moves(self.choice)
680 move = moves[random.randint(0, len(moves)-1)]
683 def update(self, result):
684 #sys.stderr.write(sys.argv[0] + " : Update board for AgentRandom\n")
685 self.board.update(result)
688 def quit(self, final_result):
692 # --- player.py --- #
693 import multiprocessing
695 # Hacky alternative to using select for timing out players
697 # WARNING: Do not wrap around HumanPlayer or things breakify
699 class Sleeper(multiprocessing.Process):
700 def __init__(self, timeout):
701 multiprocessing.Process.__init__(self)
702 self.timeout = timeout
705 time.sleep(self.timeout)
708 class Worker(multiprocessing.Process):
709 def __init__(self, function, args, q):
710 multiprocessing.Process.__init__(self)
711 self.function = function
716 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args)
717 self.q.put(self.function(*self.args))
721 def TimeoutFunction(function, args, timeout):
722 q = multiprocessing.Queue()
723 w = Worker(function, args, q)
727 while True: # Busy loop of crappyness
732 #print "TimeoutFunction gets " + str(result)
734 elif not s.is_alive():
737 raise Exception("UNRESPONSIVE")
742 # A player that wraps another player and times out its moves
744 # A (crappy) alternative to the use of select()
745 class TimeoutPlayer(Player):
746 def __init__(self, base_player, timeout):
747 Player.__init__(self, base_player.name, base_player.colour)
748 self.base_player = base_player
749 self.timeout = timeout
752 return TimeoutFunction(self.base_player.select, [], self.timeout)
756 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
758 def update(self, result):
759 return TimeoutFunction(self.base_player.update, [result], self.timeout)
761 def quit(self, final_result):
762 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
763 # --- timeout_player.py --- #
767 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
768 network_timeout_delay = 1.0 # Maximum time between two characters being received
771 def __init__(self, colour, address = None):
772 self.socket = socket.socket()
773 #self.socket.setblocking(0)
775 if colour == "white":
782 # print str(self) + " listens on port " + str(self.port)
785 self.host = socket.gethostname()
786 self.socket.bind((self.host, self.port))
787 self.socket.listen(5)
789 self.src, self.address = self.socket.accept()
790 self.src.send("ok\n")
791 if self.get_response() == "QUIT":
795 self.socket.connect((address, self.port))
796 self.src = self.socket
797 self.src.send("ok\n")
798 if self.get_response() == "QUIT":
801 def get_response(self):
802 # Timeout the start of the message (first character)
803 if network_timeout_start > 0.0:
804 ready = select.select([self.src], [], [], network_timeout_start)[0]
807 if self.src in ready:
810 raise Exception("UNRESPONSIVE")
813 while s[len(s)-1] != '\n':
814 # Timeout on each character in the message
815 if network_timeout_delay > 0.0:
816 ready = select.select([self.src], [], [], network_timeout_delay)[0]
819 if self.src in ready:
820 s += self.src.recv(1)
822 raise Exception("UNRESPONSIVE")
824 return s.strip(" \r\n")
826 def send_message(self,s):
827 if network_timeout_start > 0.0:
828 ready = select.select([], [self.src], [], network_timeout_start)[1]
832 if self.src in ready:
833 self.src.send(s + "\n")
835 raise Exception("UNRESPONSIVE")
837 def check_quit(self, s):
841 game.final_result = " ".join(s[1:]) + " " + str(opponent(self.colour))
847 class NetworkSender(Player,Network):
848 def __init__(self, base_player, address = None):
849 self.base_player = base_player
850 Player.__init__(self, base_player.name, base_player.colour)
852 self.address = address
855 Network.__init__(self, self.base_player.colour, self.address)
860 [x,y] = self.base_player.select()
861 choice = self.board.grid[x][y]
862 s = str(x) + " " + str(y)
863 #print str(self) + ".select sends " + s
868 [x,y] = self.base_player.get_move()
869 s = str(x) + " " + str(y)
870 #print str(self) + ".get_move sends " + s
875 self.base_player.update(s)
877 [x,y] = map(int, s[0:2])
878 selected = self.board.grid[x][y]
879 if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
882 if selected.types_revealed[i] == True:
883 s += " " + str(selected.types[i])
886 #print str(self) + ".update sends " + s
890 def quit(self, final_result):
891 self.base_player.quit(final_result)
892 #self.src.send("QUIT " + str(final_result) + "\n")
895 class NetworkReceiver(Player,Network):
896 def __init__(self, colour, address=None):
898 Player.__init__(self, address, colour)
900 self.address = address
905 Network.__init__(self, self.colour, self.address)
910 s = self.get_response()
911 #print str(self) + ".select gets " + s
912 [x,y] = map(int,s.split(" "))
913 if x == -1 and y == -1:
914 #print str(self) + ".select quits the game"
916 game.final_state = "network terminated " + self.colour
920 s = self.get_response()
921 #print str(self) + ".get_move gets " + s
922 [x,y] = map(int,s.split(" "))
923 if x == -1 and y == -1:
924 #print str(self) + ".get_move quits the game"
926 game.final_state = "network terminated " + self.colour
930 def update(self, result):
932 result = result.split(" ")
933 [x,y] = map(int, result[0:2])
934 selected = self.board.grid[x][y]
935 if selected != None and selected.colour == self.colour and len(result) > 2 and not "->" in result:
936 s = self.get_response()
937 #print str(self) + ".update - receives " + str(s)
939 selected.choice = int(s[2])
941 selected.types[i] = str(s[3+i])
942 if s[3+i] == "unknown":
943 selected.types_revealed[i] = False
945 selected.types_revealed[i] = True
946 selected.current_type = selected.types[selected.choice]
949 #print str(self) + ".update - ignore result " + str(result)
952 def quit(self, final_result):
955 # --- network.py --- #
958 # A thread that can be stopped!
959 # Except it can only be stopped if it checks self.stopped() periodically
960 # So it can sort of be stopped
961 class StoppableThread(threading.Thread):
963 threading.Thread.__init__(self)
964 self._stop = threading.Event()
970 return self._stop.isSet()
971 # --- thread_util.py --- #
973 # A thread that runs the game
974 class GameThread(StoppableThread):
975 def __init__(self, board, players):
976 StoppableThread.__init__(self)
978 self.players = players
979 self.state = {"turn" : None} # The game state
980 self.error = 0 # Whether the thread exits with an error
981 self.lock = threading.RLock() #lock for access of self.state
982 self.cond = threading.Condition() # conditional for some reason, I forgot
983 self.final_result = ""
985 # Run the game (run in new thread with start(), run in current thread with run())
988 while not self.stopped():
990 for p in self.players:
992 if isinstance(p, NetworkSender):
993 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
995 self.state["turn"] = p
998 [x,y] = p.select() # Player selects a square
1005 result = self.board.select(x, y, colour = p.colour)
1006 for p2 in self.players:
1007 p2.update(result) # Inform players of what happened
1011 target = self.board.grid[x][y]
1012 if isinstance(graphics, GraphicsThread):
1014 graphics.state["moves"] = self.board.possible_moves(target)
1015 graphics.state["select"] = target
1017 time.sleep(turn_delay)
1020 if len(self.board.possible_moves(target)) == 0:
1021 #print "Piece cannot move"
1023 if isinstance(graphics, GraphicsThread):
1025 graphics.state["moves"] = None
1026 graphics.state["select"] = None
1027 graphics.state["dest"] = None
1031 [x2,y2] = p.get_move() # Player selects a destination
1038 result = self.board.update_move(x, y, x2, y2)
1039 for p2 in self.players:
1040 p2.update(str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)) # Inform players of what happened
1042 if isinstance(graphics, GraphicsThread):
1044 graphics.state["moves"] = [[x2,y2]]
1046 time.sleep(turn_delay)
1048 if isinstance(graphics, GraphicsThread):
1050 graphics.state["select"] = None
1051 graphics.state["dest"] = None
1052 graphics.state["moves"] = None
1054 # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
1055 # except Exception,e:
1056 # result = e.message
1057 # #sys.stderr.write(result + "\n")
1061 # self.final_result = self.state["turn"].colour + " " + e.message
1063 if self.board.king["black"] == None:
1064 if self.board.king["white"] == None:
1066 self.final_result = self.state["turn"].colour + " DRAW"
1069 self.final_result = "white"
1071 elif self.board.king["white"] == None:
1073 self.final_result = "black"
1081 for p2 in self.players:
1082 p2.quit(self.final_result)
1089 def opponent(colour):
1090 if colour == "white":
1098 # Dictionary that stores the unicode character representations of the different pieces
1099 # Chess was clearly the reason why unicode was invented
1100 # For some reason none of the pygame chess implementations I found used them!
1101 piece_char = {"white" : {"king" : u'\u2654',
1102 "queen" : u'\u2655',
1104 "bishop" : u'\u2657',
1105 "knight" : u'\u2658',
1108 "black" : {"king" : u'\u265A',
1109 "queen" : u'\u265B',
1111 "bishop" : u'\u265D',
1112 "knight" : u'\u265E',
1116 images = {"white" : {}, "black" : {}}
1117 small_images = {"white" : {}, "black" : {}}
1119 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
1121 # Get the font sizes
1122 l_size = 5*(grid_sz[0] / 8)
1123 s_size = 3*(grid_sz[0] / 8)
1125 for c in piece_char.keys():
1128 for p in piece_char[c].keys():
1129 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
1130 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})
1132 for p in piece_char[c].keys():
1133 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1134 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1135 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1136 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1139 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
1140 if not os.path.exists(image_dir):
1141 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
1142 for c in piece_char.keys():
1143 for p in piece_char[c].keys():
1144 images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
1145 small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
1146 # --- images.py --- #
1157 # A thread to make things pretty
1158 class GraphicsThread(StoppableThread):
1159 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1160 StoppableThread.__init__(self)
1164 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1165 pygame.display.set_caption(title)
1167 #print "Initialised properly"
1169 self.grid_sz = grid_sz[:]
1170 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
1172 self.lock = threading.RLock()
1173 self.cond = threading.Condition()
1176 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
1178 #create_images(grid_sz)
1179 create_images(grid_sz)
1182 for c in images.keys():
1183 for p in images[c].keys():
1184 images[c][p] = images[c][p].convert(self.window)
1185 small_images[c][p] = small_images[c][p].convert(self.window)
1192 # On the run from the world
1195 while not self.stopped():
1197 #print "Display grid"
1198 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
1200 #print "Display overlay"
1203 #print "Display pieces"
1204 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
1206 pygame.display.flip()
1208 for event in pygame.event.get():
1209 if event.type == pygame.QUIT:
1210 if isinstance(game, GameThread):
1212 game.final_result = ""
1213 if game.state["turn"] != None:
1214 game.final_result = game.state["turn"].colour + " "
1215 game.final_result += "terminated"
1219 elif event.type == pygame.MOUSEBUTTONDOWN:
1220 self.mouse_down(event)
1221 elif event.type == pygame.MOUSEBUTTONUP:
1222 self.mouse_up(event)
1229 self.message("Game ends, result \""+str(game.final_result) + "\"")
1232 # Wake up anyone who is sleeping
1237 pygame.quit() # Time to say goodbye
1239 # Mouse release event handler
1240 def mouse_up(self, event):
1241 if event.button == 3:
1243 self.state["overlay"] = None
1244 elif event.button == 2:
1246 self.state["coverage"] = None
1248 # Mouse click event handler
1249 def mouse_down(self, event):
1250 if event.button == 1:
1251 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
1252 if isinstance(game, GameThread):
1254 p = game.state["turn"]
1259 if isinstance(p, HumanPlayer):
1261 s = self.board.grid[m[0]][m[1]]
1262 select = self.state["select"]
1264 if s != None and s.colour != p.colour:
1265 self.message("Wrong colour") # Look at all this user friendliness!
1268 # Notify human player of move
1271 self.state["select"] = s
1272 self.state["dest"] = None
1281 if self.state["moves"] == None:
1284 if not m in self.state["moves"]:
1285 self.message("Illegal Move") # I still think last year's mouse interface was adequate
1290 if self.state["dest"] == None:
1292 self.state["dest"] = m
1293 self.state["select"] = None
1294 self.state["moves"] = None
1297 elif event.button == 3:
1298 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1299 if isinstance(game, GameThread):
1301 p = game.state["turn"]
1306 if isinstance(p, HumanPlayer):
1308 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
1310 elif event.button == 2:
1311 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1312 if isinstance(game, GameThread):
1314 p = game.state["turn"]
1319 if isinstance(p, HumanPlayer):
1321 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
1326 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
1327 # Draw square over the selected piece
1329 select = self.state["select"]
1331 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
1332 square_img.fill(pygame.Color(0,255,0,64))
1333 self.window.blit(square_img, mp)
1334 # If a piece is selected, draw all reachable squares
1335 # (This quality user interface has been patented)
1337 m = self.state["moves"]
1339 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
1341 mp = [self.grid_sz[i] * move[i] for i in range(2)]
1342 self.window.blit(square_img, mp)
1343 # If a piece is overlayed, show all squares that it has a probability to reach
1345 m = self.state["overlay"]
1350 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
1351 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
1352 self.window.blit(square_img, mp)
1353 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
1354 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
1355 self.window.blit(text, mp)
1357 # If a square is selected, highlight all pieces that have a probability to reach it
1359 m = self.state["coverage"]
1362 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
1363 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
1364 self.window.blit(square_img, mp)
1365 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
1366 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
1367 self.window.blit(text, mp)
1368 # Draw a square where the mouse is
1369 # This also serves to indicate who's turn it is
1371 if isinstance(game, GameThread):
1373 turn = game.state["turn"]
1377 if isinstance(turn, HumanPlayer):
1378 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
1379 square_img.fill(pygame.Color(0,0,255,128))
1380 if turn.colour == "white":
1381 c = pygame.Color(255,255,255)
1383 c = pygame.Color(0,0,0)
1384 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
1385 self.window.blit(square_img, mp)
1387 # Message in a bottle
1388 def message(self, string, pos = None, colour = None, font_size = 20):
1389 #print "Drawing message..."
1390 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
1392 colour = pygame.Color(0,0,0)
1394 text = font.render(string, 1, colour)
1397 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
1398 s.fill(pygame.Color(128,128,128))
1400 tmp = self.window.get_size()
1403 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
1405 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
1408 rect = (pos[0], pos[1], text.get_width(), text.get_height())
1410 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
1411 self.window.blit(s, pos)
1412 self.window.blit(text, pos)
1414 pygame.display.flip()
1416 def getstr(self, prompt = None):
1417 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
1418 s.blit(self.window, (0,0))
1424 self.message(prompt)
1425 self.message(result, pos = (0, 1))
1428 for event in pygame.event.get():
1429 if event.type == pygame.QUIT:
1431 if event.type == pygame.KEYDOWN:
1432 if event.key == pygame.K_BACKSPACE:
1433 result = result[0:len(result)-1]
1434 self.window.blit(s, (0,0)) # Revert the display
1439 if event.unicode == '\r':
1442 result += str(event.unicode)
1447 # Function to pick a button
1448 def SelectButton(self, choices, prompt = None, font_size=20):
1450 #print "Select button called!"
1451 self.board.display_grid(self.window, self.grid_sz)
1453 self.message(prompt)
1454 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
1456 sz = self.window.get_size()
1459 for i in range(len(choices)):
1462 text = font.render(c, 1, pygame.Color(0,0,0))
1463 p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
1464 targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
1467 mp =pygame.mouse.get_pos()
1468 for i in range(len(choices)):
1470 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
1471 font_colour = pygame.Color(255,0,0)
1472 box_colour = pygame.Color(0,0,255,128)
1474 font_colour = pygame.Color(0,0,0)
1475 box_colour = pygame.Color(128,128,128)
1477 text = font.render(c, 1, font_colour)
1478 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
1480 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
1481 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
1482 self.window.blit(s, targets[i][0:2])
1485 pygame.display.flip()
1487 for event in pygame.event.get():
1488 if event.type == pygame.QUIT:
1490 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
1491 for i in range(len(targets)):
1493 if event.pos[0] > t[0] and event.pos[0] < t[2]:
1494 if event.pos[1] > t[1] and event.pos[1] < t[3]:
1496 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
1499 # Function to pick players in a nice GUI way
1500 def SelectPlayers(self, players = []):
1503 #print "SelectPlayers called"
1505 missing = ["white", "black"]
1507 missing.remove(p.colour)
1509 for colour in missing:
1512 choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
1514 players.append(HumanPlayer("human", colour))
1518 from tkFileDialog import askopenfilename
1519 root = Tkinter.Tk() # Need a root to make Tkinter behave
1520 root.withdraw() # Some sort of magic incantation
1521 path = askopenfilename(parent=root, initialdir="../agents",title=
1524 return self.SelectPlayers()
1525 players.append(make_player(path, colour))
1527 print "Exception was " + str(e.message)
1530 self.board.display_grid(self.window, self.grid_sz)
1531 pygame.display.flip()
1532 path = self.getstr(prompt = "Enter path:")
1537 return self.SelectPlayers()
1540 p = make_player(path, colour)
1542 self.board.display_grid(self.window, self.grid_sz)
1543 pygame.display.flip()
1544 self.message("Invalid path!")
1550 while address == "":
1551 self.board.display_grid(self.window, self.grid_sz)
1553 address = self.getstr(prompt = "Address? (leave blank for server)")
1560 map(int, address.split("."))
1562 self.board.display_grid(self.window, self.grid_sz)
1563 self.message("Invalid IPv4 address!")
1566 players.append(NetworkReceiver(colour, address))
1569 #print str(self) + ".SelectPlayers returns " + str(players)
1574 # --- graphics.py --- #
1575 #!/usr/bin/python -u
1577 # Do you know what the -u does? It unbuffers stdin and stdout
1578 # I can't remember why, but last year things broke without that
1581 UCC::Progcomp 2013 Quantum Chess game
1582 @author Sam Moore [SZM] "matches"
1583 @copyright The University Computer Club, Incorporated
1584 (ie: You can copy it for not for profit purposes)
1587 # system python modules or whatever they are called
1593 [game, graphics] = [None, None]
1595 def make_player(name, colour):
1597 if name[1:] == "human":
1598 return HumanPlayer(name, colour)
1599 s = name[1:].split(":")
1600 if s[0] == "network":
1604 return NetworkReceiver(colour, address)
1607 return AgentPlayer(name, colour)
1611 # The main function! It does the main stuff!
1614 # Apparently python will silently treat things as local unless you do this
1615 # Anyone who says "You should never use a global variable" can die in a fire
1620 global agent_timeout
1629 graphics_enabled = True
1633 while i < len(argv)-1:
1637 players.append(make_player(arg, colour))
1638 if colour == "white":
1640 elif colour == "black":
1643 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
1646 # Option parsing goes here
1647 if arg[1] == '-' and arg[2:] == "classical":
1649 elif arg[1] == '-' and arg[2:] == "quantum":
1651 elif (arg[1] == '-' and arg[2:] == "graphics"):
1652 graphics_enabled = not graphics_enabled
1653 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
1654 # Load game from file
1655 if len(arg[2:].split("=")) == 1:
1656 src_file = sys.stdout
1658 src_file = arg[2:].split("=")[1]
1659 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
1661 if len(arg[2:].split("=")) == 1:
1662 log_file = sys.stdout
1664 log_file = arg[2:].split("=")[1]
1665 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
1667 if len(arg[2:].split("=")) == 1:
1670 turn_delay = float(arg[2:].split("=")[1])
1672 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
1674 if len(arg[2:].split("=")) == 1:
1677 agent_timeout = float(arg[2:].split("=")[1])
1679 elif (arg[1] == '-' and arg[2:] == "help"):
1681 os.system("less data/help.txt") # The best help function
1686 board = Board(style)
1690 if graphics_enabled == True:
1692 graphics = GraphicsThread(board, grid_sz = [64,64]) # Construct a GraphicsThread!
1696 sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
1697 graphics_enabled = False
1699 # If there are no players listed, display a nice pretty menu
1700 if len(players) != 2:
1701 if graphics != None:
1702 players = graphics.SelectPlayers(players)
1704 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
1707 # If there are still no players, quit
1708 if players == None or len(players) != 2:
1709 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
1713 # Wrap NetworkSender players around original players if necessary
1714 for i in range(len(players)):
1715 if isinstance(players[i], NetworkReceiver):
1716 players[i].board = board # Network players need direct access to the board
1717 for j in range(len(players)):
1720 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
1722 players[j] = NetworkSender(players[j], players[i].address)
1723 players[j].board = board
1725 # Connect the networked players
1727 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
1728 if graphics != None:
1729 graphics.board.display_grid(graphics.window, graphics.grid_sz)
1730 graphics.message("Connecting to " + p.colour + " player...")
1734 # If using windows, select won't work; use horrible TimeoutPlayer hack
1735 if agent_timeout > 0 and platform.system() == "Windows":
1736 sys.stderr.write(sys.argv[0] + " : Warning - You are using Windows\n")
1737 sys.stderr.write(sys.argv[0] + " : - Timeouts will be implemented with a terrible hack.\n")
1739 for i in range(len(players)):
1740 if isinstance(players[i], AgentPlayer):
1741 players[i] = TimeoutPlayer(players[i], agent_timeout)
1743 # Could potentially wrap TimeoutPlayer around internal classes...
1744 # But that would suck
1750 # Construct a GameThread! Make it global! Damn the consequences!
1751 game = GameThread(board, players)
1755 if graphics != None:
1756 game.start() # This runs in a new thread
1759 return game.error + graphics.error
1764 # This is how python does a main() function...
1765 if __name__ == "__main__":
1766 sys.exit(main(sys.argv))
1768 # EOF - created from make on Mon Jan 28 22:52:28 WST 2013