Did something, apparently
[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):
176                 piece = self.grid[x][y]
177                 if piece.types[type_index] == "unknown":
178                         if not state in self.unrevealed_types[piece.colour].keys() and sanity == True:
179                                 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
180                         self.unrevealed_types[piece.colour][state] -= 1
181                         if self.unrevealed_types[piece.colour][state] <= 0:
182                                 del self.unrevealed_types[piece.colour][state]
183
184                 piece.types[type_index] = state
185                 piece.current_type = state
186
187                 if len(self.possible_moves(piece)) <= 0:
188                         piece.deselect() # Piece can't move; deselect it
189                         
190                 # Piece needs to recalculate moves
191                 piece.possible_moves = None
192                 
193         # Update the board when a piece has been moved
194         def update_move(self, x, y, x2, y2, sanity=True):
195                                 
196                 piece = self.grid[x][y]
197                 #print "Moving " + str(x) + "," + str(y) + " to " + str(x2) + "," + str(y2) + "; possible_moves are " + str(self.possible_moves(piece))
198                 
199                 if not [x2,y2] in self.possible_moves(piece) and sanity == True:
200                         raise Exception("ILLEGAL move " + str(x2)+","+str(y2))
201                 
202                 self.grid[x][y] = None
203                 taken = self.grid[x2][y2]
204                 if taken != None:
205                         if taken.current_type == "king":
206                                 self.king[taken.colour] = None
207                         self.pieces[taken.colour].remove(taken)
208                 self.grid[x2][y2] = piece
209                 piece.x = x2
210                 piece.y = y2
211
212                 # If the piece is a pawn, and it reaches the final row, it becomes a queen
213                 # I know you are supposed to get a choice
214                 # But that would be effort
215                 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
216                         if self.style == "classical":
217                                 piece.types[0] = "queen"
218                                 piece.types[1] = "queen"
219                         else:
220                                 piece.types[piece.choice] = "queen"
221                         piece.current_type = "queen"
222
223                 piece.deselect() # Uncollapse (?) the wavefunction!
224                 self.moves += 1
225                 
226                 # All other pieces need to recalculate moves
227                 for p in self.pieces["white"] + self.pieces["black"]:
228                         p.possible_moves = None
229                 
230                 #self.verify()  
231
232         # Update the board from a string
233         # Guesses what to do based on the format of the string
234         def update(self, result, sanity=True):
235                 #print "Update called with \"" + str(result) + "\""
236                 # String always starts with 'x y'
237                 try:
238                         s = result.split(" ")
239                         [x,y] = map(int, s[0:2])        
240                 except:
241                         raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
242
243                 piece = self.grid[x][y]
244                 if piece == None and sanity == True:
245                         raise Exception("EMPTY")
246
247                 # If a piece is being moved, the third token is '->'
248                 # We could get away with just using four integers, but that wouldn't look as cool
249                 if "->" in s:
250                         # Last two tokens are the destination
251                         try:
252                                 [x2,y2] = map(int, s[3:])
253                         except:
254                                 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
255
256                         # Move the piece (take opponent if possible)
257                         self.update_move(x, y, x2, y2, sanity)
258                         
259                 else:
260                         # Otherwise we will just assume a piece has been selected
261                         try:
262                                 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
263                                 state = s[3] # The last token is a string identifying the type
264                         except:
265                                 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
266
267
268                         # Select the piece
269                         self.update_select(x, y, type_index, state, sanity)
270
271                 return result
272
273         # Gets each piece that could reach the given square and the probability that it could reach that square 
274         # Will include allied pieces that defend the attacker
275         def coverage(self, x, y, colour = None, reject_allied = True):
276                 result = {}
277                 
278                 if colour == None:
279                         pieces = self.pieces["white"] + self.pieces["black"]
280                 else:
281                         pieces = self.pieces[colour]
282
283                 for p in pieces:
284                         prob = self.probability_grid(p, reject_allied)[x][y]
285                         if prob > 0:
286                                 result.update({p : prob})
287                 
288                 #self.verify()
289                 return result
290
291
292                 
293
294
295         # Associates each square with a probability that the piece could move into it
296         # Look, I'm doing all the hard work for you here...
297         def probability_grid(self, p, reject_allied = True):
298                 
299                 result = [[0.0] * w for _ in range(h)]
300                 if not isinstance(p, Piece):
301                         return result
302
303                 if p.current_type != "unknown":
304                         #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
305                         for point in self.possible_moves(p, reject_allied):
306                                 result[point[0]][point[1]] = 1.0
307                         return result
308                 
309                 
310                 for i in range(len(p.types)):
311                         t = p.types[i]
312                         prob = 1.0 / float(len(p.types))
313                         if t == "unknown" or p.types[i][0] == '?':
314                                 total_types = 0
315                                 for t2 in self.unrevealed_types[p.colour].keys():
316                                         total_types += self.unrevealed_types[p.colour][t2]
317                                 
318                                 for t2 in self.unrevealed_types[p.colour].keys():
319                                         prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
320                                         #p.current_type = t2
321                                         for point in self.possible_moves(p, reject_allied, state=t2):
322                                                 result[point[0]][point[1]] += prob2 * prob
323                                 
324                         else:
325                                 #p.current_type = t
326                                 for point in self.possible_moves(p, reject_allied, state=t):
327                                                 result[point[0]][point[1]] += prob
328                 
329                 #self.verify()
330                 #p.current_type = "unknown"
331                 return result
332
333         def prob_is_type(self, p, state):
334                 prob = 0.5
335                 result = 0
336                 for i in range(len(p.types)):
337                         t = p.types[i]
338                         if t == state:
339                                 result += prob
340                                 continue        
341                         if t == "unknown" or p.types[i][0] == '?':
342                                 total_prob = 0
343                                 for t2 in self.unrevealed_types[p.colour].keys():
344                                         total_prob += self.unrevealed_types[p.colour][t2]
345                                 for t2 in self.unrevealed_types[p.colour].keys():
346                                         if t2 == state:
347                                                 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
348                                 
349
350
351         # Get all squares that the piece could move into
352         # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
353         # reject_allied indicates whether squares occupied by allied pieces will be removed
354         # (set to false to check for defense)
355         def possible_moves(self, p, reject_allied = True, state=None):
356                 if p == None:
357                         raise Exception("SANITY: No piece")
358                 
359                 
360                 
361                 if state != None and state != p.current_type:
362                         old_type = p.current_type
363                         p.current_type = state
364                         result = self.possible_moves(p, reject_allied, state=None)
365                         p.current_type = old_type
366                         return result
367                 
368                 
369                 
370                 
371                 result = []
372                 
373
374                 
375                 if p.current_type == "unknown":
376                         raise Exception("SANITY: Piece state unknown")
377                         # The below commented out code causes things to break badly
378                         #for t in p.types:
379                         #       if t == "unknown":
380                         #               continue
381                         #       p.current_type = t
382                         #       result += self.possible_moves(p)                                                
383                         #p.current_type = "unknown"
384                         #return result
385
386                 if p.current_type == "king":
387                         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]]
388                 elif p.current_type == "queen":
389                         for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
390                                 result += self.scan(p.x, p.y, d[0], d[1])
391                 elif p.current_type == "bishop":
392                         for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
393                                 result += self.scan(p.x, p.y, d[0], d[1])
394                 elif p.current_type == "rook":
395                         for d in [[-1,0],[1,0],[0,-1],[0,1]]:
396                                 result += self.scan(p.x, p.y, d[0], d[1])
397                 elif p.current_type == "knight":
398                         # I would use two lines, but I'm not sure how python likes that
399                         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]]
400                 elif p.current_type == "pawn":
401                         if p.colour == "white":
402                                 
403                                 # Pawn can't move forward into occupied square
404                                 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
405                                         result = [[p.x,p.y-1]]
406                                 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
407                                         if not self.on_board(f[0], f[1]):
408                                                 continue
409                                         if self.grid[f[0]][f[1]] != None:  # Pawn can take diagonally
410                                                 result.append(f)
411                                 if p.y == h-2:
412                                         # Slightly embarrassing if the pawn jumps over someone on its first move...
413                                         if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
414                                                 result.append([p.x, p.y-2])
415                         else:
416                                 # Vice versa for the black pawn
417                                 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
418                                         result = [[p.x,p.y+1]]
419
420                                 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
421                                         if not self.on_board(f[0], f[1]):
422                                                 continue
423                                         if self.grid[f[0]][f[1]] != None:
424                                                 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
425                                                 result.append(f)
426                                 if p.y == 1:
427                                         if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
428                                                 result.append([p.x, p.y+2])
429
430                         #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
431
432                 # Remove illegal moves
433                 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
434                 for point in result[:]: 
435
436                         if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
437                                 result.remove(point) # Remove locations outside the board
438                                 continue
439                         g = self.grid[point[0]][point[1]]
440                         
441                         if g != None and (g.colour == p.colour and reject_allied == True):
442                                 result.remove(point) # Remove allied pieces
443                 
444                 #self.verify()
445                 
446                 p.possible_moves = result
447                 return result
448
449
450         # Scans in a direction until it hits a piece, returns all squares in the line
451         # (includes the final square (which contains a piece), but not the original square)
452         def scan(self, x, y, vx, vy):
453                 p = []
454                         
455                 xx = x
456                 yy = y
457                 while True:
458                         xx += vx
459                         yy += vy
460                         if not self.on_board(xx, yy):
461                                 break
462                         if not [xx,yy] in p:
463                                 p.append([xx, yy])
464                         g = self.grid[xx][yy]
465                         if g != None:
466                                 return p        
467                                         
468                 return p
469
470         # Returns "white", "black" or "DRAW" if the game should end
471         def end_condition(self):
472                 if self.king["white"] == None:
473                         if self.king["black"] == None:
474                                 return "DRAW" # This shouldn't happen
475                         return "black"
476                 elif self.king["black"] == None:
477                         return "white"
478                 elif len(self.pieces["white"]) == 1 and len(self.pieces["black"]) == 1:
479                         return "DRAW"
480                 elif self.max_moves != None and self.moves > self.max_moves:
481                         return "DRAW"
482                 return None
483
484
485         # I typed the full statement about 30 times before writing this function...
486         def on_board(self, x, y):
487                 return (x >= 0 and x < w) and (y >= 0 and y < h)
488         
489         # Pushes a move temporarily
490         def push_move(self, piece, x, y):
491                 target = self.grid[x][y]
492                 self.move_stack.append([piece, target, piece.x, piece.y, x, y])
493                 [piece.x, piece.y] = [x, y]
494                 self.grid[x][y] = piece
495                 self.grid[piece.x][piece.y] = None
496                 
497                 for p in self.pieces["white"] + self.pieces["black"]:
498                         p.possible_moves = None
499                 
500         # Restore move
501         def pop_move(self):
502                 #print str(self.move_stack)
503                 [piece, target, x1, y1, x2, y2] = self.move_stack[len(self.move_stack)-1]
504                 self.move_stack = self.move_stack[:-1]
505                 piece.x = x1
506                 piece.y = y1
507                 self.grid[x1][y1] = piece
508                 if target != None:
509                         target.x = x2
510                         target.y = y2
511                 self.grid[x2][y2] = target
512                 
513                 for p in self.pieces["white"] + self.pieces["black"]:
514                                 p.possible_moves = None
515                 

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