1 [w,h] = [8,8] # Width and height of board(s)
3 always_reveal_states = False
5 # Class to represent a quantum chess board
7 # Initialise; if master=True then the secondary piece types are assigned
8 # Otherwise, they are left as unknown
9 # So you can use this class in Agent programs, and fill in the types as they are revealed
10 def __init__(self, style="agent"):
12 self.pieces = {"white" : [], "black" : []}
13 self.grid = [[None] * w for _ in range(h)] # 2D List (you can get arrays in python, somehow, but they scare me)
14 self.unrevealed_types = {"white" : piece_types.copy(), "black" : piece_types.copy()}
15 self.king = {"white" : None, "black" : None} # We need to keep track of the king, because he is important
18 for c in ["black", "white"]:
19 del self.unrevealed_types[c]["unknown"]
24 # Add all the pieces with known primary types
27 s = ["black", "white"][i]
31 c.append(Piece(s, 0, y, ["rook"]))
32 c.append(Piece(s, 1, y, ["knight"]))
33 c.append(Piece(s, 2, y, ["bishop"]))
34 k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
35 k.current_type = "king"
38 c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
39 c.append(Piece(s, 5, y, ["bishop"]))
40 c.append(Piece(s, 6, y, ["knight"]))
41 c.append(Piece(s, 7, y, ["rook"]))
50 c.append(Piece(s, x, y, ["pawn"]))
53 types_left.update(piece_types)
54 del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
55 del types_left["unknown"] # We certainly don't want these!
58 self.grid[piece.x][piece.y] = piece
60 if len(piece.types) > 1:
62 if style == "agent": # Assign placeholder "unknown" secondary type
63 piece.types.append("unknown")
66 elif style == "quantum":
67 # The master allocates the secondary types
68 choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
69 types_left[choice] -= 1
70 if types_left[choice] <= 0:
71 del types_left[choice]
72 piece.types.append('?' + choice)
73 elif style == "classical":
74 piece.types.append(piece.types[0])
75 piece.current_type = piece.types[0]
79 newboard = Board(master = False)
80 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
81 mypieces = self.pieces["white"] + self.pieces["black"]
83 for i in range(len(mypieces)):
84 newpieces[i].init_from_copy(mypieces[i])
86 # Reset the board from a string
87 def reset_board(self, s):
88 self.pieces = {"white" : [], "black" : []}
89 self.king = {"white" : None, "black" : None}
90 self.grid = [[None] * w for _ in range(h)]
93 self.grid[x][y] = None
95 for line in s.split("\n"):
101 tokens = line.split(" ")
102 [x, y] = map(int, tokens[len(tokens)-1].split(","))
103 current_type = tokens[1]
104 types = map(lambda e : e.strip(" '[],"), line.split('[')[1].split(']')[0].split(','))
106 target = Piece(tokens[0], x, y, types)
107 target.current_type = current_type
110 target.choice = types.index(current_type)
114 self.pieces[tokens[0]].append(target)
115 if target.current_type == "king":
116 self.king[tokens[0]] = target
118 self.grid[x][y] = target
121 def display_grid(self, window = None, grid_sz = [80,80]):
123 return # I was considering implementing a text only display, then I thought "Fuck that"
125 # The indentation is getting seriously out of hand...
126 for x in range(0, w):
127 for y in range(0, h):
129 c = pygame.Color(200,200,200)
131 c = pygame.Color(64,64,64)
132 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
134 def display_pieces(self, window = None, grid_sz = [80,80]):
137 for p in self.pieces["white"] + self.pieces["black"]:
138 p.draw(window, grid_sz, self.style)
140 # Draw the board in a pygame window
141 def display(self, window = None):
142 self.display_grid(window)
143 self.display_pieces(window)
151 if self.grid[x][y] == None:
153 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
154 raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
156 # Select a piece on the board (colour is the colour of whoever is doing the selecting)
157 def select(self, x,y, colour=None):
158 if not self.on_board(x, y): # Get on board everyone!
159 raise Exception("BOUNDS")
161 piece = self.grid[x][y]
163 raise Exception("EMPTY")
165 if colour != None and piece.colour != colour:
166 raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
168 # I'm not quite sure why I made this return a string, but screw logical design
169 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
172 # Update the board when a piece has been selected
173 # "type" is apparently reserved, so I'll use "state"
174 def update_select(self, x, y, type_index, state):
175 piece = self.grid[x][y]
176 if piece.types[type_index] == "unknown":
177 if not state in self.unrevealed_types[piece.colour].keys():
178 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
179 self.unrevealed_types[piece.colour][state] -= 1
180 if self.unrevealed_types[piece.colour][state] <= 0:
181 del self.unrevealed_types[piece.colour][state]
183 piece.types[type_index] = state
184 piece.current_type = state
186 if len(self.possible_moves(piece)) <= 0:
187 piece.deselect() # Piece can't move; deselect it
189 # Update the board when a piece has been moved
190 def update_move(self, x, y, x2, y2):
191 piece = self.grid[x][y]
192 self.grid[x][y] = None
193 taken = self.grid[x2][y2]
195 if taken.current_type == "king":
196 self.king[taken.colour] = None
197 self.pieces[taken.colour].remove(taken)
198 self.grid[x2][y2] = piece
202 # If the piece is a pawn, and it reaches the final row, it becomes a queen
203 # I know you are supposed to get a choice
204 # But that would be effort
205 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
206 if self.style == "classical":
207 piece.types[0] = "queen"
208 piece.types[1] = "queen"
210 piece.types[piece.choice] = "queen"
211 piece.current_type = "queen"
213 piece.deselect() # Uncollapse (?) the wavefunction!
217 # Update the board from a string
218 # Guesses what to do based on the format of the string
219 def update(self, result):
220 #print "Update called with \"" + str(result) + "\""
221 # String always starts with 'x y'
223 s = result.split(" ")
224 [x,y] = map(int, s[0:2])
226 raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
228 piece = self.grid[x][y]
230 raise Exception("EMPTY")
232 # If a piece is being moved, the third token is '->'
233 # We could get away with just using four integers, but that wouldn't look as cool
235 # Last two tokens are the destination
237 [x2,y2] = map(int, s[3:])
239 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
241 # Move the piece (take opponent if possible)
242 self.update_move(x, y, x2, y2)
245 # Otherwise we will just assume a piece has been selected
247 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
248 state = s[3] # The last token is a string identifying the type
250 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
253 self.update_select(x, y, type_index, state)
257 # Gets each piece that could reach the given square and the probability that it could reach that square
258 # Will include allied pieces that defend the attacker
259 def coverage(self, x, y, colour = None, reject_allied = True):
263 pieces = self.pieces["white"] + self.pieces["black"]
265 pieces = self.pieces[colour]
268 prob = self.probability_grid(p, reject_allied)[x][y]
270 result.update({p : prob})
279 # Associates each square with a probability that the piece could move into it
280 # Look, I'm doing all the hard work for you here...
281 def probability_grid(self, p, reject_allied = True):
283 result = [[0.0] * w for _ in range(h)]
284 if not isinstance(p, Piece):
287 if p.current_type != "unknown":
288 #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
289 for point in self.possible_moves(p, reject_allied):
290 result[point[0]][point[1]] = 1.0
294 for i in range(len(p.types)):
297 if t == "unknown" or p.types[i][0] == '?':
299 for t2 in self.unrevealed_types[p.colour].keys():
300 total_types += self.unrevealed_types[p.colour][t2]
302 for t2 in self.unrevealed_types[p.colour].keys():
303 prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
305 for point in self.possible_moves(p, reject_allied):
306 result[point[0]][point[1]] += prob2 * prob
310 for point in self.possible_moves(p, reject_allied):
311 result[point[0]][point[1]] += prob
314 p.current_type = "unknown"
317 def prob_is_type(self, p, state):
320 for i in range(len(p.types)):
325 if t == "unknown" or p.types[i][0] == '?':
327 for t2 in self.unrevealed_types[p.colour].keys():
328 total_prob += self.unrevealed_types[p.colour][t2]
329 for t2 in self.unrevealed_types[p.colour].keys():
331 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
335 # Get all squares that the piece could move into
336 # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
337 # reject_allied indicates whether squares occupied by allied pieces will be removed
338 # (set to false to check for defense)
339 def possible_moves(self, p, reject_allied = True):
345 if p.current_type == "unknown":
346 raise Exception("SANITY: Piece state unknown")
347 # The below commented out code causes things to break badly
352 # result += self.possible_moves(p)
353 #p.current_type = "unknown"
356 if p.current_type == "king":
357 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]]
358 elif p.current_type == "queen":
359 for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
360 result += self.scan(p.x, p.y, d[0], d[1])
361 elif p.current_type == "bishop":
362 for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
363 result += self.scan(p.x, p.y, d[0], d[1])
364 elif p.current_type == "rook":
365 for d in [[-1,0],[1,0],[0,-1],[0,1]]:
366 result += self.scan(p.x, p.y, d[0], d[1])
367 elif p.current_type == "knight":
368 # I would use two lines, but I'm not sure how python likes that
369 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]]
370 elif p.current_type == "pawn":
371 if p.colour == "white":
373 # Pawn can't move forward into occupied square
374 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
375 result = [[p.x,p.y-1]]
376 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
377 if not self.on_board(f[0], f[1]):
379 if self.grid[f[0]][f[1]] != None: # Pawn can take diagonally
382 # Slightly embarrassing if the pawn jumps over someone on its first move...
383 if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
384 result.append([p.x, p.y-2])
386 # Vice versa for the black pawn
387 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
388 result = [[p.x,p.y+1]]
390 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
391 if not self.on_board(f[0], f[1]):
393 if self.grid[f[0]][f[1]] != None:
394 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
397 if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
398 result.append([p.x, p.y+2])
400 #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
402 # Remove illegal moves
403 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
404 for point in result[:]:
406 if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
407 result.remove(point) # Remove locations outside the board
409 g = self.grid[point[0]][point[1]]
411 if g != None and (g.colour == p.colour and reject_allied == True):
412 result.remove(point) # Remove allied pieces
418 # Scans in a direction until it hits a piece, returns all squares in the line
419 # (includes the final square (which contains a piece), but not the original square)
420 def scan(self, x, y, vx, vy):
428 if not self.on_board(xx, yy):
432 g = self.grid[xx][yy]
438 # Returns "white", "black" or "DRAW" if the game should end
439 def end_condition(self):
440 if self.king["white"] == None:
441 if self.king["black"] == None:
442 return "DRAW" # This shouldn't happen
444 elif self.king["black"] == None:
446 elif len(self.pieces["white"]) == 1 and len(self.pieces["black"]) == 1:
448 elif self.max_moves != None and self.moves > self.max_moves:
453 # I typed the full statement about 30 times before writing this function...
454 def on_board(self, x, y):
455 return (x >= 0 and x < w) and (y >= 0 and y < h)