aca46010bf0e77486140330315b76acbfa3bfed1
[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 " + str(piece.colour) + " not " + str(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 # +++ network.py +++ #
659 import socket
660
661 class Network():
662         def __init__(self, colour, address = None):
663                 self.socket = socket.socket()
664
665                 if colour == "white":
666                         self.port = 4563
667                 else:
668                         self.port = 4564
669
670                 self.src = None
671
672                 if address == None:
673                         self.host = 'localhost' #socket.gethostname()
674                         self.socket.bind((self.host, self.port))
675                         self.socket.listen(5)   
676
677                         self.src, self.address = self.socket.accept()
678                 else:
679                         self.host = address
680                         self.socket.connect(('localhost', self.port))
681                         self.src = self.socket
682
683         def getline(self):
684                 s = self.src.recv(1)
685                 while s[len(s)-1] != '\n':
686                         s += self.src.recv(1)
687                 return s
688                 
689
690                 
691
692 class NetworkSender(Player,Network):
693         def __init__(self, base_player, board, address = None):
694                 self.base_player = base_player
695                 Player.__init__(self, base_player.name, base_player.colour)
696                 Network.__init__(self, base_player.colour, address)
697
698                 self.board = board
699
700         def select(self):
701                 [x,y] = self.base_player.select()
702                 choice = self.board.grid[x][y]
703                 s = str(x) + " " + str(y)
704                 print str(self) + ".select sends " + s
705                 self.src.send(s + "\n")
706                 return [x,y]
707
708         def get_move(self):
709                 [x,y] = self.base_player.get_move()
710                 s = str(x) + " " + str(y)
711                 print str(self) + ".get_move sends " + s
712                 self.src.send(s + "\n")
713                 return [x,y]
714
715         def update(self, s):
716                 self.base_player.update(s)
717                 s = s.split(" ")
718                 [x,y] = map(int, s[0:2])
719                 selected = self.board.grid[x][y]
720                 if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
721                         s = " ".join(s[0:3])
722                         for i in range(2):
723                                 if selected.types_revealed[i] == True:
724                                         s += " " + str(selected.types[i])
725                                 else:
726                                         s += " unknown"
727                         print str(self) + ".update sends " + s
728                         self.src.send(s + "\n")
729                                 
730
731         def quit(self, final_result):
732                 self.base_player.quit(final_result)
733                 self.src.close()
734
735 class NetworkReceiver(Player,Network):
736         def __init__(self, colour, board, address=None):
737                 
738                 Player.__init__(self, address, colour)
739
740                 Network.__init__(self, colour, address)
741
742                 self.board = board
743                         
744
745         def select(self):
746                 s = self.getline().strip(" \r\n")
747                 return map(int,s.split(" "))
748         def get_move(self):
749                 s = self.getline().strip(" \r\n")
750                 print str(self) + ".get_move gets " + s
751                 return map(int, s.split(" "))
752
753         def update(self, result):
754                 
755                 result = result.split(" ")
756                 [x,y] = map(int, result[0:2])
757                 selected = self.board.grid[x][y]
758                 if selected != None and selected.colour == self.colour and len(result) > 2 and not "->" in result:
759                         s = self.getline().strip(" \r\n")
760                         print str(self) + ".update - receives " + str(s)
761                         s = s.split(" ")
762                         selected.choice = int(s[2])
763                         for i in range(2):
764                                 selected.types[i] = str(s[3+i])
765                                 if s[3+i] == "unknown":
766                                         selected.types_revealed[i] = False
767                                 else:
768                                         selected.types_revealed[i] = True
769                         selected.current_type = selected.types[selected.choice] 
770                 else:
771                         print str(self) + ".update - ignore result " + str(result)                      
772                 
773
774         def quit(self, final_result):
775                 self.src.close()
776         
777 # --- network.py --- #
778 # +++ thread_util.py +++ #
779 import threading
780
781 # A thread that can be stopped!
782 # Except it can only be stopped if it checks self.stopped() periodically
783 # So it can sort of be stopped
784 class StoppableThread(threading.Thread):
785         def __init__(self):
786                 threading.Thread.__init__(self)
787                 self._stop = threading.Event()
788
789         def stop(self):
790                 self._stop.set()
791
792         def stopped(self):
793                 return self._stop.isSet()
794 # --- thread_util.py --- #
795 # +++ game.py +++ #
796
797 # A thread that runs the game
798 class GameThread(StoppableThread):
799         def __init__(self, board, players):
800                 StoppableThread.__init__(self)
801                 self.board = board
802                 self.players = players
803                 self.state = {"turn" : None} # The game state
804                 self.error = 0 # Whether the thread exits with an error
805                 self.lock = threading.RLock() #lock for access of self.state
806                 self.cond = threading.Condition() # conditional for some reason, I forgot
807                 self.final_result = ""
808
809         # Run the game (run in new thread with start(), run in current thread with run())
810         def run(self):
811                 result = ""
812                 while not self.stopped():
813                         
814                         for p in self.players:
815                                 with self.lock:
816                                         if isinstance(p, NetworkSender):
817                                                 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
818                                         else:
819                                                 self.state["turn"] = p
820                                 #try:
821                                 if True:
822                                         [x,y] = p.select() # Player selects a square
823                                         if self.stopped():
824                                                 break
825
826                                         
827                                                 
828
829                                         result = self.board.select(x, y, colour = p.colour)                             
830                                         for p2 in self.players:
831                                                 p2.update(result) # Inform players of what happened
832
833
834
835                                         target = self.board.grid[x][y]
836                                         if isinstance(graphics, GraphicsThread):
837                                                 with graphics.lock:
838                                                         graphics.state["moves"] = self.board.possible_moves(target)
839                                                         graphics.state["select"] = target
840
841                                         time.sleep(turn_delay)
842
843
844                                         if len(self.board.possible_moves(target)) == 0:
845                                                 #print "Piece cannot move"
846                                                 target.deselect()
847                                                 if isinstance(graphics, GraphicsThread):
848                                                         with graphics.lock:
849                                                                 graphics.state["moves"] = None
850                                                                 graphics.state["select"] = None
851                                                                 graphics.state["dest"] = None
852                                                 continue
853
854                                         try:
855                                                 [x2,y2] = p.get_move() # Player selects a destination
856                                         except:
857                                                 self.stop()
858
859                                         if self.stopped():
860                                                 break
861
862                                         result = self.board.update_move(x, y, x2, y2)
863                                         for p2 in self.players:
864                                                 p2.update(str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)) # Inform players of what happened
865
866                                         if isinstance(graphics, GraphicsThread):
867                                                 with graphics.lock:
868                                                         graphics.state["moves"] = [[x2,y2]]
869
870                                         time.sleep(turn_delay)
871
872                                         if isinstance(graphics, GraphicsThread):
873                                                 with graphics.lock:
874                                                         graphics.state["select"] = None
875                                                         graphics.state["dest"] = None
876                                                         graphics.state["moves"] = None
877
878                         # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
879                                 #except Exception,e:
880                                         #result = "ILLEGAL " + e.message
881                                         #sys.stderr.write(result + "\n")
882                                         
883                                         #self.stop()
884                                         #with self.lock:
885                                         #       self.final_result = self.state["turn"].colour + " " + "ILLEGAL"
886
887                                 if self.board.king["black"] == None:
888                                         if self.board.king["white"] == None:
889                                                 with self.lock:
890                                                         self.final_result = "DRAW"
891                                         else:
892                                                 with self.lock:
893                                                         self.final_result = "white"
894                                         self.stop()
895                                 elif self.board.king["white"] == None:
896                                         with self.lock:
897                                                 self.final_result = "black"
898                                         self.stop()
899                                                 
900
901                                 if self.stopped():
902                                         break
903
904
905                 for p2 in self.players:
906                         p2.quit(self.final_result)
907
908                 graphics.stop()
909
910         
911
912
913 def opponent(colour):
914         if colour == "white":
915                 return "black"
916         else:
917                 return "white"
918 # --- game.py --- #
919 # +++ graphics.py +++ #
920 import pygame
921
922 # Dictionary that stores the unicode character representations of the different pieces
923 # Chess was clearly the reason why unicode was invented
924 # For some reason none of the pygame chess implementations I found used them!
925 piece_char = {"white" : {"king" : u'\u2654',
926                          "queen" : u'\u2655',
927                          "rook" : u'\u2656',
928                          "bishop" : u'\u2657',
929                          "knight" : u'\u2658',
930                          "pawn" : u'\u2659',
931                          "unknown" : '?'},
932                 "black" : {"king" : u'\u265A',
933                          "queen" : u'\u265B',
934                          "rook" : u'\u265C',
935                          "bishop" : u'\u265D',
936                          "knight" : u'\u265E',
937                          "pawn" : u'\u265F',
938                          "unknown" : '?'}}
939
940 images = {"white" : {}, "black" : {}}
941 small_images = {"white" : {}, "black" : {}}
942
943 # A thread to make things pretty
944 class GraphicsThread(StoppableThread):
945         def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
946                 StoppableThread.__init__(self)
947                 
948                 self.board = board
949                 pygame.init()
950                 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
951                 pygame.display.set_caption(title)
952                 self.grid_sz = grid_sz[:]
953                 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
954                 self.error = 0
955                 self.lock = threading.RLock()
956                 self.cond = threading.Condition()
957
958                 # Get the font sizes
959                 l_size = 5*(self.grid_sz[0] / 8)
960                 s_size = 3*(self.grid_sz[0] / 8)
961                 for p in piece_types.keys():
962                         c = "black"
963                         images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", l_size).render(piece_char[c][p], True,(0,0,0))})
964                         small_images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", s_size).render(piece_char[c][p],True,(0,0,0))})
965                         c = "white"
966
967                         images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", l_size+1).render(piece_char["black"][p], True,(255,255,255))})
968                         images[c][p].blit(pygame.font.Font("data/DejaVuSans.ttf", l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
969                         small_images[c].update({p : pygame.font.Font("data/DejaVuSans.ttf", s_size+1).render(piece_char["black"][p],True,(255,255,255))})
970                         small_images[c][p].blit(pygame.font.Font("data/DejaVuSans.ttf", s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
971
972                 
973         
974
975
976         # On the run from the world
977         def run(self):
978                 
979                 while not self.stopped():
980                         
981                         self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
982
983                         self.overlay()
984
985                         self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board                
986
987                         pygame.display.flip()
988
989                         for event in pygame.event.get():
990                                 if event.type == pygame.QUIT:
991                                         if isinstance(game, GameThread):
992                                                 with game.lock:
993                                                         game.final_result = "terminated"
994                                                 game.stop()
995                                         self.stop()
996                                         break
997                                 elif event.type == pygame.MOUSEBUTTONDOWN:
998                                         self.mouse_down(event)
999                                 elif event.type == pygame.MOUSEBUTTONUP:
1000                                         self.mouse_up(event)
1001                                         
1002
1003                                 
1004                                                                 
1005                                                 
1006                                                 
1007                 self.message("Game ends, result \""+str(game.final_result) + "\"")
1008                 time.sleep(1)
1009
1010                 # Wake up anyone who is sleeping
1011                 self.cond.acquire()
1012                 self.cond.notify()
1013                 self.cond.release()
1014
1015                 pygame.quit() # Time to say goodbye
1016
1017         # Mouse release event handler
1018         def mouse_up(self, event):
1019                 if event.button == 3:
1020                         with self.lock:
1021                                 self.state["overlay"] = None
1022                 elif event.button == 2:
1023                         with self.lock:
1024                                 self.state["coverage"] = None   
1025
1026         # Mouse click event handler
1027         def mouse_down(self, event):
1028                 if event.button == 1:
1029                         m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
1030                         if isinstance(game, GameThread):
1031                                 with game.lock:
1032                                         p = game.state["turn"]
1033                         else:
1034                                         p = None
1035                                         
1036                                         
1037                         if isinstance(p, HumanPlayer):
1038                                 with self.lock:
1039                                         s = self.board.grid[m[0]][m[1]]
1040                                         select = self.state["select"]
1041                                 if select == None:
1042                                         if s != None and s.colour != p.colour:
1043                                                 self.message("Wrong colour") # Look at all this user friendliness!
1044                                                 time.sleep(1)
1045                                                 return
1046                                         # Notify human player of move
1047                                         self.cond.acquire()
1048                                         with self.lock:
1049                                                 self.state["select"] = s
1050                                                 self.state["dest"] = None
1051                                         self.cond.notify()
1052                                         self.cond.release()
1053                                         return
1054
1055                                 if select == None:
1056                                         return
1057                                                 
1058                                         
1059                                 if self.state["moves"] == None:
1060                                         return
1061
1062                                 if not m in self.state["moves"]:
1063                                         self.message("Illegal Move") # I still think last year's mouse interface was adequate
1064                                         time.sleep(2)
1065                                         return
1066                                                 
1067                                 with self.lock:
1068                                         if self.state["dest"] == None:
1069                                                 self.cond.acquire()
1070                                                 self.state["dest"] = m
1071                                                 self.state["select"] = None
1072                                                 self.state["moves"] = None
1073                                                 self.cond.notify()
1074                                                 self.cond.release()
1075                 elif event.button == 3:
1076                         m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1077                         if isinstance(game, GameThread):
1078                                 with game.lock:
1079                                         p = game.state["turn"]
1080                         else:
1081                                 p = None
1082                                         
1083                                         
1084                         if isinstance(p, HumanPlayer):
1085                                 with self.lock:
1086                                         self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
1087
1088                 elif event.button == 2:
1089                         m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1090                         if isinstance(game, GameThread):
1091                                 with game.lock:
1092                                         p = game.state["turn"]
1093                         else:
1094                                 p = None
1095                         
1096                         
1097                         if isinstance(p, HumanPlayer):
1098                                 with self.lock:
1099                                         self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
1100                                 
1101         # Draw the overlay
1102         def overlay(self):
1103
1104                 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
1105                 # Draw square over the selected piece
1106                 with self.lock:
1107                         select = self.state["select"]
1108                 if select != None:
1109                         mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
1110                         square_img.fill(pygame.Color(0,255,0,64))
1111                         self.window.blit(square_img, mp)
1112                 # If a piece is selected, draw all reachable squares
1113                 # (This quality user interface has been patented)
1114                 with self.lock:
1115                         m = self.state["moves"]
1116                 if m != None:
1117                         square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
1118                         for move in m:
1119                                 mp = [self.grid_sz[i] * move[i] for i in range(2)]
1120                                 self.window.blit(square_img, mp)
1121                 # If a piece is overlayed, show all squares that it has a probability to reach
1122                 with self.lock:
1123                         m = self.state["overlay"]
1124                 if m != None:
1125                         for x in range(w):
1126                                 for y in range(h):
1127                                         if m[x][y] > 0.0:
1128                                                 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
1129                                                 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
1130                                                 self.window.blit(square_img, mp)
1131                                                 font = pygame.font.Font(None, 14)
1132                                                 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
1133                                                 self.window.blit(text, mp)
1134                                 
1135                 # If a square is selected, highlight all pieces that have a probability to reach it
1136                 with self.lock:                         
1137                         m = self.state["coverage"]
1138                 if m != None:
1139                         for p in m:
1140                                 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
1141                                 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
1142                                 self.window.blit(square_img, mp)
1143                                 font = pygame.font.Font(None, 14)
1144                                 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
1145                                 self.window.blit(text, mp)
1146                         # Draw a square where the mouse is
1147                 # This also serves to indicate who's turn it is
1148                 
1149                 if isinstance(game, GameThread):
1150                         with game.lock:
1151                                 turn = game.state["turn"]
1152                 else:
1153                         turn = None
1154
1155                 if isinstance(turn, HumanPlayer):
1156                         mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
1157                         square_img.fill(pygame.Color(0,0,255,128))
1158                         if turn.colour == "white":
1159                                 c = pygame.Color(255,255,255)
1160                         else:
1161                                 c = pygame.Color(0,0,0)
1162                         pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
1163                         self.window.blit(square_img, mp)
1164
1165         # Message in a bottle
1166         def message(self, string, pos = None, colour = None, font_size = 32):
1167                 font = pygame.font.Font(None, font_size)
1168                 if colour == None:
1169                         colour = pygame.Color(0,0,0)
1170                 
1171                 text = font.render(string, 1, colour)
1172         
1173
1174                 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
1175                 s.fill(pygame.Color(128,128,128))
1176
1177                 tmp = self.window.get_size()
1178
1179                 if pos == None:
1180                         pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
1181                 else:
1182                         pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
1183                 
1184
1185                 rect = (pos[0], pos[1], text.get_width(), text.get_height())
1186         
1187                 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
1188                 self.window.blit(s, pos)
1189                 self.window.blit(text, pos)
1190
1191                 pygame.display.flip()
1192
1193         def getstr(self, prompt = None):
1194                 result = ""
1195                 while True:
1196                         #print "LOOP"
1197                         if prompt != None:
1198                                 self.message(prompt)
1199                                 self.message(result, pos = (0, 1))
1200         
1201                         for event in pygame.event.get():
1202                                 if event.type == pygame.KEYDOWN:
1203                                         if chr(event.key) == '\r':
1204                                                 return result
1205                                         result += str(chr(event.key))
1206 # --- graphics.py --- #
1207 # +++ main.py +++ #
1208 #!/usr/bin/python -u
1209
1210 # Do you know what the -u does? It unbuffers stdin and stdout
1211 # I can't remember why, but last year things broke without that
1212
1213 """
1214         UCC::Progcomp 2013 Quantum Chess game
1215         @author Sam Moore [SZM] "matches"
1216         @copyright The University Computer Club, Incorporated
1217                 (ie: You can copy it for not for profit purposes)
1218 """
1219
1220 # system python modules or whatever they are called
1221 import sys
1222 import os
1223 import time
1224
1225 turn_delay = 0.5
1226 [game, graphics] = [None, None]
1227
1228
1229 # The main function! It does the main stuff!
1230 def main(argv):
1231
1232         # Apparently python will silently treat things as local unless you do this
1233         # But (here's the fun part), only if you actually modify the variable.
1234         # For example, all those 'if graphics_enabled' conditions work in functions that never say it is global
1235         # Anyone who says "You should never use a global variable" can die in a fire
1236         global game
1237         global graphics
1238
1239         # Magical argument parsing goes here
1240 #       if len(argv) == 1:
1241 #               players = [HumanPlayer("saruman", "white"), AgentRandom("sabbath", "black")]
1242 #       elif len(argv) == 2:
1243 #               players = [AgentPlayer(argv[1], "white"), HumanPlayer("shadow", "black"), ]
1244 #       elif len(argv) == 3:
1245 #               players = [AgentPlayer(argv[1], "white"), AgentPlayer(argv[2], "black")]
1246
1247
1248         board = Board(style = "quantum")
1249         # Construct the board!
1250         if len(argv) == 1:
1251                 players = [NetworkSender(HumanPlayer("saruman", "white"), board), NetworkReceiver("black", board, 'localhost')]
1252                 
1253         else:
1254                 players = [NetworkReceiver("white", board, 'localhost'), NetworkSender(HumanPlayer("sabbath", "black"), board)]
1255                 
1256         
1257         
1258
1259         graphics = GraphicsThread(board, grid_sz = [64,64]) # Construct a GraphicsThread! I KNOW WHAT I'M DOING! BEAR WITH ME!
1260         
1261
1262
1263
1264         game = GameThread(board, players) # Construct a GameThread! Make it global! Damn the consequences!
1265         game.start() # This runs in a new thread
1266
1267         graphics.run()
1268         game.join()
1269         return game.error + graphics.error
1270
1271
1272 # This is how python does a main() function...
1273 if __name__ == "__main__":
1274         sys.exit(main(sys.argv))
1275 # --- main.py --- #
1276 # EOF - created from update.sh on Thu Jan 24 03:04:38 WST 2013

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