439ab77dfab77aa62565d92d648b46a814147b1c
[progcomp2013.git] / qchess / src / board.py
1 [w,h] = [8,8] # Width and height of board(s)
2
3 always_reveal_states = False
4
5 # Class to represent a quantum chess board
6 class 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"):
11                 self.style = style
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
16                 self.max_moves = None
17                 self.moves = 0
18                 self.move_stack = []
19                 for c in ["black", "white"]:
20                         del self.unrevealed_types[c]["unknown"]
21
22                 if style == "empty":
23                         return
24
25                 # Add all the pieces with known primary types
26                 for i in range(0, 2):
27                         
28                         s = ["black", "white"][i]
29                         c = self.pieces[s]
30                         y = [0, h-1][i]
31
32                         c.append(Piece(s, 0, y, ["rook"]))
33                         c.append(Piece(s, 1, y, ["knight"]))
34                         c.append(Piece(s, 2, y, ["bishop"]))
35                         k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
36                         k.current_type = "king"
37                         self.king[s] = k
38                         c.append(k)
39                         c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
40                         c.append(Piece(s, 5, y, ["bishop"]))
41                         c.append(Piece(s, 6, y, ["knight"]))
42                         c.append(Piece(s, 7, y, ["rook"]))
43                         
44                         if y == 0: 
45                                 y += 1 
46                         else: 
47                                 y -= 1
48                         
49                         # Lots of pawn
50                         for x in range(0, w):
51                                 c.append(Piece(s, x, y, ["pawn"]))
52
53                         types_left = {}
54                         types_left.update(piece_types)
55                         del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
56                         del types_left["unknown"] # We certainly don't want these!
57                         for piece in c:
58                                 # Add to grid
59                                 self.grid[piece.x][piece.y] = piece 
60
61                                 if len(piece.types) > 1:
62                                         continue                                
63                                 if style == "agent": # Assign placeholder "unknown" secondary type
64                                         piece.types.append("unknown")
65                                         continue
66
67                                 elif style == "quantum":
68                                         # The master allocates the secondary types
69                                         choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
70                                         types_left[choice] -= 1
71                                         if types_left[choice] <= 0:
72                                                 del types_left[choice]
73                                         piece.types.append('?' + choice)
74                                 elif style == "classical":
75                                         piece.types.append(piece.types[0])
76                                         piece.current_type = piece.types[0]
77                                         piece.choice = 0
78
79         def clone(self):
80                 newboard = Board(master = False)
81                 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
82                 mypieces = self.pieces["white"] + self.pieces["black"]
83
84                 for i in range(len(mypieces)):
85                         newpieces[i].init_from_copy(mypieces[i])
86         
87         # Reset the board from a string
88         def reset_board(self, s):
89                 self.pieces = {"white" : [], "black" : []}
90                 self.king = {"white" : None, "black" : None}
91                 self.grid = [[None] * w for _ in range(h)]
92                 for x in range(w):
93                         for y in range(h):
94                                 self.grid[x][y] = None
95
96                 for line in s.split("\n"):
97                         if line == "":
98                                 continue
99                         if line[0] == "#":
100                                 continue
101
102                         tokens = line.split(" ")
103                         [x, y] = map(int, tokens[len(tokens)-1].split(","))
104                         current_type = tokens[1]
105                         types = map(lambda e : e.strip(" '[],"), line.split('[')[1].split(']')[0].split(','))
106                         
107                         target = Piece(tokens[0], x, y, types)
108                         target.current_type = current_type
109                         
110                         try:
111                                 target.choice = types.index(current_type)
112                         except:
113                                 target.choice = -1
114
115                         self.pieces[tokens[0]].append(target)
116                         if target.current_type == "king":
117                                 self.king[tokens[0]] = target
118
119                         self.grid[x][y] = target
120                         
121
122         def display_grid(self, window = None, grid_sz = [80,80]):
123                 if window == None:
124                         return # I was considering implementing a text only display, then I thought "Fuck that"
125
126                 # The indentation is getting seriously out of hand...
127                 for x in range(0, w):
128                         for y in range(0, h):
129                                 if (x + y) % 2 == 0:
130                                         c = pygame.Color(200,200,200)
131                                 else:
132                                         c = pygame.Color(64,64,64)
133                                 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
134
135         def display_pieces(self, window = None, grid_sz = [80,80]):
136                 if window == None:
137                         return
138                 for p in self.pieces["white"] + self.pieces["black"]:
139                         p.draw(window, grid_sz, self.style)
140
141         # Draw the board in a pygame window
142         def display(self, window = None):
143                 self.display_grid(window)
144                 self.display_pieces(window)
145                 
146
147                 
148
149         def verify(self):
150                 for x in range(w):
151                         for y in range(h):
152                                 if self.grid[x][y] == None:
153                                         continue
154                                 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
155                                         raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
156
157         # Select a piece on the board (colour is the colour of whoever is doing the selecting)
158         def select(self, x,y, colour=None):
159                 if not self.on_board(x, y): # Get on board everyone!
160                         raise Exception("BOUNDS")
161
162                 piece = self.grid[x][y]
163                 if piece == None:
164                         raise Exception("EMPTY")
165
166                 if colour != None and piece.colour != colour:
167                         raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
168
169                 # I'm not quite sure why I made this return a string, but screw logical design
170                 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
171
172
173         # Update the board when a piece has been selected
174         # "type" is apparently reserved, so I'll use "state"
175         def update_select(self, x, y, type_index, state, sanity=True, deselect=True):
176                 debug(str(self) + " update_select called")
177                 piece = self.grid[x][y]
178                 if piece.types[type_index] == "unknown":
179                         if not state in self.unrevealed_types[piece.colour].keys() and sanity == True:
180                                 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
181                         self.unrevealed_types[piece.colour][state] -= 1
182                         if self.unrevealed_types[piece.colour][state] <= 0:
183                                 del self.unrevealed_types[piece.colour][state]
184
185                 piece.types[type_index] = state
186                 piece.current_type = state
187
188                 if deselect == True and len(self.possible_moves(piece)) <= 0:
189                         piece.deselect() # Piece can't move; deselect it
190                         
191                 # Piece needs to recalculate moves
192                 piece.possible_moves = None
193                 
194         # Update the board when a piece has been moved
195         def update_move(self, x, y, x2, y2, sanity=True):
196                 debug(str(self) + " update_move called \""+str(x)+ " " + str(y) + " -> " + str(x2) + " " + str(y2) + "\"")      
197                 piece = self.grid[x][y]
198                 #print "Moving " + str(x) + "," + str(y) + " to " + str(x2) + "," + str(y2) + "; possible_moves are " + str(self.possible_moves(piece))
199                 
200                 if not [x2,y2] in self.possible_moves(piece) and sanity == True:
201                         raise Exception("ILLEGAL move " + str(x2)+","+str(y2))
202                 
203                 self.grid[x][y] = None
204                 taken = self.grid[x2][y2]
205                 if taken != None:
206                         if taken.current_type == "king":
207                                 self.king[taken.colour] = None
208                         self.pieces[taken.colour].remove(taken)
209                 self.grid[x2][y2] = piece
210                 piece.x = x2
211                 piece.y = y2
212
213                 # If the piece is a pawn, and it reaches the final row, it becomes a queen
214                 # I know you are supposed to get a choice
215                 # But that would be effort
216                 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
217                         if self.style == "classical":
218                                 piece.types[0] = "queen"
219                                 piece.types[1] = "queen"
220                         else:
221                                 piece.types[piece.choice] = "queen"
222                         piece.current_type = "queen"
223
224                 piece.deselect() # Uncollapse (?) the wavefunction!
225                 self.moves += 1
226                 
227                 # All other pieces need to recalculate moves
228                 for p in self.pieces["white"] + self.pieces["black"]:
229                         p.possible_moves = None
230                 
231                 #self.verify()  
232
233         # Update the board from a string
234         # Guesses what to do based on the format of the string
235         def update(self, result, sanity=True, deselect=True):
236                 debug(str(self) + " update called \""+str(result)+"\"")
237                 # String always starts with 'x y'
238                 try:
239                         s = result.split(" ")
240                         [x,y] = map(int, s[0:2])        
241                 except:
242                         raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
243
244                 piece = self.grid[x][y]
245                 if piece == None and sanity == True:
246                         raise Exception("EMPTY " + str(x) + " " + str(y))
247
248                 # If a piece is being moved, the third token is '->'
249                 # We could get away with just using four integers, but that wouldn't look as cool
250                 if "->" in s:
251                         # Last two tokens are the destination
252                         try:
253                                 [x2,y2] = map(int, s[3:])
254                         except:
255                                 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
256
257                         # Move the piece (take opponent if possible)
258                         self.update_move(x, y, x2, y2, sanity)
259                         
260                 else:
261                         # Otherwise we will just assume a piece has been selected
262                         try:
263                                 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
264                                 state = s[3] # The last token is a string identifying the type
265                         except:
266                                 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
267
268
269                         # Select the piece
270                         self.update_select(x, y, type_index, state, sanity=sanity, deselect=deselect)
271
272                 return result
273
274         # Gets each piece that could reach the given square and the probability that it could reach that square 
275         # Will include allied pieces that defend the attacker
276         def coverage(self, x, y, colour = None, reject_allied = True):
277                 result = {}
278                 
279                 if colour == None:
280                         pieces = self.pieces["white"] + self.pieces["black"]
281                 else:
282                         pieces = self.pieces[colour]
283
284                 for p in pieces:
285                         prob = self.probability_grid(p, reject_allied)[x][y]
286                         if prob > 0:
287                                 result.update({p : prob})
288                 
289                 #self.verify()
290                 return result
291
292
293                 
294
295
296         # Associates each square with a probability that the piece could move into it
297         # Look, I'm doing all the hard work for you here...
298         def probability_grid(self, p, reject_allied = True):
299                 
300                 result = [[0.0] * w for _ in range(h)]
301                 if not isinstance(p, Piece):
302                         return result
303
304                 if p.current_type != "unknown":
305                         #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
306                         for point in self.possible_moves(p, reject_allied):
307                                 result[point[0]][point[1]] = 1.0
308                         return result
309                 
310                 
311                 for i in range(len(p.types)):
312                         t = p.types[i]
313                         prob = 1.0 / float(len(p.types))
314                         if t == "unknown" or p.types[i][0] == '?':
315                                 total_types = 0
316                                 for t2 in self.unrevealed_types[p.colour].keys():
317                                         total_types += self.unrevealed_types[p.colour][t2]
318                                 
319                                 for t2 in self.unrevealed_types[p.colour].keys():
320                                         prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
321                                         #p.current_type = t2
322                                         for point in self.possible_moves(p, reject_allied, state=t2):
323                                                 result[point[0]][point[1]] += prob2 * prob
324                                 
325                         else:
326                                 #p.current_type = t
327                                 for point in self.possible_moves(p, reject_allied, state=t):
328                                                 result[point[0]][point[1]] += prob
329                 
330                 #self.verify()
331                 #p.current_type = "unknown"
332                 return result
333
334         def prob_is_type(self, p, state):
335                 prob = 0.5
336                 result = 0
337                 for i in range(len(p.types)):
338                         t = p.types[i]
339                         if t == state:
340                                 result += prob
341                                 continue        
342                         if t == "unknown" or p.types[i][0] == '?':
343                                 total_prob = 0
344                                 for t2 in self.unrevealed_types[p.colour].keys():
345                                         total_prob += self.unrevealed_types[p.colour][t2]
346                                 for t2 in self.unrevealed_types[p.colour].keys():
347                                         if t2 == state:
348                                                 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
349                                 
350
351
352         # Get all squares that the piece could move into
353         # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
354         # reject_allied indicates whether squares occupied by allied pieces will be removed
355         # (set to false to check for defense)
356         def possible_moves(self, p, reject_allied = True, state=None):
357                 if p == None:
358                         raise Exception("SANITY: No piece")
359                 
360                 
361                 
362                 if state != None and state != p.current_type:
363                         old_type = p.current_type
364                         p.current_type = state
365                         result = self.possible_moves(p, reject_allied, state=None)
366                         p.current_type = old_type
367                         return result
368                 
369                 
370                 
371                 
372                 result = []
373                 
374
375                 
376                 if p.current_type == "unknown":
377                         raise Exception("SANITY: Unknown state for piece: "+str(p))
378                         # The below commented out code causes things to break badly
379                         #for t in p.types:
380                         #       if t == "unknown":
381                         #               continue
382                         #       p.current_type = t
383                         #       result += self.possible_moves(p)                                                
384                         #p.current_type = "unknown"
385                         #return result
386
387                 if p.current_type == "king":
388                         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]]
389                 elif p.current_type == "queen":
390                         for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
391                                 result += self.scan(p.x, p.y, d[0], d[1])
392                 elif p.current_type == "bishop":
393                         for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
394                                 result += self.scan(p.x, p.y, d[0], d[1])
395                 elif p.current_type == "rook":
396                         for d in [[-1,0],[1,0],[0,-1],[0,1]]:
397                                 result += self.scan(p.x, p.y, d[0], d[1])
398                 elif p.current_type == "knight":
399                         # I would use two lines, but I'm not sure how python likes that
400                         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]]
401                 elif p.current_type == "pawn":
402                         if p.colour == "white":
403                                 
404                                 # Pawn can't move forward into occupied square
405                                 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
406                                         result = [[p.x,p.y-1]]
407                                 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
408                                         if not self.on_board(f[0], f[1]):
409                                                 continue
410                                         if self.grid[f[0]][f[1]] != None:  # Pawn can take diagonally
411                                                 result.append(f)
412                                 if p.y == h-2:
413                                         # Slightly embarrassing if the pawn jumps over someone on its first move...
414                                         if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
415                                                 result.append([p.x, p.y-2])
416                         else:
417                                 # Vice versa for the black pawn
418                                 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
419                                         result = [[p.x,p.y+1]]
420
421                                 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
422                                         if not self.on_board(f[0], f[1]):
423                                                 continue
424                                         if self.grid[f[0]][f[1]] != None:
425                                                 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
426                                                 result.append(f)
427                                 if p.y == 1:
428                                         if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
429                                                 result.append([p.x, p.y+2])
430
431                         #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
432
433                 # Remove illegal moves
434                 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
435                 for point in result[:]: 
436
437                         if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
438                                 result.remove(point) # Remove locations outside the board
439                                 continue
440                         g = self.grid[point[0]][point[1]]
441                         
442                         if g != None and (g.colour == p.colour and reject_allied == True):
443                                 result.remove(point) # Remove allied pieces
444                 
445                 #self.verify()
446                 
447                 p.possible_moves = result
448                 return result
449
450
451         # Scans in a direction until it hits a piece, returns all squares in the line
452         # (includes the final square (which contains a piece), but not the original square)
453         def scan(self, x, y, vx, vy):
454                 p = []
455                         
456                 xx = x
457                 yy = y
458                 while True:
459                         xx += vx
460                         yy += vy
461                         if not self.on_board(xx, yy):
462                                 break
463                         if not [xx,yy] in p:
464                                 p.append([xx, yy])
465                         g = self.grid[xx][yy]
466                         if g != None:
467                                 return p        
468                                         
469                 return p
470
471         # Returns "white", "black" or "DRAW" if the game should end
472         def end_condition(self):
473                 if self.king["white"] == None:
474                         if self.king["black"] == None:
475                                 return "DRAW" # This shouldn't happen
476                         return "black"
477                 elif self.king["black"] == None:
478                         return "white"
479                 elif len(self.pieces["white"]) == 1 and len(self.pieces["black"]) == 1:
480                         return "DRAW"
481                 elif self.max_moves != None and self.moves > self.max_moves:
482                         return "DRAW"
483                 return None
484
485
486         # I typed the full statement about 30 times before writing this function...
487         def on_board(self, x, y):
488                 return (x >= 0 and x < w) and (y >= 0 and y < h)
489         
490         # Pushes a move temporarily
491         def push_move(self, piece, x, y):
492                 target = self.grid[x][y]
493                 self.move_stack.append([piece, target, piece.x, piece.y, x, y])
494                 [piece.x, piece.y] = [x, y]
495                 self.grid[x][y] = piece
496                 self.grid[piece.x][piece.y] = None
497                 
498                 for p in self.pieces["white"] + self.pieces["black"]:
499                         p.possible_moves = None
500                 
501         # Restore move
502         def pop_move(self):
503                 #print str(self.move_stack)
504                 [piece, target, x1, y1, x2, y2] = self.move_stack[len(self.move_stack)-1]
505                 self.move_stack = self.move_stack[:-1]
506                 piece.x = x1
507                 piece.y = y1
508                 self.grid[x1][y1] = piece
509                 if target != None:
510                         target.x = x2
511                         target.y = y2
512                 self.grid[x2][y2] = target
513                 
514                 for p in self.pieces["white"] + self.pieces["black"]:
515                                 p.possible_moves = None
516                 

UCC git Repository :: git.ucc.asn.au