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

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