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]):
48 # First draw the image corresponding to self.current_type
49 img = images[self.colour][self.current_type]
51 offset = [-rect.width/2,-3*rect.height/4]
52 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]))
55 # Draw the two possible types underneath the current_type image
56 for i in range(len(self.types)):
57 if self.types_revealed[i] == True:
58 img = small_images[self.colour][self.types[i]]
60 img = small_images[self.colour]["unknown"] # If the type hasn't been revealed, show a placeholder
64 offset = [-rect.width/2,-rect.height/2]
67 target = (self.x * grid_sz[0] + grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])
69 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])
71 window.blit(img, target) # Blit shit
73 # Collapses the wave function!
75 if self.current_type == "unknown":
76 self.choice = random.randint(0,1)
77 self.current_type = self.types[self.choice]
78 self.types_revealed[self.choice] = True
81 # Uncollapses (?) the wave function!
83 #print "Deselect called"
84 if (self.x + self.y) % 2 != 0:
85 if (self.types[0] != self.types[1]) or (self.types_revealed[0] == False or self.types_revealed[1] == False):
86 self.current_type = "unknown"
89 self.choice = 0 # Both the two types are the same
91 # The sad moment when you realise that you do not understand anything about a subject you studied for 4 years...
94 [w,h] = [8,8] # Width and height of board(s)
96 # Class to represent a quantum chess board
98 # Initialise; if master=True then the secondary piece types are assigned
99 # Otherwise, they are left as unknown
100 # So you can use this class in Agent programs, and fill in the types as they are revealed
101 def __init__(self, style="agent"):
103 self.pieces = {"white" : [], "black" : []}
104 self.grid = [[None] * w for _ in range(h)] # 2D List (you can get arrays in python, somehow, but they scare me)
105 self.unrevealed_types = {"white" : piece_types.copy(), "black" : piece_types.copy()}
106 self.king = {"white" : None, "black" : None} # We need to keep track of the king, because he is important
107 for c in ["black", "white"]:
108 del self.unrevealed_types[c]["unknown"]
110 # Add all the pieces with known primary types
111 for i in range(0, 2):
113 s = ["black", "white"][i]
117 c.append(Piece(s, 0, y, ["rook"]))
118 c.append(Piece(s, 1, y, ["knight"]))
119 c.append(Piece(s, 2, y, ["bishop"]))
120 k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
121 k.types_revealed[1] = True
122 k.current_type = "king"
125 c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
126 c.append(Piece(s, 5, y, ["bishop"]))
127 c.append(Piece(s, 6, y, ["knight"]))
128 c.append(Piece(s, 7, y, ["rook"]))
136 for x in range(0, w):
137 c.append(Piece(s, x, y, ["pawn"]))
140 types_left.update(piece_types)
141 del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
142 del types_left["unknown"] # We certainly don't want these!
145 self.grid[piece.x][piece.y] = piece
147 if len(piece.types) > 1:
149 if style == "agent": # Assign placeholder "unknown" secondary type
150 piece.types.append("unknown")
153 elif style == "quantum":
154 # The master allocates the secondary types
155 choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
156 types_left[choice] -= 1
157 if types_left[choice] <= 0:
158 del types_left[choice]
159 piece.types.append(choice)
160 elif style == "classical":
161 piece.types.append(piece.types[0])
162 piece.current_type = piece.types[0]
163 piece.types_revealed[1] = True
167 newboard = Board(master = False)
168 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
169 mypieces = self.pieces["white"] + self.pieces["black"]
171 for i in range(len(mypieces)):
172 newpieces[i].init_from_copy(mypieces[i])
175 def display_grid(self, window = None, grid_sz = [80,80]):
177 return # I was considering implementing a text only display, then I thought "Fuck that"
179 # The indentation is getting seriously out of hand...
180 for x in range(0, w):
181 for y in range(0, h):
183 c = pygame.Color(200,200,200)
185 c = pygame.Color(64,64,64)
186 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
188 def display_pieces(self, window = None, grid_sz = [80,80]):
191 for p in self.pieces["white"] + self.pieces["black"]:
192 p.draw(window, grid_sz)
194 # Draw the board in a pygame window
195 def display(self, window = None):
196 self.display_grid(window)
197 self.display_pieces(window)
205 if self.grid[x][y] == None:
207 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
208 raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
210 # Select a piece on the board (colour is the colour of whoever is doing the selecting)
211 def select(self, x,y, colour=None):
212 if not self.on_board(x, y): # Get on board everyone!
213 raise Exception("BOUNDS")
215 piece = self.grid[x][y]
217 raise Exception("EMPTY")
219 if colour != None and piece.colour != colour:
220 raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
222 # I'm not quite sure why I made this return a string, but screw logical design
223 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
226 # Update the board when a piece has been selected
227 # "type" is apparently reserved, so I'll use "state"
228 def update_select(self, x, y, type_index, state):
229 piece = self.grid[x][y]
230 if piece.types[type_index] == "unknown":
231 if not state in self.unrevealed_types[piece.colour].keys():
232 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
233 self.unrevealed_types[piece.colour][state] -= 1
234 if self.unrevealed_types[piece.colour][state] <= 0:
235 del self.unrevealed_types[piece.colour][state]
237 piece.types[type_index] = state
238 piece.types_revealed[type_index] = True
239 piece.current_type = state
241 if len(self.possible_moves(piece)) <= 0:
242 piece.deselect() # Piece can't move; deselect it
244 # Update the board when a piece has been moved
245 def update_move(self, x, y, x2, y2):
246 piece = self.grid[x][y]
247 self.grid[x][y] = None
248 taken = self.grid[x2][y2]
250 if taken.current_type == "king":
251 self.king[taken.colour] = None
252 self.pieces[taken.colour].remove(taken)
253 self.grid[x2][y2] = piece
257 # If the piece is a pawn, and it reaches the final row, it becomes a queen
258 # I know you are supposed to get a choice
259 # But that would be effort
260 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
261 if self.style == "classical":
262 piece.types[0] = "queen"
263 piece.types[1] = "queen"
265 piece.types[piece.choice] = "queen"
266 piece.current_type = "queen"
268 piece.deselect() # Uncollapse (?) the wavefunction!
271 # Update the board from a string
272 # Guesses what to do based on the format of the string
273 def update(self, result):
274 #print "Update called with \"" + str(result) + "\""
275 # String always starts with 'x y'
277 s = result.split(" ")
278 [x,y] = map(int, s[0:2])
280 raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
282 piece = self.grid[x][y]
284 raise Exception("EMPTY")
286 # If a piece is being moved, the third token is '->'
287 # We could get away with just using four integers, but that wouldn't look as cool
289 # Last two tokens are the destination
291 [x2,y2] = map(int, s[3:])
293 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
295 # Move the piece (take opponent if possible)
296 self.update_move(x, y, x2, y2)
299 # Otherwise we will just assume a piece has been selected
301 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
302 state = s[3] # The last token is a string identifying the type
304 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
307 self.update_select(x, y, type_index, state)
311 # Gets each piece that could reach the given square and the probability that it could reach that square
312 # Will include allied pieces that defend the attacker
313 def coverage(self, x, y, colour = None, reject_allied = True):
317 pieces = self.pieces["white"] + self.pieces["black"]
319 pieces = self.pieces[colour]
322 prob = self.probability_grid(p, reject_allied)[x][y]
324 result.update({p : prob})
333 # Associates each square with a probability that the piece could move into it
334 # Look, I'm doing all the hard work for you here...
335 def probability_grid(self, p, reject_allied = True):
337 result = [[0.0] * w for _ in range(h)]
338 if not isinstance(p, Piece):
341 if p.current_type != "unknown":
342 #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
343 for point in self.possible_moves(p, reject_allied):
344 result[point[0]][point[1]] = 1.0
348 for i in range(len(p.types)):
351 if t == "unknown" or p.types_revealed[i] == False:
353 for t2 in self.unrevealed_types[p.colour].keys():
354 total_types += self.unrevealed_types[p.colour][t2]
356 for t2 in self.unrevealed_types[p.colour].keys():
357 prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
359 for point in self.possible_moves(p, reject_allied):
360 result[point[0]][point[1]] += prob2 * prob
364 for point in self.possible_moves(p, reject_allied):
365 result[point[0]][point[1]] += prob
368 p.current_type = "unknown"
371 def prob_is_type(self, p, state):
374 for i in range(len(p.types)):
379 if t == "unknown" or p.types_revealed[i] == False:
381 for t2 in self.unrevealed_types[p.colour].keys():
382 total_prob += self.unrevealed_types[p.colour][t2]
383 for t2 in self.unrevealed_types[p.colour].keys():
385 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
389 # Get all squares that the piece could move into
390 # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
391 # reject_allied indicates whether squares occupied by allied pieces will be removed
392 # (set to false to check for defense)
393 def possible_moves(self, p, reject_allied = True):
399 if p.current_type == "unknown":
400 raise Exception("SANITY: Piece state unknown")
401 # The below commented out code causes things to break badly
406 # result += self.possible_moves(p)
407 #p.current_type = "unknown"
410 if p.current_type == "king":
411 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]]
412 elif p.current_type == "queen":
413 for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
414 result += self.scan(p.x, p.y, d[0], d[1])
415 elif p.current_type == "bishop":
416 for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
417 result += self.scan(p.x, p.y, d[0], d[1])
418 elif p.current_type == "rook":
419 for d in [[-1,0],[1,0],[0,-1],[0,1]]:
420 result += self.scan(p.x, p.y, d[0], d[1])
421 elif p.current_type == "knight":
422 # I would use two lines, but I'm not sure how python likes that
423 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]]
424 elif p.current_type == "pawn":
425 if p.colour == "white":
427 # Pawn can't move forward into occupied square
428 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
429 result = [[p.x,p.y-1]]
430 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
431 if not self.on_board(f[0], f[1]):
433 if self.grid[f[0]][f[1]] != None: # Pawn can take diagonally
436 # Slightly embarrassing if the pawn jumps over someone on its first move...
437 if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
438 result.append([p.x, p.y-2])
440 # Vice versa for the black pawn
441 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
442 result = [[p.x,p.y+1]]
444 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
445 if not self.on_board(f[0], f[1]):
447 if self.grid[f[0]][f[1]] != None:
448 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
451 if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
452 result.append([p.x, p.y+2])
454 #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
456 # Remove illegal moves
457 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
458 for point in result[:]:
460 if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
461 result.remove(point) # Remove locations outside the board
463 g = self.grid[point[0]][point[1]]
465 if g != None and (g.colour == p.colour and reject_allied == True):
466 result.remove(point) # Remove allied pieces
472 # Scans in a direction until it hits a piece, returns all squares in the line
473 # (includes the final square (which contains a piece), but not the original square)
474 def scan(self, x, y, vx, vy):
482 if not self.on_board(xx, yy):
486 g = self.grid[xx][yy]
494 # I typed the full statement about 30 times before writing this function...
495 def on_board(self, x, y):
496 return (x >= 0 and x < w) and (y >= 0 and y < h)
498 # +++ player.py +++ #
503 # A player who can't play
505 def __init__(self, name, colour):
509 # Player that runs from another process
510 class AgentPlayer(Player):
511 def __init__(self, name, colour):
512 Player.__init__(self, name, colour)
513 self.p = subprocess.Popen(name, stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=sys.stderr)
515 self.p.stdin.write(colour + "\n")
517 raise Exception("UNRESPONSIVE")
522 self.p.stdin.write("SELECTION?\n")
523 line = self.p.stdout.readline().strip("\r\n ")
525 # raise Exception("UNRESPONSIVE")
527 result = map(int, line.split(" "))
529 raise Exception("GIBBERISH \"" + str(line) + "\"")
532 def update(self, result):
533 #print "Update " + str(result) + " called for AgentPlayer"
535 self.p.stdin.write(result + "\n")
537 # raise Exception("UNRESPONSIVE")
542 self.p.stdin.write("MOVE?\n")
543 line = self.p.stdout.readline().strip("\r\n ")
545 raise Exception("UNRESPONSIVE")
547 result = map(int, line.split(" "))
549 raise Exception("GIBBERISH \"" + str(line) + "\"")
552 def quit(self, final_result):
554 self.p.stdin.write("QUIT " + final_result + "\n")
558 # So you want to be a player here?
559 class HumanPlayer(Player):
560 def __init__(self, name, colour):
561 Player.__init__(self, name, colour)
563 # Select your preferred account
565 if isinstance(graphics, GraphicsThread):
566 # Basically, we let the graphics thread do some shit and then return that information to the game thread
567 graphics.cond.acquire()
568 # We wait for the graphics thread to select a piece
569 while graphics.stopped() == False and graphics.state["select"] == None:
570 graphics.cond.wait() # The difference between humans and machines is that humans sleep
571 select = graphics.state["select"]
574 graphics.cond.release()
575 if graphics.stopped():
577 return [select.x, select.y]
579 # Since I don't display the board in this case, I'm not sure why I filled it in...
581 sys.stdout.write("SELECTION?\n")
583 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
585 sys.stderr.write("ILLEGAL GIBBERISH\n")
587 # It's your move captain
589 if isinstance(graphics, GraphicsThread):
590 graphics.cond.acquire()
591 while graphics.stopped() == False and graphics.state["dest"] == None:
593 graphics.cond.release()
595 return graphics.state["dest"]
599 sys.stdout.write("MOVE?\n")
601 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
603 sys.stderr.write("ILLEGAL GIBBERISH\n")
606 # Are you sure you want to quit?
607 def quit(self, final_result):
608 sys.stdout.write("QUIT " + final_result + "\n")
610 # Completely useless function
611 def update(self, result):
612 if isinstance(graphics, GraphicsThread):
615 sys.stdout.write(result + "\n")
618 # Player that makes random moves
619 class AgentRandom(Player):
620 def __init__(self, name, colour):
621 Player.__init__(self, name, colour)
624 self.board = Board(style = "agent")
628 self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
630 # Check that the piece has some possibility to move
631 tmp = self.choice.current_type
632 if tmp == "unknown": # For unknown pieces, try both types
633 for t in self.choice.types:
636 self.choice.current_type = t
637 all_moves += self.board.possible_moves(self.choice)
639 all_moves = self.board.possible_moves(self.choice)
640 self.choice.current_type = tmp
641 if len(all_moves) > 0:
643 return [self.choice.x, self.choice.y]
646 moves = self.board.possible_moves(self.choice)
647 move = moves[random.randint(0, len(moves)-1)]
650 def update(self, result):
651 #sys.stderr.write(sys.argv[0] + " : Update board for AgentRandom\n")
652 self.board.update(result)
655 def quit(self, final_result):
657 # --- player.py --- #
658 # +++ network.py +++ #
662 def __init__(self, colour, address = None):
663 self.socket = socket.socket()
665 if colour == "white":
673 self.host = 'localhost' #socket.gethostname()
674 self.socket.bind((self.host, self.port))
675 self.socket.listen(5)
677 self.src, self.address = self.socket.accept()
680 self.socket.connect(('localhost', self.port))
681 self.src = self.socket
685 while s[len(s)-1] != '\n':
686 s += self.src.recv(1)
692 class NetworkSender(Player,Network):
693 def __init__(self, base_player, board, address = None):
694 self.base_player = base_player
695 Player.__init__(self, base_player.name, base_player.colour)
696 Network.__init__(self, base_player.colour, address)
701 [x,y] = self.base_player.select()
702 choice = self.board.grid[x][y]
703 s = str(x) + " " + str(y)
704 print str(self) + ".select sends " + s
705 self.src.send(s + "\n")
709 [x,y] = self.base_player.get_move()
710 s = str(x) + " " + str(y)
711 print str(self) + ".get_move sends " + s
712 self.src.send(s + "\n")
716 self.base_player.update(s)
718 [x,y] = map(int, s[0:2])
719 selected = self.board.grid[x][y]
720 if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
723 if selected.types_revealed[i] == True:
724 s += " " + str(selected.types[i])
727 print str(self) + ".update sends " + s
728 self.src.send(s + "\n")
731 def quit(self, final_result):
732 self.base_player.quit(final_result)
735 class NetworkReceiver(Player,Network):
736 def __init__(self, colour, board, address=None):
738 Player.__init__(self, address, colour)
740 Network.__init__(self, colour, address)
746 s = self.getline().strip(" \r\n")
747 return map(int,s.split(" "))
749 s = self.getline().strip(" \r\n")
750 print str(self) + ".get_move gets " + s
751 return map(int, s.split(" "))
753 def update(self, result):
755 result = result.split(" ")
756 [x,y] = map(int, result[0:2])
757 selected = self.board.grid[x][y]
758 if selected != None and selected.colour == self.colour and len(result) > 2 and not "->" in result:
759 s = self.getline().strip(" \r\n")
760 print str(self) + ".update - receives " + str(s)
762 selected.choice = int(s[2])
764 selected.types[i] = str(s[3+i])
765 if s[3+i] == "unknown":
766 selected.types_revealed[i] = False
768 selected.types_revealed[i] = True
769 selected.current_type = selected.types[selected.choice]
771 print str(self) + ".update - ignore result " + str(result)
774 def quit(self, final_result):
777 # --- network.py --- #
778 # +++ thread_util.py +++ #
781 # A thread that can be stopped!
782 # Except it can only be stopped if it checks self.stopped() periodically
783 # So it can sort of be stopped
784 class StoppableThread(threading.Thread):
786 threading.Thread.__init__(self)
787 self._stop = threading.Event()
793 return self._stop.isSet()
794 # --- thread_util.py --- #
797 # A thread that runs the game
798 class GameThread(StoppableThread):
799 def __init__(self, board, players):
800 StoppableThread.__init__(self)
802 self.players = players
803 self.state = {"turn" : None} # The game state
804 self.error = 0 # Whether the thread exits with an error
805 self.lock = threading.RLock() #lock for access of self.state
806 self.cond = threading.Condition() # conditional for some reason, I forgot
807 self.final_result = ""
809 # Run the game (run in new thread with start(), run in current thread with run())
812 while not self.stopped():
814 for p in self.players:
816 if isinstance(p, NetworkSender):
817 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
819 self.state["turn"] = p
822 [x,y] = p.select() # Player selects a square
829 result = self.board.select(x, y, colour = p.colour)
830 for p2 in self.players:
831 p2.update(result) # Inform players of what happened
835 target = self.board.grid[x][y]
836 if isinstance(graphics, GraphicsThread):
838 graphics.state["moves"] = self.board.possible_moves(target)
839 graphics.state["select"] = target
841 time.sleep(turn_delay)
844 if len(self.board.possible_moves(target)) == 0:
845 #print "Piece cannot move"
847 if isinstance(graphics, GraphicsThread):
849 graphics.state["moves"] = None
850 graphics.state["select"] = None
851 graphics.state["dest"] = None
855 [x2,y2] = p.get_move() # Player selects a destination
862 result = self.board.update_move(x, y, x2, y2)
863 for p2 in self.players:
864 p2.update(str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)) # Inform players of what happened
866 if isinstance(graphics, GraphicsThread):
868 graphics.state["moves"] = [[x2,y2]]
870 time.sleep(turn_delay)
872 if isinstance(graphics, GraphicsThread):
874 graphics.state["select"] = None
875 graphics.state["dest"] = None
876 graphics.state["moves"] = None
878 # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
880 #result = "ILLEGAL " + e.message
881 #sys.stderr.write(result + "\n")
885 # self.final_result = self.state["turn"].colour + " " + "ILLEGAL"
887 if self.board.king["black"] == None:
888 if self.board.king["white"] == None:
890 self.final_result = "DRAW"
893 self.final_result = "white"
895 elif self.board.king["white"] == None:
897 self.final_result = "black"
905 for p2 in self.players:
906 p2.quit(self.final_result)
913 def opponent(colour):
914 if colour == "white":
919 # +++ graphics.py +++ #
922 # Dictionary that stores the unicode character representations of the different pieces
923 # Chess was clearly the reason why unicode was invented
924 # For some reason none of the pygame chess implementations I found used them!
925 piece_char = {"white" : {"king" : u'\u2654',
928 "bishop" : u'\u2657',
929 "knight" : u'\u2658',
932 "black" : {"king" : u'\u265A',
935 "bishop" : u'\u265D',
936 "knight" : u'\u265E',
940 images = {"white" : {}, "black" : {}}
941 small_images = {"white" : {}, "black" : {}}
943 # A thread to make things pretty
944 class GraphicsThread(StoppableThread):
945 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
946 StoppableThread.__init__(self)
950 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
951 pygame.display.set_caption(title)
952 self.grid_sz = grid_sz[:]
953 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
955 self.lock = threading.RLock()
956 self.cond = threading.Condition()
959 l_size = 5*(self.grid_sz[0] / 8)
960 s_size = 3*(self.grid_sz[0] / 8)
961 for p in piece_types.keys():
963 images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", l_size).render(piece_char[c][p], True,(0,0,0))})
964 small_images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", s_size).render(piece_char[c][p],True,(0,0,0))})
967 images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", l_size+1).render(piece_char["black"][p], True,(255,255,255))})
968 images[c][p].blit(pygame.font.Font("data/DejaVuSans.ttf", l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
969 small_images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", s_size+1).render(piece_char["black"][p],True,(255,255,255))})
970 small_images[c][p].blit(pygame.font.Font("data/DejaVuSans.ttf", s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
976 # On the run from the world
979 while not self.stopped():
981 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
985 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
987 pygame.display.flip()
989 for event in pygame.event.get():
990 if event.type == pygame.QUIT:
991 if isinstance(game, GameThread):
993 game.final_result = "terminated"
997 elif event.type == pygame.MOUSEBUTTONDOWN:
998 self.mouse_down(event)
999 elif event.type == pygame.MOUSEBUTTONUP:
1000 self.mouse_up(event)
1007 self.message("Game ends, result \""+str(game.final_result) + "\"")
1010 # Wake up anyone who is sleeping
1015 pygame.quit() # Time to say goodbye
1017 # Mouse release event handler
1018 def mouse_up(self, event):
1019 if event.button == 3:
1021 self.state["overlay"] = None
1022 elif event.button == 2:
1024 self.state["coverage"] = None
1026 # Mouse click event handler
1027 def mouse_down(self, event):
1028 if event.button == 1:
1029 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
1030 if isinstance(game, GameThread):
1032 p = game.state["turn"]
1037 if isinstance(p, HumanPlayer):
1039 s = self.board.grid[m[0]][m[1]]
1040 select = self.state["select"]
1042 if s != None and s.colour != p.colour:
1043 self.message("Wrong colour") # Look at all this user friendliness!
1046 # Notify human player of move
1049 self.state["select"] = s
1050 self.state["dest"] = None
1059 if self.state["moves"] == None:
1062 if not m in self.state["moves"]:
1063 self.message("Illegal Move") # I still think last year's mouse interface was adequate
1068 if self.state["dest"] == None:
1070 self.state["dest"] = m
1071 self.state["select"] = None
1072 self.state["moves"] = None
1075 elif event.button == 3:
1076 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1077 if isinstance(game, GameThread):
1079 p = game.state["turn"]
1084 if isinstance(p, HumanPlayer):
1086 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
1088 elif event.button == 2:
1089 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1090 if isinstance(game, GameThread):
1092 p = game.state["turn"]
1097 if isinstance(p, HumanPlayer):
1099 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
1104 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
1105 # Draw square over the selected piece
1107 select = self.state["select"]
1109 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
1110 square_img.fill(pygame.Color(0,255,0,64))
1111 self.window.blit(square_img, mp)
1112 # If a piece is selected, draw all reachable squares
1113 # (This quality user interface has been patented)
1115 m = self.state["moves"]
1117 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
1119 mp = [self.grid_sz[i] * move[i] for i in range(2)]
1120 self.window.blit(square_img, mp)
1121 # If a piece is overlayed, show all squares that it has a probability to reach
1123 m = self.state["overlay"]
1128 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
1129 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
1130 self.window.blit(square_img, mp)
1131 font = pygame.font.Font(None, 14)
1132 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
1133 self.window.blit(text, mp)
1135 # If a square is selected, highlight all pieces that have a probability to reach it
1137 m = self.state["coverage"]
1140 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
1141 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
1142 self.window.blit(square_img, mp)
1143 font = pygame.font.Font(None, 14)
1144 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
1145 self.window.blit(text, mp)
1146 # Draw a square where the mouse is
1147 # This also serves to indicate who's turn it is
1149 if isinstance(game, GameThread):
1151 turn = game.state["turn"]
1155 if isinstance(turn, HumanPlayer):
1156 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
1157 square_img.fill(pygame.Color(0,0,255,128))
1158 if turn.colour == "white":
1159 c = pygame.Color(255,255,255)
1161 c = pygame.Color(0,0,0)
1162 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
1163 self.window.blit(square_img, mp)
1165 # Message in a bottle
1166 def message(self, string, pos = None, colour = None, font_size = 32):
1167 font = pygame.font.Font(None, font_size)
1169 colour = pygame.Color(0,0,0)
1171 text = font.render(string, 1, colour)
1174 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
1175 s.fill(pygame.Color(128,128,128))
1177 tmp = self.window.get_size()
1180 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
1182 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
1185 rect = (pos[0], pos[1], text.get_width(), text.get_height())
1187 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
1188 self.window.blit(s, pos)
1189 self.window.blit(text, pos)
1191 pygame.display.flip()
1193 def getstr(self, prompt = None):
1198 self.message(prompt)
1199 self.message(result, pos = (0, 1))
1201 for event in pygame.event.get():
1202 if event.type == pygame.KEYDOWN:
1203 if chr(event.key) == '\r':
1205 result += str(chr(event.key))
1206 # --- graphics.py --- #
1208 #!/usr/bin/python -u
1210 # Do you know what the -u does? It unbuffers stdin and stdout
1211 # I can't remember why, but last year things broke without that
1214 UCC::Progcomp 2013 Quantum Chess game
1215 @author Sam Moore [SZM] "matches"
1216 @copyright The University Computer Club, Incorporated
1217 (ie: You can copy it for not for profit purposes)
1220 # system python modules or whatever they are called
1226 [game, graphics] = [None, None]
1229 # The main function! It does the main stuff!
1232 # Apparently python will silently treat things as local unless you do this
1233 # But (here's the fun part), only if you actually modify the variable.
1234 # For example, all those 'if graphics_enabled' conditions work in functions that never say it is global
1235 # Anyone who says "You should never use a global variable" can die in a fire
1239 # Magical argument parsing goes here
1240 # if len(argv) == 1:
1241 # players = [HumanPlayer("saruman", "white"), AgentRandom("sabbath", "black")]
1242 # elif len(argv) == 2:
1243 # players = [AgentPlayer(argv[1], "white"), HumanPlayer("shadow", "black"), ]
1244 # elif len(argv) == 3:
1245 # players = [AgentPlayer(argv[1], "white"), AgentPlayer(argv[2], "black")]
1248 board = Board(style = "quantum")
1249 # Construct the board!
1251 players = [NetworkSender(HumanPlayer("saruman", "white"), board), NetworkReceiver("black", board, 'localhost')]
1254 players = [NetworkReceiver("white", board, 'localhost'), NetworkSender(HumanPlayer("sabbath", "black"), board)]
1259 graphics = GraphicsThread(board, grid_sz = [64,64]) # Construct a GraphicsThread! I KNOW WHAT I'M DOING! BEAR WITH ME!
1264 game = GameThread(board, players) # Construct a GameThread! Make it global! Damn the consequences!
1265 game.start() # This runs in a new thread
1269 return game.error + graphics.error
1272 # This is how python does a main() function...
1273 if __name__ == "__main__":
1274 sys.exit(main(sys.argv))
1276 # EOF - created from update.sh on Thu Jan 24 03:04:38 WST 2013