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")
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 # +++ thread_util.py +++ #
661 # A thread that can be stopped!
662 # Except it can only be stopped if it checks self.stopped() periodically
663 # So it can sort of be stopped
664 class StoppableThread(threading.Thread):
666 threading.Thread.__init__(self)
667 self._stop = threading.Event()
673 return self._stop.isSet()
674 # --- thread_util.py --- #
677 # A thread that runs the game
678 class GameThread(StoppableThread):
679 def __init__(self, board, players):
680 StoppableThread.__init__(self)
682 self.players = players
683 self.state = {"turn" : None} # The game state
684 self.error = 0 # Whether the thread exits with an error
685 self.lock = threading.RLock() #lock for access of self.state
686 self.cond = threading.Condition() # conditional for some reason, I forgot
687 self.final_result = ""
689 # Run the game (run in new thread with start(), run in current thread with run())
692 while not self.stopped():
694 for p in self.players:
696 self.state["turn"] = p # "turn" contains the player who's turn it is
699 [x,y] = p.select() # Player selects a square
703 result = self.board.select(x, y, colour = p.colour)
704 for p2 in self.players:
705 p2.update(result) # Inform players of what happened
709 target = self.board.grid[x][y]
710 if isinstance(graphics, GraphicsThread):
712 graphics.state["moves"] = self.board.possible_moves(target)
713 graphics.state["select"] = target
715 time.sleep(turn_delay)
718 if len(self.board.possible_moves(target)) == 0:
719 #print "Piece cannot move"
721 if isinstance(graphics, GraphicsThread):
723 graphics.state["moves"] = None
724 graphics.state["select"] = None
725 graphics.state["dest"] = None
729 [x2,y2] = p.get_move() # Player selects a destination
736 result = self.board.update_move(x, y, x2, y2)
737 for p2 in self.players:
738 p2.update(str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)) # Inform players of what happened
740 if isinstance(graphics, GraphicsThread):
742 graphics.state["moves"] = [[x2,y2]]
744 time.sleep(turn_delay)
746 if isinstance(graphics, GraphicsThread):
748 graphics.state["select"] = None
749 graphics.state["dest"] = None
750 graphics.state["moves"] = None
752 # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
754 #result = "ILLEGAL " + e.message
755 #sys.stderr.write(result + "\n")
759 # self.final_result = self.state["turn"].colour + " " + "ILLEGAL"
761 if self.board.king["black"] == None:
762 if self.board.king["white"] == None:
764 self.final_result = "DRAW"
767 self.final_result = "white"
769 elif self.board.king["white"] == None:
771 self.final_result = "black"
779 for p2 in self.players:
780 p2.quit(self.final_result)
787 def opponent(colour):
788 if colour == "white":
793 # +++ graphics.py +++ #
796 # Dictionary that stores the unicode character representations of the different pieces
797 # Chess was clearly the reason why unicode was invented
798 # For some reason none of the pygame chess implementations I found used them!
799 piece_char = {"white" : {"king" : u'\u2654',
802 "bishop" : u'\u2657',
803 "knight" : u'\u2658',
806 "black" : {"king" : u'\u265A',
809 "bishop" : u'\u265D',
810 "knight" : u'\u265E',
814 images = {"white" : {}, "black" : {}}
815 small_images = {"white" : {}, "black" : {}}
817 # A thread to make things pretty
818 class GraphicsThread(StoppableThread):
819 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
820 StoppableThread.__init__(self)
824 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
825 pygame.display.set_caption(title)
826 self.grid_sz = grid_sz[:]
827 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
829 self.lock = threading.RLock()
830 self.cond = threading.Condition()
833 l_size = 5*(self.grid_sz[0] / 8)
834 s_size = 3*(self.grid_sz[0] / 8)
835 for p in piece_types.keys():
837 images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", l_size).render(piece_char[c][p], True,(0,0,0))})
838 small_images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", s_size).render(piece_char[c][p],True,(0,0,0))})
841 images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", l_size+1).render(piece_char["black"][p], True,(255,255,255))})
842 images[c][p].blit(pygame.font.Font("data/DejaVuSans.ttf", l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
843 small_images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", s_size+1).render(piece_char["black"][p],True,(255,255,255))})
844 small_images[c][p].blit(pygame.font.Font("data/DejaVuSans.ttf", s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
850 # On the run from the world
853 while not self.stopped():
855 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
859 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
861 pygame.display.flip()
863 for event in pygame.event.get():
864 if event.type == pygame.QUIT:
865 if isinstance(game, GameThread):
867 game.final_result = "terminated"
871 elif event.type == pygame.MOUSEBUTTONDOWN:
872 self.mouse_down(event)
873 elif event.type == pygame.MOUSEBUTTONUP:
881 self.message("Game ends, result \""+str(game.final_result) + "\"")
884 # Wake up anyone who is sleeping
889 pygame.quit() # Time to say goodbye
891 # Mouse release event handler
892 def mouse_up(self, event):
893 if event.button == 3:
895 self.state["overlay"] = None
896 elif event.button == 2:
898 self.state["coverage"] = None
900 # Mouse click event handler
901 def mouse_down(self, event):
902 if event.button == 1:
903 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
904 if isinstance(game, GameThread):
906 p = game.state["turn"]
911 if isinstance(p, HumanPlayer):
913 s = self.board.grid[m[0]][m[1]]
914 select = self.state["select"]
916 if s != None and s.colour != p.colour:
917 self.message("Wrong colour") # Look at all this user friendliness!
920 # Notify human player of move
923 self.state["select"] = s
924 self.state["dest"] = None
933 if self.state["moves"] == None:
936 if not m in self.state["moves"]:
937 self.message("Illegal Move") # I still think last year's mouse interface was adequate
942 if self.state["dest"] == None:
944 self.state["dest"] = m
945 self.state["select"] = None
946 self.state["moves"] = None
949 elif event.button == 3:
950 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
951 if isinstance(game, GameThread):
953 p = game.state["turn"]
958 if isinstance(p, HumanPlayer):
960 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
962 elif event.button == 2:
963 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
964 if isinstance(game, GameThread):
966 p = game.state["turn"]
971 if isinstance(p, HumanPlayer):
973 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
978 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
979 # Draw square over the selected piece
981 select = self.state["select"]
983 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
984 square_img.fill(pygame.Color(0,255,0,64))
985 self.window.blit(square_img, mp)
986 # If a piece is selected, draw all reachable squares
987 # (This quality user interface has been patented)
989 m = self.state["moves"]
991 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
993 mp = [self.grid_sz[i] * move[i] for i in range(2)]
994 self.window.blit(square_img, mp)
995 # If a piece is overlayed, show all squares that it has a probability to reach
997 m = self.state["overlay"]
1002 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
1003 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
1004 self.window.blit(square_img, mp)
1005 font = pygame.font.Font(None, 14)
1006 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
1007 self.window.blit(text, mp)
1009 # If a square is selected, highlight all pieces that have a probability to reach it
1011 m = self.state["coverage"]
1014 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
1015 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
1016 self.window.blit(square_img, mp)
1017 font = pygame.font.Font(None, 14)
1018 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
1019 self.window.blit(text, mp)
1020 # Draw a square where the mouse is
1021 # This also serves to indicate who's turn it is
1023 if isinstance(game, GameThread):
1025 turn = game.state["turn"]
1029 if isinstance(turn, HumanPlayer):
1030 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
1031 square_img.fill(pygame.Color(0,0,255,128))
1032 if turn.colour == "white":
1033 c = pygame.Color(255,255,255)
1035 c = pygame.Color(0,0,0)
1036 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
1037 self.window.blit(square_img, mp)
1039 # Message in a bottle
1040 def message(self, string, pos = None, colour = None, font_size = 32):
1041 font = pygame.font.Font(None, font_size)
1043 colour = pygame.Color(0,0,0)
1045 text = font.render(string, 1, colour)
1048 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
1049 s.fill(pygame.Color(128,128,128))
1051 tmp = self.window.get_size()
1054 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
1056 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
1059 rect = (pos[0], pos[1], text.get_width(), text.get_height())
1061 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
1062 self.window.blit(s, pos)
1063 self.window.blit(text, pos)
1065 pygame.display.flip()
1067 def getstr(self, prompt = None):
1072 self.message(prompt)
1073 self.message(result, pos = (0, 1))
1075 for event in pygame.event.get():
1076 if event.type == pygame.KEYDOWN:
1077 if chr(event.key) == '\r':
1079 result += str(chr(event.key))
1080 # --- graphics.py --- #
1082 #!/usr/bin/python -u
1084 # Do you know what the -u does? It unbuffers stdin and stdout
1085 # I can't remember why, but last year things broke without that
1088 UCC::Progcomp 2013 Quantum Chess game
1089 @author Sam Moore [SZM] "matches"
1090 @copyright The University Computer Club, Incorporated
1091 (ie: You can copy it for not for profit purposes)
1094 # system python modules or whatever they are called
1100 [game, graphics] = [None, None]
1103 # The main function! It does the main stuff!
1106 # Apparently python will silently treat things as local unless you do this
1107 # But (here's the fun part), only if you actually modify the variable.
1108 # For example, all those 'if graphics_enabled' conditions work in functions that never say it is global
1109 # Anyone who says "You should never use a global variable" can die in a fire
1113 # Magical argument parsing goes here
1115 players = [HumanPlayer("saruman", "white"), AgentRandom("sabbath", "black")]
1116 elif len(argv) == 2:
1117 players = [AgentPlayer(argv[1], "white"), HumanPlayer("shadow", "black"), ]
1118 elif len(argv) == 3:
1119 players = [AgentPlayer(argv[1], "white"), AgentPlayer(argv[2], "black")]
1121 # Construct the board!
1122 board = Board(style = "quantum")
1123 game = GameThread(board, players) # Construct a GameThread! Make it global! Damn the consequences!
1126 graphics = GraphicsThread(board, grid_sz = [64,64]) # Construct a GraphicsThread! I KNOW WHAT I'M DOING! BEAR WITH ME!
1127 game.start() # This runs in a new thread
1129 # print "Run game in main thread"
1130 # game.run() # Run game in the main thread (no need for joining)
1132 #except Exception, e:
1138 return game.error + graphics.error
1141 # This is how python does a main() function...
1142 if __name__ == "__main__":
1143 sys.exit(main(sys.argv))
1145 # EOF - created from update.sh on Wed Jan 23 22:01:52 WST 2013