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 def update(self, result):
522 # Player that runs from another process
523 class ExternalAgent(Player):
526 def __init__(self, name, colour):
527 Player.__init__(self, name, colour)
528 self.p = subprocess.Popen(name,bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,universal_newlines=True)
530 self.send_message(colour)
532 def send_message(self, s):
533 if agent_timeout > 0.0:
534 ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
536 ready = [self.p.stdin]
537 if self.p.stdin in ready:
538 #sys.stderr.write("Writing \'" + s + "\' to " + str(self.p) + "\n")
540 self.p.stdin.write(s + "\n")
542 raise Exception("UNRESPONSIVE")
544 raise Exception("TIMEOUT")
546 def get_response(self):
547 if agent_timeout > 0.0:
548 ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
550 ready = [self.p.stdout]
551 if self.p.stdout in ready:
552 #sys.stderr.write("Reading from " + str(self.p) + " 's stdout...\n")
554 result = self.p.stdout.readline().strip("\r\n")
555 #sys.stderr.write("Read \'" + result + "\' from " + str(self.p) + "\n")
557 except: # Exception, e:
558 raise Exception("UNRESPONSIVE")
560 raise Exception("TIMEOUT")
564 self.send_message("SELECTION?")
565 line = self.get_response()
568 result = map(int, line.split(" "))
570 raise Exception("GIBBERISH \"" + str(line) + "\"")
573 def update(self, result):
574 #print "Update " + str(result) + " called for AgentPlayer"
575 self.send_message(result)
580 self.send_message("MOVE?")
581 line = self.get_response()
584 result = map(int, line.split(" "))
586 raise Exception("GIBBERISH \"" + str(line) + "\"")
589 def quit(self, final_result):
591 self.send_message("QUIT " + final_result)
595 # So you want to be a player here?
596 class HumanPlayer(Player):
597 def __init__(self, name, colour):
598 Player.__init__(self, name, colour)
600 # Select your preferred account
602 if isinstance(graphics, GraphicsThread):
603 # Basically, we let the graphics thread do some shit and then return that information to the game thread
604 graphics.cond.acquire()
605 # We wait for the graphics thread to select a piece
606 while graphics.stopped() == False and graphics.state["select"] == None:
607 graphics.cond.wait() # The difference between humans and machines is that humans sleep
608 select = graphics.state["select"]
611 graphics.cond.release()
612 if graphics.stopped():
614 return [select.x, select.y]
616 # Since I don't display the board in this case, I'm not sure why I filled it in...
618 sys.stdout.write("SELECTION?\n")
620 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
622 sys.stderr.write("ILLEGAL GIBBERISH\n")
624 # It's your move captain
626 if isinstance(graphics, GraphicsThread):
627 graphics.cond.acquire()
628 while graphics.stopped() == False and graphics.state["dest"] == None:
630 graphics.cond.release()
632 return graphics.state["dest"]
636 sys.stdout.write("MOVE?\n")
638 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
640 sys.stderr.write("ILLEGAL GIBBERISH\n")
643 # Are you sure you want to quit?
644 def quit(self, final_result):
646 sys.stdout.write("QUIT " + final_result + "\n")
648 # Completely useless function
649 def update(self, result):
650 if isinstance(graphics, GraphicsThread):
653 sys.stdout.write(result + "\n")
656 # Default internal player (makes random moves)
657 class InternalAgent(Player):
658 def __init__(self, name, colour):
659 Player.__init__(self, name, colour)
662 self.board = Board(style = "agent")
666 def update(self, result):
668 self.board.update(result)
671 def quit(self, final_result):
674 class AgentRandom(InternalAgent):
675 def __init__(self, name, colour):
676 InternalAgent.__init__(self, name, colour)
680 self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
682 # Check that the piece has some possibility to move
683 tmp = self.choice.current_type
684 if tmp == "unknown": # For unknown pieces, try both types
685 for t in self.choice.types:
688 self.choice.current_type = t
689 all_moves += self.board.possible_moves(self.choice)
691 all_moves = self.board.possible_moves(self.choice)
692 self.choice.current_type = tmp
693 if len(all_moves) > 0:
695 return [self.choice.x, self.choice.y]
698 moves = self.board.possible_moves(self.choice)
699 move = moves[random.randint(0, len(moves)-1)]
703 # Terrible, terrible hacks
705 def run_agent(agent):
706 #sys.stderr.write(sys.argv[0] + " : Running agent " + str(agent) + "\n")
707 colour = sys.stdin.readline().strip(" \r\n")
708 agent.colour = colour
710 line = sys.stdin.readline().strip(" \r\n")
711 if line == "SELECTION?":
712 #sys.stderr.write(sys.argv[0] + " : Make selection\n")
713 [x,y] = agent.select() # Gets your agent's selection
714 #sys.stderr.write(sys.argv[0] + " : Selection was " + str(agent.choice) + "\n")
715 sys.stdout.write(str(x) + " " + str(y) + "\n")
716 elif line == "MOVE?":
717 #sys.stderr.write(sys.argv[0] + " : Make move\n")
718 [x,y] = agent.get_move() # Gets your agent's move
719 sys.stdout.write(str(x) + " " + str(y) + "\n")
720 elif line.split(" ")[0] == "QUIT":
721 #sys.stderr.write(sys.argv[0] + " : Quitting\n")
722 agent.quit(" ".join(line.split(" ")[1:])) # Quits the game
725 agent.update(line) # Updates agent.board
731 class ExternalWrapper(ExternalAgent):
732 def __init__(self, agent):
733 run = "python -u -c \"import sys;import os;from qchess import *;agent = " + agent.__class__.__name__ + "('" + agent.name + "','"+agent.colour+"');sys.exit(run_agent(agent))\""
735 ExternalAgent.__init__(self, run, agent.colour)
739 # --- player.py --- #
743 class AgentBishop(InternalAgent): # Inherits from InternalAgent (in qchess)
744 def __init__(self, name, colour):
745 InternalAgent.__init__(self, name, colour)
746 self.value = {"pawn" : 1, "bishop" : 3, "knight" : 3, "rook" : 5, "queen" : 9, "king" : 100, "unknown" : 4}
748 self.aggression = 2.0 # Multiplier for scoring due to aggressive actions
749 self.defence = 1.0 # Multiplier for scoring due to defensive actions
751 self.depth = 0 # Current depth
752 self.max_depth = 2 # Recurse this many times (for some reason, makes more mistakes when this is increased???)
753 self.recurse_for = -1 # Recurse for the best few moves each times (less than 0 = all moves)
755 for p in self.board.pieces["white"] + self.board.pieces["black"]:
757 p.selected_moves = None
761 def get_value(self, piece):
764 return float(self.value[piece.types[0]] + self.value[piece.types[1]]) / 2.0
766 # Score possible moves for the piece
768 def prioritise_moves(self, piece):
770 #sys.stderr.write(sys.argv[0] + " : " + str(self) + " prioritise called for " + str(piece) + "\n")
774 grid = self.board.probability_grid(piece)
775 #sys.stderr.write("\t Probability grid " + str(grid) + "\n")
779 if grid[x][y] < 0.3: # Throw out moves with < 30% probability
780 #sys.stderr.write("\tReject " + str(x) + "," + str(y) + " (" + str(grid[x][y]) + ")\n")
783 target = self.board.grid[x][y]
788 # Get total probability that the move is protected
789 [xx,yy] = [piece.x, piece.y]
790 [piece.x, piece.y] = [x, y]
791 self.board.grid[x][y] = piece
792 self.board.grid[xx][yy] = None
794 defenders = self.board.coverage(x, y, piece.colour, reject_allied = False)
796 for d in defenders.keys():
797 d_prob += defenders[d]
798 if len(defenders.keys()) > 0:
799 d_prob /= float(len(defenders.keys()))
804 # Get total probability that the move is threatened
805 attackers = self.board.coverage(x, y, opponent(piece.colour), reject_allied = False)
807 for a in attackers.keys():
808 a_prob += attackers[a]
809 if len(attackers.keys()) > 0:
810 a_prob /= float(len(attackers.keys()))
815 self.board.grid[x][y] = target
816 self.board.grid[xx][yy] = piece
817 [piece.x, piece.y] = [xx, yy]
821 value = self.aggression * (1.0 + d_prob) * self.get_value(target) - self.defence * (1.0 - d_prob) * a_prob * self.get_value(piece)
823 # Adjust score based on movement of piece out of danger
824 attackers = self.board.coverage(piece.x, piece.y, opponent(piece.colour))
826 for a in attackers.keys():
827 s_prob += attackers[a]
828 if len(attackers.keys()) > 0:
829 s_prob /= float(len(attackers.keys()))
833 value += self.defence * s_prob * self.get_value(piece)
835 # Adjust score based on probability that the move is actually possible
836 moves.append([[x, y], grid[x][y] * value])
838 moves.sort(key = lambda e : e[1], reverse = True)
839 #sys.stderr.write(sys.argv[0] + ": Moves for " + str(piece) + " are " + str(moves) + "\n")
841 piece.last_moves = moves
842 piece.selected_moves = None
849 def select_best(self, colour):
853 for p in self.board.pieces[colour]:
854 self.choice = p # Temporarily pick that piece
855 m = self.prioritise_moves(p)
857 all_moves.update({p : m[0]})
859 if len(all_moves.items()) <= 0:
863 opts = all_moves.items()
864 opts.sort(key = lambda e : e[1][1], reverse = True)
866 if self.depth >= self.max_depth:
870 if self.recurse_for >= 0:
871 opts = opts[0:self.recurse_for]
872 #sys.stderr.write(sys.argv[0] + " : Before recurse, options are " + str(opts) + "\n")
874 # Take the best few moves, and recurse
875 for choice in opts[0:self.recurse_for]:
876 [xx,yy] = [choice[0].x, choice[0].y] # Remember position
877 [nx,ny] = choice[1][0] # Target
878 [choice[0].x, choice[0].y] = [nx, ny] # Set position
879 target = self.board.grid[nx][ny] # Remember piece in spot
880 self.board.grid[xx][yy] = None # Remove piece
881 self.board.grid[nx][ny] = choice[0] # Replace with moving piece
884 best_enemy_move = self.select_best(opponent(choice[0].colour))
885 choice[1][1] -= best_enemy_move[1][1] / float(self.depth + 1.0)
887 [choice[0].x, choice[0].y] = [xx, yy] # Restore position
888 self.board.grid[nx][ny] = target # Restore taken piece
889 self.board.grid[xx][yy] = choice[0] # Restore moved piece
893 opts.sort(key = lambda e : e[1][1], reverse = True)
894 #sys.stderr.write(sys.argv[0] + " : After recurse, options are " + str(opts) + "\n")
901 # Returns [x,y] of selected piece
903 #sys.stderr.write("Getting choice...")
904 self.choice = self.select_best(self.colour)[0]
905 #sys.stderr.write(" Done " + str(self.choice)+"\n")
906 return [self.choice.x, self.choice.y]
908 # Returns [x,y] of square to move selected piece into
910 #sys.stderr.write("Choice is " + str(self.choice) + "\n")
911 self.choice.selected_moves = self.choice.last_moves
912 moves = self.prioritise_moves(self.choice)
916 return InternalAgent.get_move(self)
918 # --- agent_bishop.py --- #
919 import multiprocessing
921 # Hacky alternative to using select for timing out players
923 # WARNING: Do not wrap around HumanPlayer or things breakify
924 # WARNING: Do not use in general or things breakify
926 class Sleeper(multiprocessing.Process):
927 def __init__(self, timeout):
928 multiprocessing.Process.__init__(self)
929 self.timeout = timeout
932 time.sleep(self.timeout)
935 class Worker(multiprocessing.Process):
936 def __init__(self, function, args, q):
937 multiprocessing.Process.__init__(self)
938 self.function = function
943 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args)
944 self.q.put(self.function(*self.args))
948 def TimeoutFunction(function, args, timeout):
949 q = multiprocessing.Queue()
950 w = Worker(function, args, q)
954 while True: # Busy loop of crappyness
959 #print "TimeoutFunction gets " + str(result)
961 elif not s.is_alive():
964 raise Exception("TIMEOUT")
969 # A player that wraps another player and times out its moves
971 # A (crappy) alternative to the use of select()
972 class TimeoutPlayer(Player):
973 def __init__(self, base_player, timeout):
974 Player.__init__(self, base_player.name, base_player.colour)
975 self.base_player = base_player
976 self.timeout = timeout
979 return TimeoutFunction(self.base_player.select, [], self.timeout)
983 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
985 def update(self, result):
986 return TimeoutFunction(self.base_player.update, [result], self.timeout)
988 def quit(self, final_result):
989 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
990 # --- timeout_player.py --- #
994 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
995 network_timeout_delay = 1.0 # Maximum time between two characters being received
998 def __init__(self, colour, address = None):
999 self.socket = socket.socket()
1000 #self.socket.setblocking(0)
1002 if colour == "white":
1009 # print str(self) + " listens on port " + str(self.port)
1012 self.host = socket.gethostname()
1013 self.socket.bind((self.host, self.port))
1014 self.socket.listen(5)
1016 self.src, self.address = self.socket.accept()
1017 self.src.send("ok\n")
1018 if self.get_response() == "QUIT":
1022 self.socket.connect((address, self.port))
1023 self.src = self.socket
1024 self.src.send("ok\n")
1025 if self.get_response() == "QUIT":
1028 def get_response(self):
1029 # Timeout the start of the message (first character)
1030 if network_timeout_start > 0.0:
1031 ready = select.select([self.src], [], [], network_timeout_start)[0]
1034 if self.src in ready:
1035 s = self.src.recv(1)
1037 raise Exception("UNRESPONSIVE")
1040 while s[len(s)-1] != '\n':
1041 # Timeout on each character in the message
1042 if network_timeout_delay > 0.0:
1043 ready = select.select([self.src], [], [], network_timeout_delay)[0]
1046 if self.src in ready:
1047 s += self.src.recv(1)
1049 raise Exception("UNRESPONSIVE")
1051 return s.strip(" \r\n")
1053 def send_message(self,s):
1054 if network_timeout_start > 0.0:
1055 ready = select.select([], [self.src], [], network_timeout_start)[1]
1059 if self.src in ready:
1060 self.src.send(s + "\n")
1062 raise Exception("UNRESPONSIVE")
1064 def check_quit(self, s):
1068 game.final_result = " ".join(s[1:]) + " " + str(opponent(self.colour))
1074 class NetworkSender(Player,Network):
1075 def __init__(self, base_player, address = None):
1076 self.base_player = base_player
1077 Player.__init__(self, base_player.name, base_player.colour)
1079 self.address = address
1082 Network.__init__(self, self.base_player.colour, self.address)
1087 [x,y] = self.base_player.select()
1088 choice = self.board.grid[x][y]
1089 s = str(x) + " " + str(y)
1090 #print str(self) + ".select sends " + s
1091 self.send_message(s)
1095 [x,y] = self.base_player.get_move()
1096 s = str(x) + " " + str(y)
1097 #print str(self) + ".get_move sends " + s
1098 self.send_message(s)
1101 def update(self, s):
1102 self.base_player.update(s)
1104 [x,y] = map(int, s[0:2])
1105 selected = self.board.grid[x][y]
1106 if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
1107 s = " ".join(s[0:3])
1109 if selected.types_revealed[i] == True:
1110 s += " " + str(selected.types[i])
1113 #print str(self) + ".update sends " + s
1114 self.send_message(s)
1117 def quit(self, final_result):
1118 self.base_player.quit(final_result)
1119 #self.src.send("QUIT " + str(final_result) + "\n")
1122 class NetworkReceiver(Player,Network):
1123 def __init__(self, colour, address=None):
1125 Player.__init__(self, address, colour)
1127 self.address = address
1132 Network.__init__(self, self.colour, self.address)
1137 s = self.get_response()
1138 #print str(self) + ".select gets " + s
1139 [x,y] = map(int,s.split(" "))
1140 if x == -1 and y == -1:
1141 #print str(self) + ".select quits the game"
1143 game.final_state = "network terminated " + self.colour
1147 s = self.get_response()
1148 #print str(self) + ".get_move gets " + s
1149 [x,y] = map(int,s.split(" "))
1150 if x == -1 and y == -1:
1151 #print str(self) + ".get_move quits the game"
1153 game.final_state = "network terminated " + self.colour
1157 def update(self, result):
1159 result = result.split(" ")
1160 [x,y] = map(int, result[0:2])
1161 selected = self.board.grid[x][y]
1162 if selected != None and selected.colour == self.colour and len(result) > 2 and not "->" in result:
1163 s = self.get_response()
1164 #print str(self) + ".update - receives " + str(s)
1166 selected.choice = int(s[2])
1168 selected.types[i] = str(s[3+i])
1169 if s[3+i] == "unknown":
1170 selected.types_revealed[i] = False
1172 selected.types_revealed[i] = True
1173 selected.current_type = selected.types[selected.choice]
1176 #print str(self) + ".update - ignore result " + str(result)
1179 def quit(self, final_result):
1182 # --- network.py --- #
1185 # A thread that can be stopped!
1186 # Except it can only be stopped if it checks self.stopped() periodically
1187 # So it can sort of be stopped
1188 class StoppableThread(threading.Thread):
1190 threading.Thread.__init__(self)
1191 self._stop = threading.Event()
1197 return self._stop.isSet()
1198 # --- thread_util.py --- #
1204 if log_file != None:
1206 log_file.write(str(datetime.datetime.now()) + " : " + s + "\n")
1211 # A thread that runs the game
1212 class GameThread(StoppableThread):
1213 def __init__(self, board, players):
1214 StoppableThread.__init__(self)
1216 self.players = players
1217 self.state = {"turn" : None} # The game state
1218 self.error = 0 # Whether the thread exits with an error
1219 self.lock = threading.RLock() #lock for access of self.state
1220 self.cond = threading.Condition() # conditional for some reason, I forgot
1221 self.final_result = ""
1223 # Run the game (run in new thread with start(), run in current thread with run())
1226 while not self.stopped():
1228 for p in self.players:
1230 if isinstance(p, NetworkSender):
1231 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
1233 self.state["turn"] = p
1236 [x,y] = p.select() # Player selects a square
1243 result = self.board.select(x, y, colour = p.colour)
1244 for p2 in self.players:
1245 p2.update(result) # Inform players of what happened
1250 target = self.board.grid[x][y]
1251 if isinstance(graphics, GraphicsThread):
1253 graphics.state["moves"] = self.board.possible_moves(target)
1254 graphics.state["select"] = target
1256 time.sleep(turn_delay)
1259 if len(self.board.possible_moves(target)) == 0:
1260 #print "Piece cannot move"
1262 if isinstance(graphics, GraphicsThread):
1264 graphics.state["moves"] = None
1265 graphics.state["select"] = None
1266 graphics.state["dest"] = None
1270 [x2,y2] = p.get_move() # Player selects a destination
1277 self.board.update_move(x, y, x2, y2)
1278 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1279 for p2 in self.players:
1280 p2.update(result) # Inform players of what happened
1284 if isinstance(graphics, GraphicsThread):
1286 graphics.state["moves"] = [[x2,y2]]
1288 time.sleep(turn_delay)
1290 if isinstance(graphics, GraphicsThread):
1292 graphics.state["select"] = None
1293 graphics.state["dest"] = None
1294 graphics.state["moves"] = None
1296 # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
1297 # except Exception,e:
1298 # result = e.message
1299 # #sys.stderr.write(result + "\n")
1303 # self.final_result = self.state["turn"].colour + " " + e.message
1305 if self.board.king["black"] == None:
1306 if self.board.king["white"] == None:
1308 self.final_result = self.state["turn"].colour + " DRAW"
1311 self.final_result = "white"
1313 elif self.board.king["white"] == None:
1315 self.final_result = "black"
1323 for p2 in self.players:
1324 p2.quit(self.final_result)
1326 log(self.final_result)
1331 # A thread that replays a log file
1332 class ReplayThread(GameThread):
1333 def __init__(self, players, src):
1334 self.board = Board(style="agent")
1335 GameThread.__init__(self, self.board, players)
1343 for line in self.src:
1350 self.state["turn"] = self.players[i]
1352 line = line.split(":")
1353 result = line[len(line)-1].strip(" \r\n")
1357 self.board.update(result)
1360 self.final_result = result
1361 if isinstance(graphics, GraphicsThread):
1365 [x,y] = map(int, result.split(" ")[0:2])
1366 target = self.board.grid[x][y]
1368 if isinstance(graphics, GraphicsThread):
1371 graphics.state["moves"] = self.board.possible_moves(target)
1372 graphics.state["select"] = target
1374 time.sleep(turn_delay)
1377 [x2,y2] = map(int, result.split(" ")[3:5])
1379 graphics.state["moves"] = [[x2,y2]]
1381 time.sleep(turn_delay)
1384 graphics.state["select"] = None
1385 graphics.state["dest"] = None
1386 graphics.state["moves"] = None
1392 for p in self.players:
1395 phase = (phase + 1) % 2
1401 def opponent(colour):
1402 if colour == "white":
1410 # Dictionary that stores the unicode character representations of the different pieces
1411 # Chess was clearly the reason why unicode was invented
1412 # For some reason none of the pygame chess implementations I found used them!
1413 piece_char = {"white" : {"king" : u'\u2654',
1414 "queen" : u'\u2655',
1416 "bishop" : u'\u2657',
1417 "knight" : u'\u2658',
1420 "black" : {"king" : u'\u265A',
1421 "queen" : u'\u265B',
1423 "bishop" : u'\u265D',
1424 "knight" : u'\u265E',
1428 images = {"white" : {}, "black" : {}}
1429 small_images = {"white" : {}, "black" : {}}
1431 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
1433 # Get the font sizes
1434 l_size = 5*(grid_sz[0] / 8)
1435 s_size = 3*(grid_sz[0] / 8)
1437 for c in piece_char.keys():
1440 for p in piece_char[c].keys():
1441 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
1442 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})
1444 for p in piece_char[c].keys():
1445 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1446 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1447 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1448 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1451 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
1452 if not os.path.exists(image_dir):
1453 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
1454 for c in piece_char.keys():
1455 for p in piece_char[c].keys():
1456 images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
1457 small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
1458 # --- images.py --- #
1459 graphics_enabled = True
1463 graphics_enabled = False
1468 # A thread to make things pretty
1469 class GraphicsThread(StoppableThread):
1470 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1471 StoppableThread.__init__(self)
1475 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1476 pygame.display.set_caption(title)
1478 #print "Initialised properly"
1480 self.grid_sz = grid_sz[:]
1481 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
1483 self.lock = threading.RLock()
1484 self.cond = threading.Condition()
1487 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
1489 #create_images(grid_sz)
1490 create_images(grid_sz)
1493 for c in images.keys():
1494 for p in images[c].keys():
1495 images[c][p] = images[c][p].convert(self.window)
1496 small_images[c][p] = small_images[c][p].convert(self.window)
1503 # On the run from the world
1506 while not self.stopped():
1508 #print "Display grid"
1509 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
1511 #print "Display overlay"
1514 #print "Display pieces"
1515 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
1517 pygame.display.flip()
1519 for event in pygame.event.get():
1520 if event.type == pygame.QUIT:
1521 if isinstance(game, GameThread):
1523 game.final_result = ""
1524 if game.state["turn"] != None:
1525 game.final_result = game.state["turn"].colour + " "
1526 game.final_result += "terminated"
1530 elif event.type == pygame.MOUSEBUTTONDOWN:
1531 self.mouse_down(event)
1532 elif event.type == pygame.MOUSEBUTTONUP:
1533 self.mouse_up(event)
1540 self.message("Game ends, result \""+str(game.final_result) + "\"")
1543 # Wake up anyone who is sleeping
1548 pygame.quit() # Time to say goodbye
1550 # Mouse release event handler
1551 def mouse_up(self, event):
1552 if event.button == 3:
1554 self.state["overlay"] = None
1555 elif event.button == 2:
1557 self.state["coverage"] = None
1559 # Mouse click event handler
1560 def mouse_down(self, event):
1561 if event.button == 1:
1562 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
1563 if isinstance(game, GameThread):
1565 p = game.state["turn"]
1570 if isinstance(p, HumanPlayer):
1572 s = self.board.grid[m[0]][m[1]]
1573 select = self.state["select"]
1575 if s != None and s.colour != p.colour:
1576 self.message("Wrong colour") # Look at all this user friendliness!
1579 # Notify human player of move
1582 self.state["select"] = s
1583 self.state["dest"] = None
1592 if self.state["moves"] == None:
1595 if not m in self.state["moves"]:
1596 self.message("Illegal Move") # I still think last year's mouse interface was adequate
1601 if self.state["dest"] == None:
1603 self.state["dest"] = m
1604 self.state["select"] = None
1605 self.state["moves"] = None
1608 elif event.button == 3:
1609 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1610 if isinstance(game, GameThread):
1612 p = game.state["turn"]
1617 if isinstance(p, HumanPlayer):
1619 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
1621 elif event.button == 2:
1622 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1623 if isinstance(game, GameThread):
1625 p = game.state["turn"]
1630 if isinstance(p, HumanPlayer):
1632 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
1637 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
1638 # Draw square over the selected piece
1640 select = self.state["select"]
1642 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
1643 square_img.fill(pygame.Color(0,255,0,64))
1644 self.window.blit(square_img, mp)
1645 # If a piece is selected, draw all reachable squares
1646 # (This quality user interface has been patented)
1648 m = self.state["moves"]
1650 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
1652 mp = [self.grid_sz[i] * move[i] for i in range(2)]
1653 self.window.blit(square_img, mp)
1654 # If a piece is overlayed, show all squares that it has a probability to reach
1656 m = self.state["overlay"]
1661 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
1662 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
1663 self.window.blit(square_img, mp)
1664 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
1665 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
1666 self.window.blit(text, mp)
1668 # If a square is selected, highlight all pieces that have a probability to reach it
1670 m = self.state["coverage"]
1673 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
1674 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
1675 self.window.blit(square_img, mp)
1676 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
1677 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
1678 self.window.blit(text, mp)
1679 # Draw a square where the mouse is
1680 # This also serves to indicate who's turn it is
1682 if isinstance(game, GameThread):
1684 turn = game.state["turn"]
1688 if isinstance(turn, HumanPlayer):
1689 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
1690 square_img.fill(pygame.Color(0,0,255,128))
1691 if turn.colour == "white":
1692 c = pygame.Color(255,255,255)
1694 c = pygame.Color(0,0,0)
1695 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
1696 self.window.blit(square_img, mp)
1698 # Message in a bottle
1699 def message(self, string, pos = None, colour = None, font_size = 20):
1700 #print "Drawing message..."
1701 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
1703 colour = pygame.Color(0,0,0)
1705 text = font.render(string, 1, colour)
1708 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
1709 s.fill(pygame.Color(128,128,128))
1711 tmp = self.window.get_size()
1714 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
1716 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
1719 rect = (pos[0], pos[1], text.get_width(), text.get_height())
1721 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
1722 self.window.blit(s, pos)
1723 self.window.blit(text, pos)
1725 pygame.display.flip()
1727 def getstr(self, prompt = None):
1728 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
1729 s.blit(self.window, (0,0))
1735 self.message(prompt)
1736 self.message(result, pos = (0, 1))
1739 for event in pygame.event.get():
1740 if event.type == pygame.QUIT:
1742 if event.type == pygame.KEYDOWN:
1743 if event.key == pygame.K_BACKSPACE:
1744 result = result[0:len(result)-1]
1745 self.window.blit(s, (0,0)) # Revert the display
1750 if event.unicode == '\r':
1753 result += str(event.unicode)
1758 # Function to pick a button
1759 def SelectButton(self, choices, prompt = None, font_size=20):
1761 #print "Select button called!"
1762 self.board.display_grid(self.window, self.grid_sz)
1764 self.message(prompt)
1765 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
1767 sz = self.window.get_size()
1770 for i in range(len(choices)):
1773 text = font.render(c, 1, pygame.Color(0,0,0))
1774 p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
1775 targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
1778 mp =pygame.mouse.get_pos()
1779 for i in range(len(choices)):
1781 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
1782 font_colour = pygame.Color(255,0,0)
1783 box_colour = pygame.Color(0,0,255,128)
1785 font_colour = pygame.Color(0,0,0)
1786 box_colour = pygame.Color(128,128,128)
1788 text = font.render(c, 1, font_colour)
1789 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
1791 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
1792 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
1793 self.window.blit(s, targets[i][0:2])
1796 pygame.display.flip()
1798 for event in pygame.event.get():
1799 if event.type == pygame.QUIT:
1801 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
1802 for i in range(len(targets)):
1804 if event.pos[0] > t[0] and event.pos[0] < t[2]:
1805 if event.pos[1] > t[1] and event.pos[1] < t[3]:
1807 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
1810 # Function to pick players in a nice GUI way
1811 def SelectPlayers(self, players = []):
1814 #print "SelectPlayers called"
1816 missing = ["white", "black"]
1818 missing.remove(p.colour)
1820 for colour in missing:
1823 choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
1825 players.append(HumanPlayer("human", colour))
1828 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
1829 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
1830 internal_agents.remove(('InternalAgent', InternalAgent))
1831 if len(internal_agents) > 0:
1832 choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
1837 agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
1838 players.append(agent[1](agent[0], colour))
1842 from tkFileDialog import askopenfilename
1843 root = Tkinter.Tk() # Need a root to make Tkinter behave
1844 root.withdraw() # Some sort of magic incantation
1845 path = askopenfilename(parent=root, initialdir="../agents",title=
1848 return self.SelectPlayers()
1849 players.append(make_player(path, colour))
1854 self.board.display_grid(self.window, self.grid_sz)
1855 pygame.display.flip()
1856 path = self.getstr(prompt = "Enter path:")
1861 return self.SelectPlayers()
1864 p = make_player(path, colour)
1866 self.board.display_grid(self.window, self.grid_sz)
1867 pygame.display.flip()
1868 self.message("Invalid path!")
1874 while address == "":
1875 self.board.display_grid(self.window, self.grid_sz)
1877 address = self.getstr(prompt = "Address? (leave blank for server)")
1884 map(int, address.split("."))
1886 self.board.display_grid(self.window, self.grid_sz)
1887 self.message("Invalid IPv4 address!")
1890 players.append(NetworkReceiver(colour, address))
1893 #print str(self) + ".SelectPlayers returns " + str(players)
1898 # --- graphics.py --- #
1899 #!/usr/bin/python -u
1901 # Do you know what the -u does? It unbuffers stdin and stdout
1902 # I can't remember why, but last year things broke without that
1905 UCC::Progcomp 2013 Quantum Chess game
1906 @author Sam Moore [SZM] "matches"
1907 @copyright The University Computer Club, Incorporated
1908 (ie: You can copy it for not for profit purposes)
1911 # system python modules or whatever they are called
1917 [game, graphics] = [None, None]
1919 def make_player(name, colour):
1921 if name[1:] == "human":
1922 return HumanPlayer(name, colour)
1923 s = name[1:].split(":")
1924 if s[0] == "network":
1928 return NetworkReceiver(colour, address)
1929 if s[0] == "internal":
1932 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
1933 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
1934 internal_agents.remove(('InternalAgent', InternalAgent))
1937 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
1938 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
1941 for a in internal_agents:
1943 return a[1](name, colour)
1945 sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
1946 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
1951 return ExternalAgent(name, colour)
1955 # The main function! It does the main stuff!
1958 # Apparently python will silently treat things as local unless you do this
1959 # Anyone who says "You should never use a global variable" can die in a fire
1964 global agent_timeout
1967 global graphics_enabled
1975 # Get the important warnings out of the way
1976 if platform.system() == "Windows":
1977 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
1978 if platform.release() == "Vista":
1979 sys.stderr.write(sys.argv[0] + " : God help you.\n")
1984 while i < len(argv)-1:
1988 p = make_player(arg, colour)
1989 if not isinstance(p, Player):
1990 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
1993 if colour == "white":
1995 elif colour == "black":
1998 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
2001 # Option parsing goes here
2002 if arg[1] == '-' and arg[2:] == "classical":
2004 elif arg[1] == '-' and arg[2:] == "quantum":
2006 elif (arg[1] == '-' and arg[2:] == "graphics"):
2007 graphics_enabled = not graphics_enabled
2008 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
2009 # Load game from file
2010 if len(arg[2:].split("=")) == 1:
2011 src_file = sys.stdin
2013 src_file = open(arg[2:].split("=")[1])
2014 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
2016 if len(arg[2:].split("=")) == 1:
2017 log_file = sys.stdout
2019 log_file = open(arg[2:].split("=")[1], "w")
2020 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
2022 if len(arg[2:].split("=")) == 1:
2025 turn_delay = float(arg[2:].split("=")[1])
2027 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
2029 if len(arg[2:].split("=")) == 1:
2032 agent_timeout = float(arg[2:].split("=")[1])
2034 elif (arg[1] == '-' and arg[2:] == "help"):
2036 os.system("less data/help.txt") # The best help function
2042 # Construct a GameThread! Make it global! Damn the consequences!
2044 if src_file != None:
2045 if len(players) == 0:
2046 players = [Player("dummy", "white"), Player("dummy", "black")]
2047 game = ReplayThread(players, src_file)
2049 board = Board(style)
2050 game = GameThread(board, players)
2055 if graphics_enabled == True:
2057 graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
2061 sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
2062 graphics_enabled = False
2064 # If there are no players listed, display a nice pretty menu
2065 if len(players) != 2:
2066 if graphics != None:
2067 players = graphics.SelectPlayers(players)
2069 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2072 # If there are still no players, quit
2073 if players == None or len(players) != 2:
2074 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
2078 # Wrap NetworkSender players around original players if necessary
2079 for i in range(len(players)):
2080 if isinstance(players[i], NetworkReceiver):
2081 players[i].board = board # Network players need direct access to the board
2082 for j in range(len(players)):
2085 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
2087 players[j] = NetworkSender(players[j], players[i].address)
2088 players[j].board = board
2090 # Connect the networked players
2092 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
2093 if graphics != None:
2094 graphics.board.display_grid(graphics.window, graphics.grid_sz)
2095 graphics.message("Connecting to " + p.colour + " player...")
2099 # If using windows, select won't work; use horrible TimeoutPlayer hack
2100 if agent_timeout > 0:
2101 if platform.system() == "Windows":
2102 for i in range(len(players)):
2103 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
2104 players[i] = TimeoutPlayer(players[i], agent_timeout)
2108 # InternalAgents get wrapped to an ExternalAgent when there is a timeout
2109 # This is not confusing at all.
2110 for i in range(len(players)):
2111 if isinstance(players[i], InternalAgent):
2112 players[i] = ExternalWrapper(players[i])
2121 if graphics != None:
2122 game.start() # This runs in a new thread
2125 error = game.error + graphics.error
2130 if log_file != None and log_file != sys.stdout:
2133 if src_file != None and src_file != sys.stdin:
2138 # This is how python does a main() function...
2139 if __name__ == "__main__":
2140 sys.exit(main(sys.argv))
2142 # EOF - created from make on Tue Jan 29 18:10:18 WST 2013