51e73042a3584ce30342f015774b9d596987abfc
[progcomp2013.git] / qchess / qchess.py
1 #!/usr/bin/python -u
2 # +++ piece.py +++ #
3 import random
4
5 # I know using non-abreviated strings is inefficient, but this is python, who cares?
6 # Oh, yeah, this stores the number of pieces of each type in a normal chess game
7 piece_types = {"pawn" : 8, "bishop" : 2, "knight" : 2, "rook" : 2, "queen" : 1, "king" : 1, "unknown" : 0}
8
9 # Class to represent a quantum chess piece
10 class Piece():
11         def __init__(self, colour, x, y, types):
12                 self.colour = colour # Colour (string) either "white" or "black"
13                 self.x = x # x coordinate (0 - 8), none of this fancy 'a', 'b' shit here
14                 self.y = y # y coordinate (0 - 8)
15                 self.types = types # List of possible types the piece can be (should just be two)
16                 self.current_type = "unknown" # Current type
17                 self.choice = -1 # Index of the current type in self.types (-1 = unknown type)
18                 self.types_revealed = [True, False] # Whether the types are known (by default the first type is always known at game start)
19                 
20
21                 # 
22                 self.last_state = None
23                 self.move_pattern = None
24
25                 
26
27         def init_from_copy(self, c):
28                 self.colour = c.colour
29                 self.x = c.x
30                 self.y = c.y
31                 self.types = c.types[:]
32                 self.current_type = c.current_type
33                 self.choice = c.choice
34                 self.types_revealed = c.types_revealed[:]
35
36                 self.last_state = None
37                 self.move_pattern = None
38
39         
40
41         # Make a string for the piece (used for debug)
42         def __str__(self):
43                 return str(self.current_type) + " " + str(self.types) + " at " + str(self.x) + ","+str(self.y)  
44
45         # Draw the piece in a pygame surface
46         def draw(self, window, grid_sz = [80,80]):
47
48                 # First draw the image corresponding to self.current_type
49                 img = images[self.colour][self.current_type]
50                 rect = img.get_rect()
51                 offset = [-rect.width/2,-3*rect.height/4] 
52                 window.blit(img, (self.x * grid_sz[0] + grid_sz[0]/2 + offset[0], self.y * grid_sz[1] + grid_sz[1]/2 + offset[1]))
53                 
54                 
55                 # Draw the two possible types underneath the current_type image
56                 for i in range(len(self.types)):
57                         if self.types_revealed[i] == True:
58                                 img = small_images[self.colour][self.types[i]]
59                         else:
60                                 img = small_images[self.colour]["unknown"] # If the type hasn't been revealed, show a placeholder
61
62                         
63                         rect = img.get_rect()
64                         offset = [-rect.width/2,-rect.height/2] 
65                         
66                         if i == 0:
67                                 target = (self.x * grid_sz[0] + grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])                             
68                         else:
69                                 target = (self.x * grid_sz[0] + 4*grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])                           
70                                 
71                         window.blit(img, target) # Blit shit
72         
73         # Collapses the wave function!          
74         def select(self):
75                 if self.current_type == "unknown":
76                         self.choice = random.randint(0,1)
77                         self.current_type = self.types[self.choice]
78                         self.types_revealed[self.choice] = True
79                 return self.choice
80
81         # Uncollapses (?) the wave function!
82         def deselect(self):
83                 #print "Deselect called"
84                 if (self.x + self.y) % 2 != 0:
85                         if (self.types[0] != self.types[1]) or (self.types_revealed[0] == False or self.types_revealed[1] == False):
86                                 self.current_type = "unknown"
87                                 self.choice = -1
88                         else:
89                                 self.choice = 0 # Both the two types are the same
90
91         # The sad moment when you realise that you do not understand anything about a subject you studied for 4 years...
92 # --- piece.py --- #
93 # +++ board.py +++ #
94 [w,h] = [8,8] # Width and height of board(s)
95
96 # Class to represent a quantum chess board
97 class Board():
98         # Initialise; if master=True then the secondary piece types are assigned
99         #       Otherwise, they are left as unknown
100         #       So you can use this class in Agent programs, and fill in the types as they are revealed
101         def __init__(self, style="agent"):
102                 self.style = style
103                 self.pieces = {"white" : [], "black" : []}
104                 self.grid = [[None] * w for _ in range(h)] # 2D List (you can get arrays in python, somehow, but they scare me)
105                 self.unrevealed_types = {"white" : piece_types.copy(), "black" : piece_types.copy()}
106                 self.king = {"white" : None, "black" : None} # We need to keep track of the king, because he is important
107                 for c in ["black", "white"]:
108                         del self.unrevealed_types[c]["unknown"]
109
110                 # Add all the pieces with known primary types
111                 for i in range(0, 2):
112                         
113                         s = ["black", "white"][i]
114                         c = self.pieces[s]
115                         y = [0, h-1][i]
116
117                         c.append(Piece(s, 0, y, ["rook"]))
118                         c.append(Piece(s, 1, y, ["knight"]))
119                         c.append(Piece(s, 2, y, ["bishop"]))
120                         k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
121                         k.types_revealed[1] = True
122                         k.current_type = "king"
123                         self.king[s] = k
124                         c.append(k)
125                         c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
126                         c.append(Piece(s, 5, y, ["bishop"]))
127                         c.append(Piece(s, 6, y, ["knight"]))
128                         c.append(Piece(s, 7, y, ["rook"]))
129                         
130                         if y == 0: 
131                                 y += 1 
132                         else: 
133                                 y -= 1
134                         
135                         # Lots of pawn
136                         for x in range(0, w):
137                                 c.append(Piece(s, x, y, ["pawn"]))
138
139                         types_left = {}
140                         types_left.update(piece_types)
141                         del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
142                         del types_left["unknown"] # We certainly don't want these!
143                         for piece in c:
144                                 # Add to grid
145                                 self.grid[piece.x][piece.y] = piece 
146
147                                 if len(piece.types) > 1:
148                                         continue                                
149                                 if style == "agent": # Assign placeholder "unknown" secondary type
150                                         piece.types.append("unknown")
151                                         continue
152
153                                 elif style == "quantum":
154                                         # The master allocates the secondary types
155                                         choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
156                                         types_left[choice] -= 1
157                                         if types_left[choice] <= 0:
158                                                 del types_left[choice]
159                                         piece.types.append(choice)
160                                 elif style == "classical":
161                                         piece.types.append(piece.types[0])
162                                         piece.current_type = piece.types[0]
163                                         piece.types_revealed[1] = True
164                                         piece.choice = 0
165
166         def clone(self):
167                 newboard = Board(master = False)
168                 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
169                 mypieces = self.pieces["white"] + self.pieces["black"]
170
171                 for i in range(len(mypieces)):
172                         newpieces[i].init_from_copy(mypieces[i])
173                         
174
175         def display_grid(self, window = None, grid_sz = [80,80]):
176                 if window == None:
177                         return # I was considering implementing a text only display, then I thought "Fuck that"
178
179                 # The indentation is getting seriously out of hand...
180                 for x in range(0, w):
181                         for y in range(0, h):
182                                 if (x + y) % 2 == 0:
183                                         c = pygame.Color(200,200,200)
184                                 else:
185                                         c = pygame.Color(64,64,64)
186                                 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
187
188         def display_pieces(self, window = None, grid_sz = [80,80]):
189                 if window == None:
190                         return
191                 for p in self.pieces["white"] + self.pieces["black"]:
192                         p.draw(window, grid_sz)
193
194         # Draw the board in a pygame window
195         def display(self, window = None):
196                 self.display_grid(window)
197                 self.display_pieces(window)
198                 
199
200                 
201
202         def verify(self):
203                 for x in range(w):
204                         for y in range(h):
205                                 if self.grid[x][y] == None:
206                                         continue
207                                 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
208                                         raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
209
210         # Select a piece on the board (colour is the colour of whoever is doing the selecting)
211         def select(self, x,y, colour=None):
212                 if not self.on_board(x, y): # Get on board everyone!
213                         raise Exception("BOUNDS")
214
215                 piece = self.grid[x][y]
216                 if piece == None:
217                         raise Exception("EMPTY")
218
219                 if colour != None and piece.colour != colour:
220                         raise Exception("COLOUR")
221
222                 # I'm not quite sure why I made this return a string, but screw logical design
223                 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
224
225
226         # Update the board when a piece has been selected
227         # "type" is apparently reserved, so I'll use "state"
228         def update_select(self, x, y, type_index, state):
229                 piece = self.grid[x][y]
230                 if piece.types[type_index] == "unknown":
231                         if not state in self.unrevealed_types[piece.colour].keys():
232                                 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
233                         self.unrevealed_types[piece.colour][state] -= 1
234                         if self.unrevealed_types[piece.colour][state] <= 0:
235                                 del self.unrevealed_types[piece.colour][state]
236
237                 piece.types[type_index] = state
238                 piece.types_revealed[type_index] = True
239                 piece.current_type = state
240
241                 if len(self.possible_moves(piece)) <= 0:
242                         piece.deselect() # Piece can't move; deselect it
243                 
244         # Update the board when a piece has been moved
245         def update_move(self, x, y, x2, y2):
246                 piece = self.grid[x][y]
247                 self.grid[x][y] = None
248                 taken = self.grid[x2][y2]
249                 if taken != None:
250                         if taken.current_type == "king":
251                                 self.king[taken.colour] = None
252                         self.pieces[taken.colour].remove(taken)
253                 self.grid[x2][y2] = piece
254                 piece.x = x2
255                 piece.y = y2
256
257                 # If the piece is a pawn, and it reaches the final row, it becomes a queen
258                 # I know you are supposed to get a choice
259                 # But that would be effort
260                 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
261                         if self.style == "classical":
262                                 piece.types[0] = "queen"
263                                 piece.types[1] = "queen"
264                         else:
265                                 piece.types[piece.choice] = "queen"
266                         piece.current_type = "queen"
267
268                 piece.deselect() # Uncollapse (?) the wavefunction!
269                 self.verify()   
270
271         # Update the board from a string
272         # Guesses what to do based on the format of the string
273         def update(self, result):
274                 #print "Update called with \"" + str(result) + "\""
275                 # String always starts with 'x y'
276                 try:
277                         s = result.split(" ")
278                         [x,y] = map(int, s[0:2])        
279                 except:
280                         raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
281
282                 piece = self.grid[x][y]
283                 if piece == None:
284                         raise Exception("EMPTY")
285
286                 # If a piece is being moved, the third token is '->'
287                 # We could get away with just using four integers, but that wouldn't look as cool
288                 if "->" in s:
289                         # Last two tokens are the destination
290                         try:
291                                 [x2,y2] = map(int, s[3:])
292                         except:
293                                 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
294
295                         # Move the piece (take opponent if possible)
296                         self.update_move(x, y, x2, y2)
297                         
298                 else:
299                         # Otherwise we will just assume a piece has been selected
300                         try:
301                                 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
302                                 state = s[3] # The last token is a string identifying the type
303                         except:
304                                 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
305
306                         # Select the piece
307                         self.update_select(x, y, type_index, state)
308
309                 return result
310
311         # Gets each piece that could reach the given square and the probability that it could reach that square 
312         # Will include allied pieces that defend the attacker
313         def coverage(self, x, y, colour = None, reject_allied = True):
314                 result = {}
315                 
316                 if colour == None:
317                         pieces = self.pieces["white"] + self.pieces["black"]
318                 else:
319                         pieces = self.pieces[colour]
320
321                 for p in pieces:
322                         prob = self.probability_grid(p, reject_allied)[x][y]
323                         if prob > 0:
324                                 result.update({p : prob})
325                 
326                 self.verify()
327                 return result
328
329
330                 
331
332
333         # Associates each square with a probability that the piece could move into it
334         # Look, I'm doing all the hard work for you here...
335         def probability_grid(self, p, reject_allied = True):
336                 
337                 result = [[0.0] * w for _ in range(h)]
338                 if not isinstance(p, Piece):
339                         return result
340
341                 if p.current_type != "unknown":
342                         #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
343                         for point in self.possible_moves(p, reject_allied):
344                                 result[point[0]][point[1]] = 1.0
345                         return result
346                 
347                 
348                 for i in range(len(p.types)):
349                         t = p.types[i]
350                         prob = 0.5
351                         if t == "unknown" or p.types_revealed[i] == False:
352                                 total_types = 0
353                                 for t2 in self.unrevealed_types[p.colour].keys():
354                                         total_types += self.unrevealed_types[p.colour][t2]
355                                 
356                                 for t2 in self.unrevealed_types[p.colour].keys():
357                                         prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
358                                         p.current_type = t2
359                                         for point in self.possible_moves(p, reject_allied):
360                                                 result[point[0]][point[1]] += prob2 * prob
361                                 
362                         else:
363                                 p.current_type = t
364                                 for point in self.possible_moves(p, reject_allied):
365                                         result[point[0]][point[1]] += prob
366                 
367                 self.verify()
368                 p.current_type = "unknown"
369                 return result
370
371         def prob_is_type(self, p, state):
372                 prob = 0.5
373                 result = 0
374                 for i in range(len(p.types)):
375                         t = p.types[i]
376                         if t == state:
377                                 result += prob
378                                 continue        
379                         if t == "unknown" or p.types_revealed[i] == False:
380                                 total_prob = 0
381                                 for t2 in self.unrevealed_types[p.colour].keys():
382                                         total_prob += self.unrevealed_types[p.colour][t2]
383                                 for t2 in self.unrevealed_types[p.colour].keys():
384                                         if t2 == state:
385                                                 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
386                                 
387
388
389         # Get all squares that the piece could move into
390         # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
391         # reject_allied indicates whether squares occupied by allied pieces will be removed
392         # (set to false to check for defense)
393         def possible_moves(self, p, reject_allied = True):
394                 result = []
395                 if p == None:
396                         return result
397
398                 
399                 if p.current_type == "unknown":
400                         raise Exception("SANITY: Piece state unknown")
401                         # The below commented out code causes things to break badly
402                         #for t in p.types:
403                         #       if t == "unknown":
404                         #               continue
405                         #       p.current_type = t
406                         #       result += self.possible_moves(p)                                                
407                         #p.current_type = "unknown"
408                         #return result
409
410                 if p.current_type == "king":
411                         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]]
412                 elif p.current_type == "queen":
413                         for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
414                                 result += self.scan(p.x, p.y, d[0], d[1])
415                 elif p.current_type == "bishop":
416                         for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
417                                 result += self.scan(p.x, p.y, d[0], d[1])
418                 elif p.current_type == "rook":
419                         for d in [[-1,0],[1,0],[0,-1],[0,1]]:
420                                 result += self.scan(p.x, p.y, d[0], d[1])
421                 elif p.current_type == "knight":
422                         # I would use two lines, but I'm not sure how python likes that
423                         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]]
424                 elif p.current_type == "pawn":
425                         if p.colour == "white":
426                                 
427                                 # Pawn can't move forward into occupied square
428                                 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
429                                         result = [[p.x,p.y-1]]
430                                 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
431                                         if not self.on_board(f[0], f[1]):
432                                                 continue
433                                         if self.grid[f[0]][f[1]] != None:  # Pawn can take diagonally
434                                                 result.append(f)
435                                 if p.y == h-2:
436                                         # Slightly embarrassing if the pawn jumps over someone on its first move...
437                                         if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
438                                                 result.append([p.x, p.y-2])
439                         else:
440                                 # Vice versa for the black pawn
441                                 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
442                                         result = [[p.x,p.y+1]]
443
444                                 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
445                                         if not self.on_board(f[0], f[1]):
446                                                 continue
447                                         if self.grid[f[0]][f[1]] != None:
448                                                 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
449                                                 result.append(f)
450                                 if p.y == 1:
451                                         if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
452                                                 result.append([p.x, p.y+2])
453
454                         #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
455
456                 # Remove illegal moves
457                 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
458                 for point in result[:]: 
459
460                         if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
461                                 result.remove(point) # Remove locations outside the board
462                                 continue
463                         g = self.grid[point[0]][point[1]]
464                         
465                         if g != None and (g.colour == p.colour and reject_allied == True):
466                                 result.remove(point) # Remove allied pieces
467                 
468                 self.verify()
469                 return result
470
471
472         # Scans in a direction until it hits a piece, returns all squares in the line
473         # (includes the final square (which contains a piece), but not the original square)
474         def scan(self, x, y, vx, vy):
475                 p = []
476                         
477                 xx = x
478                 yy = y
479                 while True:
480                         xx += vx
481                         yy += vy
482                         if not self.on_board(xx, yy):
483                                 break
484                         if not [xx,yy] in p:
485                                 p.append([xx, yy])
486                         g = self.grid[xx][yy]
487                         if g != None:
488                                 return p        
489                                         
490                 return p
491
492
493
494         # I typed the full statement about 30 times before writing this function...
495         def on_board(self, x, y):
496                 return (x >= 0 and x < w) and (y >= 0 and y < h)
497 # --- board.py --- #
498 # +++ player.py +++ #
499 import subprocess
500
501
502
503 # A player who can't play
504 class Player():
505         def __init__(self, name, colour):
506                 self.name = name
507                 self.colour = colour
508
509 # Player that runs from another process
510 class AgentPlayer(Player):
511         def __init__(self, name, colour):
512                 Player.__init__(self, name, colour)
513                 self.p = subprocess.Popen(name, stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=sys.stderr)
514                 try:
515                         self.p.stdin.write(colour + "\n")
516                 except:
517                         raise Exception("UNRESPONSIVE")
518
519         def select(self):
520                 
521                 #try:
522                 self.p.stdin.write("SELECTION?\n")
523                 line = self.p.stdout.readline().strip("\r\n ")
524                 #except:
525                 #       raise Exception("UNRESPONSIVE")
526                 try:
527                         result = map(int, line.split(" "))
528                 except:
529                         raise Exception("GIBBERISH \"" + str(line) + "\"")
530                 return result
531
532         def update(self, result):
533                 #print "Update " + str(result) + " called for AgentPlayer"
534 #               try:
535                 self.p.stdin.write(result + "\n")
536 #               except:
537 #               raise Exception("UNRESPONSIVE")
538
539         def get_move(self):
540                 
541                 try:
542                         self.p.stdin.write("MOVE?\n")
543                         line = self.p.stdout.readline().strip("\r\n ")
544                 except:
545                         raise Exception("UNRESPONSIVE")
546                 try:
547                         result = map(int, line.split(" "))
548                 except:
549                         raise Exception("GIBBERISH \"" + str(line) + "\"")
550                 return result
551
552         def quit(self, final_result):
553                 try:
554                         self.p.stdin.write("QUIT " + final_result + "\n")
555                 except:
556                         self.p.kill()
557
558 # So you want to be a player here?
559 class HumanPlayer(Player):
560         def __init__(self, name, colour):
561                 Player.__init__(self, name, colour)
562                 
563         # Select your preferred account
564         def select(self):
565                 if isinstance(graphics, GraphicsThread):
566                         # Basically, we let the graphics thread do some shit and then return that information to the game thread
567                         graphics.cond.acquire()
568                         # We wait for the graphics thread to select a piece
569                         while graphics.stopped() == False and graphics.state["select"] == None:
570                                 graphics.cond.wait() # The difference between humans and machines is that humans sleep
571                         select = graphics.state["select"]
572                         
573                         
574                         graphics.cond.release()
575                         if graphics.stopped():
576                                 return [-1,-1]
577                         return [select.x, select.y]
578                 else:
579                         # Since I don't display the board in this case, I'm not sure why I filled it in...
580                         while True:
581                                 sys.stdout.write("SELECTION?\n")
582                                 try:
583                                         p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
584                                 except:
585                                         sys.stderr.write("ILLEGAL GIBBERISH\n")
586                                         continue
587         # It's your move captain
588         def get_move(self):
589                 if isinstance(graphics, GraphicsThread):
590                         graphics.cond.acquire()
591                         while graphics.stopped() == False and graphics.state["dest"] == None:
592                                 graphics.cond.wait()
593                         graphics.cond.release()
594                         
595                         return graphics.state["dest"]
596                 else:
597
598                         while True:
599                                 sys.stdout.write("MOVE?\n")
600                                 try:
601                                         p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
602                                 except:
603                                         sys.stderr.write("ILLEGAL GIBBERISH\n")
604                                         continue
605
606         # Are you sure you want to quit?
607         def quit(self, final_result):
608                 sys.stdout.write("QUIT " + final_result + "\n")
609
610         # Completely useless function
611         def update(self, result):
612                 if isinstance(graphics, GraphicsThread):
613                         pass
614                 else:
615                         sys.stdout.write(result + "\n") 
616
617
618 # Player that makes random moves
619 class AgentRandom(Player):
620         def __init__(self, name, colour):
621                 Player.__init__(self, name, colour)
622                 self.choice = None
623
624                 self.board = Board(style = "agent")
625
626         def select(self):
627                 while True:
628                         self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
629                         all_moves = []
630                         # Check that the piece has some possibility to move
631                         tmp = self.choice.current_type
632                         if tmp == "unknown": # For unknown pieces, try both types
633                                 for t in self.choice.types:
634                                         if t == "unknown":
635                                                 continue
636                                         self.choice.current_type = t
637                                         all_moves += self.board.possible_moves(self.choice)
638                         else:
639                                 all_moves = self.board.possible_moves(self.choice)
640                         self.choice.current_type = tmp
641                         if len(all_moves) > 0:
642                                 break
643                 return [self.choice.x, self.choice.y]
644
645         def get_move(self):
646                 moves = self.board.possible_moves(self.choice)
647                 move = moves[random.randint(0, len(moves)-1)]
648                 return move
649
650         def update(self, result):
651                 #sys.stderr.write(sys.argv[0] + " : Update board for AgentRandom\n")
652                 self.board.update(result)
653                 self.board.verify()
654
655         def quit(self, final_result):
656                 pass
657 # --- player.py --- #
658 # +++ thread_util.py +++ #
659 import threading
660
661 # A thread that can be stopped!
662 # Except it can only be stopped if it checks self.stopped() periodically
663 # So it can sort of be stopped
664 class StoppableThread(threading.Thread):
665         def __init__(self):
666                 threading.Thread.__init__(self)
667                 self._stop = threading.Event()
668
669         def stop(self):
670                 self._stop.set()
671
672         def stopped(self):
673                 return self._stop.isSet()
674 # --- thread_util.py --- #
675 # +++ game.py +++ #
676
677 # A thread that runs the game
678 class GameThread(StoppableThread):
679         def __init__(self, board, players):
680                 StoppableThread.__init__(self)
681                 self.board = board
682                 self.players = players
683                 self.state = {"turn" : None} # The game state
684                 self.error = 0 # Whether the thread exits with an error
685                 self.lock = threading.RLock() #lock for access of self.state
686                 self.cond = threading.Condition() # conditional for some reason, I forgot
687                 self.final_result = ""
688
689         # Run the game (run in new thread with start(), run in current thread with run())
690         def run(self):
691                 result = ""
692                 while not self.stopped():
693                         
694                         for p in self.players:
695                                 with self.lock:
696                                         self.state["turn"] = p # "turn" contains the player who's turn it is
697                                 #try:
698                                 if True:
699                                         [x,y] = p.select() # Player selects a square
700                                         if self.stopped():
701                                                 break
702
703                                         result = self.board.select(x, y, colour = p.colour)                             
704                                         for p2 in self.players:
705                                                 p2.update(result) # Inform players of what happened
706
707
708
709                                         target = self.board.grid[x][y]
710                                         if isinstance(graphics, GraphicsThread):
711                                                 with graphics.lock:
712                                                         graphics.state["moves"] = self.board.possible_moves(target)
713                                                         graphics.state["select"] = target
714
715                                         time.sleep(turn_delay)
716
717
718                                         if len(self.board.possible_moves(target)) == 0:
719                                                 #print "Piece cannot move"
720                                                 target.deselect()
721                                                 if isinstance(graphics, GraphicsThread):
722                                                         with graphics.lock:
723                                                                 graphics.state["moves"] = None
724                                                                 graphics.state["select"] = None
725                                                                 graphics.state["dest"] = None
726                                                 continue
727
728                                         try:
729                                                 [x2,y2] = p.get_move() # Player selects a destination
730                                         except:
731                                                 self.stop()
732
733                                         if self.stopped():
734                                                 break
735
736                                         result = self.board.update_move(x, y, x2, y2)
737                                         for p2 in self.players:
738                                                 p2.update(str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)) # Inform players of what happened
739
740                                         if isinstance(graphics, GraphicsThread):
741                                                 with graphics.lock:
742                                                         graphics.state["moves"] = [[x2,y2]]
743
744                                         time.sleep(turn_delay)
745
746                                         if isinstance(graphics, GraphicsThread):
747                                                 with graphics.lock:
748                                                         graphics.state["select"] = None
749                                                         graphics.state["dest"] = None
750                                                         graphics.state["moves"] = None
751
752                         # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
753                                 #except Exception,e:
754                                         #result = "ILLEGAL " + e.message
755                                         #sys.stderr.write(result + "\n")
756                                         
757                                         #self.stop()
758                                         #with self.lock:
759                                         #       self.final_result = self.state["turn"].colour + " " + "ILLEGAL"
760
761                                 if self.board.king["black"] == None:
762                                         if self.board.king["white"] == None:
763                                                 with self.lock:
764                                                         self.final_result = "DRAW"
765                                         else:
766                                                 with self.lock:
767                                                         self.final_result = "white"
768                                         self.stop()
769                                 elif self.board.king["white"] == None:
770                                         with self.lock:
771                                                 self.final_result = "black"
772                                         self.stop()
773                                                 
774
775                                 if self.stopped():
776                                         break
777
778
779                 for p2 in self.players:
780                         p2.quit(self.final_result)
781
782                 graphics.stop()
783
784         
785
786
787 def opponent(colour):
788         if colour == "white":
789                 return "black"
790         else:
791                 return "white"
792 # --- game.py --- #
793 # +++ graphics.py +++ #
794 import pygame
795
796 # Dictionary that stores the unicode character representations of the different pieces
797 # Chess was clearly the reason why unicode was invented
798 # For some reason none of the pygame chess implementations I found used them!
799 piece_char = {"white" : {"king" : u'\u2654',
800                          "queen" : u'\u2655',
801                          "rook" : u'\u2656',
802                          "bishop" : u'\u2657',
803                          "knight" : u'\u2658',
804                          "pawn" : u'\u2659',
805                          "unknown" : '?'},
806                 "black" : {"king" : u'\u265A',
807                          "queen" : u'\u265B',
808                          "rook" : u'\u265C',
809                          "bishop" : u'\u265D',
810                          "knight" : u'\u265E',
811                          "pawn" : u'\u265F',
812                          "unknown" : '?'}}
813
814 images = {"white" : {}, "black" : {}}
815 small_images = {"white" : {}, "black" : {}}
816
817 # A thread to make things pretty
818 class GraphicsThread(StoppableThread):
819         def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
820                 StoppableThread.__init__(self)
821                 
822                 self.board = board
823                 pygame.init()
824                 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
825                 pygame.display.set_caption(title)
826                 self.grid_sz = grid_sz[:]
827                 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
828                 self.error = 0
829                 self.lock = threading.RLock()
830                 self.cond = threading.Condition()
831
832                 # Get the font sizes
833                 l_size = 5*(self.grid_sz[0] / 8)
834                 s_size = 3*(self.grid_sz[0] / 8)
835                 for p in piece_types.keys():
836                         c = "black"
837                         images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", l_size).render(piece_char[c][p], True,(0,0,0))})
838                         small_images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", s_size).render(piece_char[c][p],True,(0,0,0))})
839                         c = "white"
840
841                         images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", l_size+1).render(piece_char["black"][p], True,(255,255,255))})
842                         images[c][p].blit(pygame.font.Font("data/DejaVuSans.ttf", l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
843                         small_images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", s_size+1).render(piece_char["black"][p],True,(255,255,255))})
844                         small_images[c][p].blit(pygame.font.Font("data/DejaVuSans.ttf", s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
845
846                 
847         
848
849
850         # On the run from the world
851         def run(self):
852                 
853                 while not self.stopped():
854                         
855                         self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
856
857                         self.overlay()
858
859                         self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board                
860
861                         pygame.display.flip()
862
863                         for event in pygame.event.get():
864                                 if event.type == pygame.QUIT:
865                                         if isinstance(game, GameThread):
866                                                 with game.lock:
867                                                         game.final_result = "terminated"
868                                                 game.stop()
869                                         self.stop()
870                                         break
871                                 elif event.type == pygame.MOUSEBUTTONDOWN:
872                                         self.mouse_down(event)
873                                 elif event.type == pygame.MOUSEBUTTONUP:
874                                         self.mouse_up(event)
875                                         
876
877                                 
878                                                                 
879                                                 
880                                                 
881                 self.message("Game ends, result \""+str(game.final_result) + "\"")
882                 time.sleep(1)
883
884                 # Wake up anyone who is sleeping
885                 self.cond.acquire()
886                 self.cond.notify()
887                 self.cond.release()
888
889                 pygame.quit() # Time to say goodbye
890
891         # Mouse release event handler
892         def mouse_up(self, event):
893                 if event.button == 3:
894                         with self.lock:
895                                 self.state["overlay"] = None
896                 elif event.button == 2:
897                         with self.lock:
898                                 self.state["coverage"] = None   
899
900         # Mouse click event handler
901         def mouse_down(self, event):
902                 if event.button == 1:
903                         m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
904                         if isinstance(game, GameThread):
905                                 with game.lock:
906                                         p = game.state["turn"]
907                         else:
908                                         p = None
909                                         
910                                         
911                         if isinstance(p, HumanPlayer):
912                                 with self.lock:
913                                         s = self.board.grid[m[0]][m[1]]
914                                         select = self.state["select"]
915                                 if select == None:
916                                         if s != None and s.colour != p.colour:
917                                                 self.message("Wrong colour") # Look at all this user friendliness!
918                                                 time.sleep(1)
919                                                 return
920                                         # Notify human player of move
921                                         self.cond.acquire()
922                                         with self.lock:
923                                                 self.state["select"] = s
924                                                 self.state["dest"] = None
925                                         self.cond.notify()
926                                         self.cond.release()
927                                         return
928
929                                 if select == None:
930                                         return
931                                                 
932                                         
933                                 if self.state["moves"] == None:
934                                         return
935
936                                 if not m in self.state["moves"]:
937                                         self.message("Illegal Move") # I still think last year's mouse interface was adequate
938                                         time.sleep(2)
939                                         return
940                                                 
941                                 with self.lock:
942                                         if self.state["dest"] == None:
943                                                 self.cond.acquire()
944                                                 self.state["dest"] = m
945                                                 self.state["select"] = None
946                                                 self.state["moves"] = None
947                                                 self.cond.notify()
948                                                 self.cond.release()
949                 elif event.button == 3:
950                         m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
951                         if isinstance(game, GameThread):
952                                 with game.lock:
953                                         p = game.state["turn"]
954                         else:
955                                 p = None
956                                         
957                                         
958                         if isinstance(p, HumanPlayer):
959                                 with self.lock:
960                                         self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
961
962                 elif event.button == 2:
963                         m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
964                         if isinstance(game, GameThread):
965                                 with game.lock:
966                                         p = game.state["turn"]
967                         else:
968                                 p = None
969                         
970                         
971                         if isinstance(p, HumanPlayer):
972                                 with self.lock:
973                                         self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
974                                 
975         # Draw the overlay
976         def overlay(self):
977
978                 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
979                 # Draw square over the selected piece
980                 with self.lock:
981                         select = self.state["select"]
982                 if select != None:
983                         mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
984                         square_img.fill(pygame.Color(0,255,0,64))
985                         self.window.blit(square_img, mp)
986                 # If a piece is selected, draw all reachable squares
987                 # (This quality user interface has been patented)
988                 with self.lock:
989                         m = self.state["moves"]
990                 if m != None:
991                         square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
992                         for move in m:
993                                 mp = [self.grid_sz[i] * move[i] for i in range(2)]
994                                 self.window.blit(square_img, mp)
995                 # If a piece is overlayed, show all squares that it has a probability to reach
996                 with self.lock:
997                         m = self.state["overlay"]
998                 if m != None:
999                         for x in range(w):
1000                                 for y in range(h):
1001                                         if m[x][y] > 0.0:
1002                                                 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
1003                                                 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
1004                                                 self.window.blit(square_img, mp)
1005                                                 font = pygame.font.Font(None, 14)
1006                                                 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
1007                                                 self.window.blit(text, mp)
1008                                 
1009                 # If a square is selected, highlight all pieces that have a probability to reach it
1010                 with self.lock:                         
1011                         m = self.state["coverage"]
1012                 if m != None:
1013                         for p in m:
1014                                 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
1015                                 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
1016                                 self.window.blit(square_img, mp)
1017                                 font = pygame.font.Font(None, 14)
1018                                 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
1019                                 self.window.blit(text, mp)
1020                         # Draw a square where the mouse is
1021                 # This also serves to indicate who's turn it is
1022                 
1023                 if isinstance(game, GameThread):
1024                         with game.lock:
1025                                 turn = game.state["turn"]
1026                 else:
1027                         turn = None
1028
1029                 if isinstance(turn, HumanPlayer):
1030                         mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
1031                         square_img.fill(pygame.Color(0,0,255,128))
1032                         if turn.colour == "white":
1033                                 c = pygame.Color(255,255,255)
1034                         else:
1035                                 c = pygame.Color(0,0,0)
1036                         pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
1037                         self.window.blit(square_img, mp)
1038
1039         # Message in a bottle
1040         def message(self, string, pos = None, colour = None, font_size = 32):
1041                 font = pygame.font.Font(None, font_size)
1042                 if colour == None:
1043                         colour = pygame.Color(0,0,0)
1044                 
1045                 text = font.render(string, 1, colour)
1046         
1047
1048                 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
1049                 s.fill(pygame.Color(128,128,128))
1050
1051                 tmp = self.window.get_size()
1052
1053                 if pos == None:
1054                         pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
1055                 else:
1056                         pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
1057                 
1058
1059                 rect = (pos[0], pos[1], text.get_width(), text.get_height())
1060         
1061                 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
1062                 self.window.blit(s, pos)
1063                 self.window.blit(text, pos)
1064
1065                 pygame.display.flip()
1066
1067         def getstr(self, prompt = None):
1068                 result = ""
1069                 while True:
1070                         #print "LOOP"
1071                         if prompt != None:
1072                                 self.message(prompt)
1073                                 self.message(result, pos = (0, 1))
1074         
1075                         for event in pygame.event.get():
1076                                 if event.type == pygame.KEYDOWN:
1077                                         if chr(event.key) == '\r':
1078                                                 return result
1079                                         result += str(chr(event.key))
1080 # --- graphics.py --- #
1081 # +++ main.py +++ #
1082 #!/usr/bin/python -u
1083
1084 # Do you know what the -u does? It unbuffers stdin and stdout
1085 # I can't remember why, but last year things broke without that
1086
1087 """
1088         UCC::Progcomp 2013 Quantum Chess game
1089         @author Sam Moore [SZM] "matches"
1090         @copyright The University Computer Club, Incorporated
1091                 (ie: You can copy it for not for profit purposes)
1092 """
1093
1094 # system python modules or whatever they are called
1095 import sys
1096 import os
1097 import time
1098
1099 turn_delay = 0.5
1100 [game, graphics] = [None, None]
1101
1102
1103 # The main function! It does the main stuff!
1104 def main(argv):
1105
1106         # Apparently python will silently treat things as local unless you do this
1107         # But (here's the fun part), only if you actually modify the variable.
1108         # For example, all those 'if graphics_enabled' conditions work in functions that never say it is global
1109         # Anyone who says "You should never use a global variable" can die in a fire
1110         global game
1111         global graphics
1112
1113         # Magical argument parsing goes here
1114         if len(argv) == 1:
1115                 players = [HumanPlayer("saruman", "white"), AgentRandom("sabbath", "black")]
1116         elif len(argv) == 2:
1117                 players = [AgentPlayer(argv[1], "white"), HumanPlayer("shadow", "black"), ]
1118         elif len(argv) == 3:
1119                 players = [AgentPlayer(argv[1], "white"), AgentPlayer(argv[2], "black")]
1120
1121         # Construct the board!
1122         board = Board(style = "quantum")
1123         game = GameThread(board, players) # Construct a GameThread! Make it global! Damn the consequences!
1124         #try:
1125         if True:
1126                 graphics = GraphicsThread(board, grid_sz = [64,64]) # Construct a GraphicsThread! I KNOW WHAT I'M DOING! BEAR WITH ME!
1127                 game.start() # This runs in a new thread
1128         #except NameError:
1129         #       print "Run game in main thread"
1130         #       game.run() # Run game in the main thread (no need for joining)
1131         #       return game.error
1132         #except Exception, e:
1133         #       raise e
1134         #else:
1135         #       print "Normal"
1136                 graphics.run()
1137                 game.join()
1138                 return game.error + graphics.error
1139
1140
1141 # This is how python does a main() function...
1142 if __name__ == "__main__":
1143         sys.exit(main(sys.argv))
1144 # --- main.py --- #
1145 # EOF - created from update.sh on Wed Jan 23 22:01:52 WST 2013

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