Messing with log files
[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                 for c in ["black", "white"]:
19                         del self.unrevealed_types[c]["unknown"]
20
21                 if style == "empty":
22                         return
23
24                 # Add all the pieces with known primary types
25                 for i in range(0, 2):
26                         
27                         s = ["black", "white"][i]
28                         c = self.pieces[s]
29                         y = [0, h-1][i]
30
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"
36                         self.king[s] = k
37                         c.append(k)
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"]))
42                         
43                         if y == 0: 
44                                 y += 1 
45                         else: 
46                                 y -= 1
47                         
48                         # Lots of pawn
49                         for x in range(0, w):
50                                 c.append(Piece(s, x, y, ["pawn"]))
51
52                         types_left = {}
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!
56                         for piece in c:
57                                 # Add to grid
58                                 self.grid[piece.x][piece.y] = piece 
59
60                                 if len(piece.types) > 1:
61                                         continue                                
62                                 if style == "agent": # Assign placeholder "unknown" secondary type
63                                         piece.types.append("unknown")
64                                         continue
65
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]
76                                         piece.choice = 0
77
78         def clone(self):
79                 newboard = Board(master = False)
80                 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
81                 mypieces = self.pieces["white"] + self.pieces["black"]
82
83                 for i in range(len(mypieces)):
84                         newpieces[i].init_from_copy(mypieces[i])
85         
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)]
91                 for x in range(w):
92                         for y in range(h):
93                                 self.grid[x][y] = None
94
95                 for line in s.split("\n"):
96                         if line == "":
97                                 continue
98                         if line[0] == "#":
99                                 continue
100
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(','))
105                         
106                         target = Piece(tokens[0], x, y, types)
107                         target.current_type = current_type
108                         
109                         try:
110                                 target.choice = types.index(current_type)
111                         except:
112                                 target.choice = -1
113
114                         self.pieces[tokens[0]].append(target)
115                         if target.current_type == "king":
116                                 self.king[tokens[0]] = target
117
118                         self.grid[x][y] = target
119                         
120
121         def display_grid(self, window = None, grid_sz = [80,80]):
122                 if window == None:
123                         return # I was considering implementing a text only display, then I thought "Fuck that"
124
125                 # The indentation is getting seriously out of hand...
126                 for x in range(0, w):
127                         for y in range(0, h):
128                                 if (x + y) % 2 == 0:
129                                         c = pygame.Color(200,200,200)
130                                 else:
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]))
133
134         def display_pieces(self, window = None, grid_sz = [80,80]):
135                 if window == None:
136                         return
137                 for p in self.pieces["white"] + self.pieces["black"]:
138                         p.draw(window, grid_sz, self.style)
139
140         # Draw the board in a pygame window
141         def display(self, window = None):
142                 self.display_grid(window)
143                 self.display_pieces(window)
144                 
145
146                 
147
148         def verify(self):
149                 for x in range(w):
150                         for y in range(h):
151                                 if self.grid[x][y] == None:
152                                         continue
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))
155
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")
160
161                 piece = self.grid[x][y]
162                 if piece == None:
163                         raise Exception("EMPTY")
164
165                 if colour != None and piece.colour != colour:
166                         raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
167
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)
170
171
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]
182
183                 piece.types[type_index] = state
184                 piece.current_type = state
185
186                 if len(self.possible_moves(piece)) <= 0:
187                         piece.deselect() # Piece can't move; deselect it
188                 
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]
194                 if taken != None:
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
199                 piece.x = x2
200                 piece.y = y2
201
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"
209                         else:
210                                 piece.types[piece.choice] = "queen"
211                         piece.current_type = "queen"
212
213                 piece.deselect() # Uncollapse (?) the wavefunction!
214                 self.moves += 1
215                 #self.verify()  
216
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'
222                 try:
223                         s = result.split(" ")
224                         [x,y] = map(int, s[0:2])        
225                 except:
226                         raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
227
228                 piece = self.grid[x][y]
229                 if piece == None:
230                         raise Exception("EMPTY")
231
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
234                 if "->" in s:
235                         # Last two tokens are the destination
236                         try:
237                                 [x2,y2] = map(int, s[3:])
238                         except:
239                                 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
240
241                         # Move the piece (take opponent if possible)
242                         self.update_move(x, y, x2, y2)
243                         
244                 else:
245                         # Otherwise we will just assume a piece has been selected
246                         try:
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
249                         except:
250                                 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
251
252                         # Select the piece
253                         self.update_select(x, y, type_index, state)
254
255                 return result
256
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):
260                 result = {}
261                 
262                 if colour == None:
263                         pieces = self.pieces["white"] + self.pieces["black"]
264                 else:
265                         pieces = self.pieces[colour]
266
267                 for p in pieces:
268                         prob = self.probability_grid(p, reject_allied)[x][y]
269                         if prob > 0:
270                                 result.update({p : prob})
271                 
272                 self.verify()
273                 return result
274
275
276                 
277
278
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):
282                 
283                 result = [[0.0] * w for _ in range(h)]
284                 if not isinstance(p, Piece):
285                         return result
286
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
291                         return result
292                 
293                 
294                 for i in range(len(p.types)):
295                         t = p.types[i]
296                         prob = 0.5
297                         if t == "unknown" or p.types[i][0] == '?':
298                                 total_types = 0
299                                 for t2 in self.unrevealed_types[p.colour].keys():
300                                         total_types += self.unrevealed_types[p.colour][t2]
301                                 
302                                 for t2 in self.unrevealed_types[p.colour].keys():
303                                         prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
304                                         p.current_type = t2
305                                         for point in self.possible_moves(p, reject_allied):
306                                                 result[point[0]][point[1]] += prob2 * prob
307                                 
308                         else:
309                                 p.current_type = t
310                                 for point in self.possible_moves(p, reject_allied):
311                                         result[point[0]][point[1]] += prob
312                 
313                 self.verify()
314                 p.current_type = "unknown"
315                 return result
316
317         def prob_is_type(self, p, state):
318                 prob = 0.5
319                 result = 0
320                 for i in range(len(p.types)):
321                         t = p.types[i]
322                         if t == state:
323                                 result += prob
324                                 continue        
325                         if t == "unknown" or p.types[i][0] == '?':
326                                 total_prob = 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():
330                                         if t2 == state:
331                                                 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
332                                 
333
334
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):
340                 result = []
341                 if p == None:
342                         return result
343
344                 
345                 if p.current_type == "unknown":
346                         raise Exception("SANITY: Piece state unknown")
347                         # The below commented out code causes things to break badly
348                         #for t in p.types:
349                         #       if t == "unknown":
350                         #               continue
351                         #       p.current_type = t
352                         #       result += self.possible_moves(p)                                                
353                         #p.current_type = "unknown"
354                         #return result
355
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":
372                                 
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]):
378                                                 continue
379                                         if self.grid[f[0]][f[1]] != None:  # Pawn can take diagonally
380                                                 result.append(f)
381                                 if p.y == h-2:
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])
385                         else:
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]]
389
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]):
392                                                 continue
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")
395                                                 result.append(f)
396                                 if p.y == 1:
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])
399
400                         #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
401
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[:]: 
405
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
408                                 continue
409                         g = self.grid[point[0]][point[1]]
410                         
411                         if g != None and (g.colour == p.colour and reject_allied == True):
412                                 result.remove(point) # Remove allied pieces
413                 
414                 self.verify()
415                 return result
416
417
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):
421                 p = []
422                         
423                 xx = x
424                 yy = y
425                 while True:
426                         xx += vx
427                         yy += vy
428                         if not self.on_board(xx, yy):
429                                 break
430                         if not [xx,yy] in p:
431                                 p.append([xx, yy])
432                         g = self.grid[xx][yy]
433                         if g != None:
434                                 return p        
435                                         
436                 return p
437
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
443                         return "black"
444                 elif self.king["black"] == None:
445                         return "white"
446                 elif len(self.pieces["white"]) == 1 and len(self.pieces["black"]) == 1:
447                         return "DRAW"
448                 elif self.max_moves != None and self.moves > self.max_moves:
449                         return "DRAW"
450                 return None
451
452
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)

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