Self inflicted wounds using cx_freeze
[progcomp2013.git] / qchess / qchess.py
1 #!/usr/bin/python -u
2 import random
3
4 # I know using non-abreviated strings is inefficient, but this is python, who cares?
5 # Oh, yeah, this stores the number of pieces of each type in a normal chess game
6 piece_types = {"pawn" : 8, "bishop" : 2, "knight" : 2, "rook" : 2, "queen" : 1, "king" : 1, "unknown" : 0}
7
8 # Class to represent a quantum chess piece
9 class Piece():
10         def __init__(self, colour, x, y, types):
11                 self.colour = colour # Colour (string) either "white" or "black"
12                 self.x = x # x coordinate (0 - 8), none of this fancy 'a', 'b' shit here
13                 self.y = y # y coordinate (0 - 8)
14                 self.types = types # List of possible types the piece can be (should just be two)
15                 self.current_type = "unknown" # Current type
16                 self.choice = -1 # Index of the current type in self.types (-1 = unknown type)
17                 self.types_revealed = [True, False] # Whether the types are known (by default the first type is always known at game start)
18                 
19
20                 # 
21                 self.last_state = None
22                 self.move_pattern = None
23
24                 
25
26         def init_from_copy(self, c):
27                 self.colour = c.colour
28                 self.x = c.x
29                 self.y = c.y
30                 self.types = c.types[:]
31                 self.current_type = c.current_type
32                 self.choice = c.choice
33                 self.types_revealed = c.types_revealed[:]
34
35                 self.last_state = None
36                 self.move_pattern = None
37
38         
39
40         # Make a string for the piece (used for debug)
41         def __str__(self):
42                 return str(self.current_type) + " " + str(self.types) + " at " + str(self.x) + ","+str(self.y)  
43
44         # Draw the piece in a pygame surface
45         def draw(self, window, grid_sz = [80,80], style="quantum"):
46
47                 # First draw the image corresponding to self.current_type
48                 img = images[self.colour][self.current_type]
49                 rect = img.get_rect()
50                 if style == "classical":
51                         offset = [-rect.width/2, -rect.height/2]
52                 else:
53                         offset = [-rect.width/2,-3*rect.height/4] 
54                 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]))
55                 
56                 
57                 if style == "classical":
58                         return
59
60                 # Draw the two possible types underneath the current_type image
61                 for i in range(len(self.types)):
62                         if self.types_revealed[i] == True:
63                                 img = small_images[self.colour][self.types[i]]
64                         else:
65                                 img = small_images[self.colour]["unknown"] # If the type hasn't been revealed, show a placeholder
66
67                         
68                         rect = img.get_rect()
69                         offset = [-rect.width/2,-rect.height/2] 
70                         
71                         if i == 0:
72                                 target = (self.x * grid_sz[0] + grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])                             
73                         else:
74                                 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])                           
75                                 
76                         window.blit(img, target) # Blit shit
77         
78         # Collapses the wave function!          
79         def select(self):
80                 if self.current_type == "unknown":
81                         self.choice = random.randint(0,1)
82                         self.current_type = self.types[self.choice]
83                         self.types_revealed[self.choice] = True
84                 return self.choice
85
86         # Uncollapses (?) the wave function!
87         def deselect(self):
88                 #print "Deselect called"
89                 if (self.x + self.y) % 2 != 0:
90                         if (self.types[0] != self.types[1]) or (self.types_revealed[0] == False or self.types_revealed[1] == False):
91                                 self.current_type = "unknown"
92                                 self.choice = -1
93                         else:
94                                 self.choice = 0 # Both the two types are the same
95
96         # The sad moment when you realise that you do not understand anything about a subject you studied for 4 years...
97 # --- piece.py --- #
98 [w,h] = [8,8] # Width and height of board(s)
99
100 # Class to represent a quantum chess board
101 class Board():
102         # Initialise; if master=True then the secondary piece types are assigned
103         #       Otherwise, they are left as unknown
104         #       So you can use this class in Agent programs, and fill in the types as they are revealed
105         def __init__(self, style="agent"):
106                 self.style = style
107                 self.pieces = {"white" : [], "black" : []}
108                 self.grid = [[None] * w for _ in range(h)] # 2D List (you can get arrays in python, somehow, but they scare me)
109                 self.unrevealed_types = {"white" : piece_types.copy(), "black" : piece_types.copy()}
110                 self.king = {"white" : None, "black" : None} # We need to keep track of the king, because he is important
111                 for c in ["black", "white"]:
112                         del self.unrevealed_types[c]["unknown"]
113
114                 # Add all the pieces with known primary types
115                 for i in range(0, 2):
116                         
117                         s = ["black", "white"][i]
118                         c = self.pieces[s]
119                         y = [0, h-1][i]
120
121                         c.append(Piece(s, 0, y, ["rook"]))
122                         c.append(Piece(s, 1, y, ["knight"]))
123                         c.append(Piece(s, 2, y, ["bishop"]))
124                         k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
125                         k.types_revealed[1] = True
126                         k.current_type = "king"
127                         self.king[s] = k
128                         c.append(k)
129                         c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
130                         c.append(Piece(s, 5, y, ["bishop"]))
131                         c.append(Piece(s, 6, y, ["knight"]))
132                         c.append(Piece(s, 7, y, ["rook"]))
133                         
134                         if y == 0: 
135                                 y += 1 
136                         else: 
137                                 y -= 1
138                         
139                         # Lots of pawn
140                         for x in range(0, w):
141                                 c.append(Piece(s, x, y, ["pawn"]))
142
143                         types_left = {}
144                         types_left.update(piece_types)
145                         del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
146                         del types_left["unknown"] # We certainly don't want these!
147                         for piece in c:
148                                 # Add to grid
149                                 self.grid[piece.x][piece.y] = piece 
150
151                                 if len(piece.types) > 1:
152                                         continue                                
153                                 if style == "agent": # Assign placeholder "unknown" secondary type
154                                         piece.types.append("unknown")
155                                         continue
156
157                                 elif style == "quantum":
158                                         # The master allocates the secondary types
159                                         choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
160                                         types_left[choice] -= 1
161                                         if types_left[choice] <= 0:
162                                                 del types_left[choice]
163                                         piece.types.append(choice)
164                                 elif style == "classical":
165                                         piece.types.append(piece.types[0])
166                                         piece.current_type = piece.types[0]
167                                         piece.types_revealed[1] = True
168                                         piece.choice = 0
169
170         def clone(self):
171                 newboard = Board(master = False)
172                 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
173                 mypieces = self.pieces["white"] + self.pieces["black"]
174
175                 for i in range(len(mypieces)):
176                         newpieces[i].init_from_copy(mypieces[i])
177                         
178
179         def display_grid(self, window = None, grid_sz = [80,80]):
180                 if window == None:
181                         return # I was considering implementing a text only display, then I thought "Fuck that"
182
183                 # The indentation is getting seriously out of hand...
184                 for x in range(0, w):
185                         for y in range(0, h):
186                                 if (x + y) % 2 == 0:
187                                         c = pygame.Color(200,200,200)
188                                 else:
189                                         c = pygame.Color(64,64,64)
190                                 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
191
192         def display_pieces(self, window = None, grid_sz = [80,80]):
193                 if window == None:
194                         return
195                 for p in self.pieces["white"] + self.pieces["black"]:
196                         p.draw(window, grid_sz, self.style)
197
198         # Draw the board in a pygame window
199         def display(self, window = None):
200                 self.display_grid(window)
201                 self.display_pieces(window)
202                 
203
204                 
205
206         def verify(self):
207                 for x in range(w):
208                         for y in range(h):
209                                 if self.grid[x][y] == None:
210                                         continue
211                                 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
212                                         raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
213
214         # Select a piece on the board (colour is the colour of whoever is doing the selecting)
215         def select(self, x,y, colour=None):
216                 if not self.on_board(x, y): # Get on board everyone!
217                         raise Exception("BOUNDS")
218
219                 piece = self.grid[x][y]
220                 if piece == None:
221                         raise Exception("EMPTY")
222
223                 if colour != None and piece.colour != colour:
224                         raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
225
226                 # I'm not quite sure why I made this return a string, but screw logical design
227                 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
228
229
230         # Update the board when a piece has been selected
231         # "type" is apparently reserved, so I'll use "state"
232         def update_select(self, x, y, type_index, state):
233                 piece = self.grid[x][y]
234                 if piece.types[type_index] == "unknown":
235                         if not state in self.unrevealed_types[piece.colour].keys():
236                                 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
237                         self.unrevealed_types[piece.colour][state] -= 1
238                         if self.unrevealed_types[piece.colour][state] <= 0:
239                                 del self.unrevealed_types[piece.colour][state]
240
241                 piece.types[type_index] = state
242                 piece.types_revealed[type_index] = True
243                 piece.current_type = state
244
245                 if len(self.possible_moves(piece)) <= 0:
246                         piece.deselect() # Piece can't move; deselect it
247                 
248         # Update the board when a piece has been moved
249         def update_move(self, x, y, x2, y2):
250                 piece = self.grid[x][y]
251                 self.grid[x][y] = None
252                 taken = self.grid[x2][y2]
253                 if taken != None:
254                         if taken.current_type == "king":
255                                 self.king[taken.colour] = None
256                         self.pieces[taken.colour].remove(taken)
257                 self.grid[x2][y2] = piece
258                 piece.x = x2
259                 piece.y = y2
260
261                 # If the piece is a pawn, and it reaches the final row, it becomes a queen
262                 # I know you are supposed to get a choice
263                 # But that would be effort
264                 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
265                         if self.style == "classical":
266                                 piece.types[0] = "queen"
267                                 piece.types[1] = "queen"
268                         else:
269                                 piece.types[piece.choice] = "queen"
270                         piece.current_type = "queen"
271
272                 piece.deselect() # Uncollapse (?) the wavefunction!
273                 self.verify()   
274
275         # Update the board from a string
276         # Guesses what to do based on the format of the string
277         def update(self, result):
278                 #print "Update called with \"" + str(result) + "\""
279                 # String always starts with 'x y'
280                 try:
281                         s = result.split(" ")
282                         [x,y] = map(int, s[0:2])        
283                 except:
284                         raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
285
286                 piece = self.grid[x][y]
287                 if piece == None:
288                         raise Exception("EMPTY")
289
290                 # If a piece is being moved, the third token is '->'
291                 # We could get away with just using four integers, but that wouldn't look as cool
292                 if "->" in s:
293                         # Last two tokens are the destination
294                         try:
295                                 [x2,y2] = map(int, s[3:])
296                         except:
297                                 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
298
299                         # Move the piece (take opponent if possible)
300                         self.update_move(x, y, x2, y2)
301                         
302                 else:
303                         # Otherwise we will just assume a piece has been selected
304                         try:
305                                 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
306                                 state = s[3] # The last token is a string identifying the type
307                         except:
308                                 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
309
310                         # Select the piece
311                         self.update_select(x, y, type_index, state)
312
313                 return result
314
315         # Gets each piece that could reach the given square and the probability that it could reach that square 
316         # Will include allied pieces that defend the attacker
317         def coverage(self, x, y, colour = None, reject_allied = True):
318                 result = {}
319                 
320                 if colour == None:
321                         pieces = self.pieces["white"] + self.pieces["black"]
322                 else:
323                         pieces = self.pieces[colour]
324
325                 for p in pieces:
326                         prob = self.probability_grid(p, reject_allied)[x][y]
327                         if prob > 0:
328                                 result.update({p : prob})
329                 
330                 self.verify()
331                 return result
332
333
334                 
335
336
337         # Associates each square with a probability that the piece could move into it
338         # Look, I'm doing all the hard work for you here...
339         def probability_grid(self, p, reject_allied = True):
340                 
341                 result = [[0.0] * w for _ in range(h)]
342                 if not isinstance(p, Piece):
343                         return result
344
345                 if p.current_type != "unknown":
346                         #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
347                         for point in self.possible_moves(p, reject_allied):
348                                 result[point[0]][point[1]] = 1.0
349                         return result
350                 
351                 
352                 for i in range(len(p.types)):
353                         t = p.types[i]
354                         prob = 0.5
355                         if t == "unknown" or p.types_revealed[i] == False:
356                                 total_types = 0
357                                 for t2 in self.unrevealed_types[p.colour].keys():
358                                         total_types += self.unrevealed_types[p.colour][t2]
359                                 
360                                 for t2 in self.unrevealed_types[p.colour].keys():
361                                         prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
362                                         p.current_type = t2
363                                         for point in self.possible_moves(p, reject_allied):
364                                                 result[point[0]][point[1]] += prob2 * prob
365                                 
366                         else:
367                                 p.current_type = t
368                                 for point in self.possible_moves(p, reject_allied):
369                                         result[point[0]][point[1]] += prob
370                 
371                 self.verify()
372                 p.current_type = "unknown"
373                 return result
374
375         def prob_is_type(self, p, state):
376                 prob = 0.5
377                 result = 0
378                 for i in range(len(p.types)):
379                         t = p.types[i]
380                         if t == state:
381                                 result += prob
382                                 continue        
383                         if t == "unknown" or p.types_revealed[i] == False:
384                                 total_prob = 0
385                                 for t2 in self.unrevealed_types[p.colour].keys():
386                                         total_prob += self.unrevealed_types[p.colour][t2]
387                                 for t2 in self.unrevealed_types[p.colour].keys():
388                                         if t2 == state:
389                                                 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
390                                 
391
392
393         # Get all squares that the piece could move into
394         # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
395         # reject_allied indicates whether squares occupied by allied pieces will be removed
396         # (set to false to check for defense)
397         def possible_moves(self, p, reject_allied = True):
398                 result = []
399                 if p == None:
400                         return result
401
402                 
403                 if p.current_type == "unknown":
404                         raise Exception("SANITY: Piece state unknown")
405                         # The below commented out code causes things to break badly
406                         #for t in p.types:
407                         #       if t == "unknown":
408                         #               continue
409                         #       p.current_type = t
410                         #       result += self.possible_moves(p)                                                
411                         #p.current_type = "unknown"
412                         #return result
413
414                 if p.current_type == "king":
415                         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]]
416                 elif p.current_type == "queen":
417                         for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
418                                 result += self.scan(p.x, p.y, d[0], d[1])
419                 elif p.current_type == "bishop":
420                         for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
421                                 result += self.scan(p.x, p.y, d[0], d[1])
422                 elif p.current_type == "rook":
423                         for d in [[-1,0],[1,0],[0,-1],[0,1]]:
424                                 result += self.scan(p.x, p.y, d[0], d[1])
425                 elif p.current_type == "knight":
426                         # I would use two lines, but I'm not sure how python likes that
427                         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]]
428                 elif p.current_type == "pawn":
429                         if p.colour == "white":
430                                 
431                                 # Pawn can't move forward into occupied square
432                                 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
433                                         result = [[p.x,p.y-1]]
434                                 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
435                                         if not self.on_board(f[0], f[1]):
436                                                 continue
437                                         if self.grid[f[0]][f[1]] != None:  # Pawn can take diagonally
438                                                 result.append(f)
439                                 if p.y == h-2:
440                                         # Slightly embarrassing if the pawn jumps over someone on its first move...
441                                         if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
442                                                 result.append([p.x, p.y-2])
443                         else:
444                                 # Vice versa for the black pawn
445                                 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
446                                         result = [[p.x,p.y+1]]
447
448                                 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
449                                         if not self.on_board(f[0], f[1]):
450                                                 continue
451                                         if self.grid[f[0]][f[1]] != None:
452                                                 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
453                                                 result.append(f)
454                                 if p.y == 1:
455                                         if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
456                                                 result.append([p.x, p.y+2])
457
458                         #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
459
460                 # Remove illegal moves
461                 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
462                 for point in result[:]: 
463
464                         if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
465                                 result.remove(point) # Remove locations outside the board
466                                 continue
467                         g = self.grid[point[0]][point[1]]
468                         
469                         if g != None and (g.colour == p.colour and reject_allied == True):
470                                 result.remove(point) # Remove allied pieces
471                 
472                 self.verify()
473                 return result
474
475
476         # Scans in a direction until it hits a piece, returns all squares in the line
477         # (includes the final square (which contains a piece), but not the original square)
478         def scan(self, x, y, vx, vy):
479                 p = []
480                         
481                 xx = x
482                 yy = y
483                 while True:
484                         xx += vx
485                         yy += vy
486                         if not self.on_board(xx, yy):
487                                 break
488                         if not [xx,yy] in p:
489                                 p.append([xx, yy])
490                         g = self.grid[xx][yy]
491                         if g != None:
492                                 return p        
493                                         
494                 return p
495
496
497
498         # I typed the full statement about 30 times before writing this function...
499         def on_board(self, x, y):
500                 return (x >= 0 and x < w) and (y >= 0 and y < h)
501 # --- board.py --- #
502 import subprocess
503 import select
504 import platform
505
506
507 agent_timeout = -1.0 # Timeout in seconds for AI players to make moves
508                         # WARNING: Won't work for windows based operating systems
509
510 if platform.system() == "Windows":
511         agent_timeout = -1 # Hence this
512
513 # A player who can't play
514 class Player():
515         def __init__(self, name, colour):
516                 self.name = name
517                 self.colour = colour
518
519 # Player that runs from another process
520 class AgentPlayer(Player):
521
522
523         def __init__(self, name, colour):
524                 Player.__init__(self, name, colour)
525                 self.p = subprocess.Popen(name, stdin=subprocess.PIPE, stdout=subprocess.PIPE,stderr=subprocess.PIPE)
526                 
527                 self.send_message(colour)
528
529         def send_message(self, s):
530                 if agent_timeout > 0.0:
531                         ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
532                 else:
533                         ready = [self.p.stdin]
534                 if self.p.stdin in ready:
535                         #print "Writing to p.stdin"
536                         try:
537                                 self.p.stdin.write(s + "\n")
538                         except:
539                                 raise Exception("UNRESPONSIVE")
540                 else:
541                         raise Exception("UNRESPONSIVE")
542
543         def get_response(self):
544                 if agent_timeout > 0.0:
545                         ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
546                 else:
547                         ready = [self.p.stdout]
548                 if self.p.stdout in ready:
549                         #print "Reading from p.stdout"
550                         try:
551                                 return self.p.stdout.readline().strip("\r\n")
552                         except: # Exception, e:
553                                 raise Exception("UNRESPONSIVE")
554                 else:
555                         raise Exception("UNRESPONSIVE")
556
557         def select(self):
558
559                 self.send_message("SELECTION?")
560                 line = self.get_response()
561                 
562                 try:
563                         result = map(int, line.split(" "))
564                 except:
565                         raise Exception("GIBBERISH \"" + str(line) + "\"")
566                 return result
567
568         def update(self, result):
569                 #print "Update " + str(result) + " called for AgentPlayer"
570                 self.send_message(result)
571
572
573         def get_move(self):
574                 
575                 self.send_message("MOVE?")
576                 line = self.get_response()
577                 
578                 try:
579                         result = map(int, line.split(" "))
580                 except:
581                         raise Exception("GIBBERISH \"" + str(line) + "\"")
582                 return result
583
584         def quit(self, final_result):
585                 try:
586                         self.send_message("QUIT " + final_result)
587                 except:
588                         self.p.kill()
589
590 # So you want to be a player here?
591 class HumanPlayer(Player):
592         def __init__(self, name, colour):
593                 Player.__init__(self, name, colour)
594                 
595         # Select your preferred account
596         def select(self):
597                 if isinstance(graphics, GraphicsThread):
598                         # Basically, we let the graphics thread do some shit and then return that information to the game thread
599                         graphics.cond.acquire()
600                         # We wait for the graphics thread to select a piece
601                         while graphics.stopped() == False and graphics.state["select"] == None:
602                                 graphics.cond.wait() # The difference between humans and machines is that humans sleep
603                         select = graphics.state["select"]
604                         
605                         
606                         graphics.cond.release()
607                         if graphics.stopped():
608                                 return [-1,-1]
609                         return [select.x, select.y]
610                 else:
611                         # Since I don't display the board in this case, I'm not sure why I filled it in...
612                         while True:
613                                 sys.stdout.write("SELECTION?\n")
614                                 try:
615                                         p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
616                                 except:
617                                         sys.stderr.write("ILLEGAL GIBBERISH\n")
618                                         continue
619         # It's your move captain
620         def get_move(self):
621                 if isinstance(graphics, GraphicsThread):
622                         graphics.cond.acquire()
623                         while graphics.stopped() == False and graphics.state["dest"] == None:
624                                 graphics.cond.wait()
625                         graphics.cond.release()
626                         
627                         return graphics.state["dest"]
628                 else:
629
630                         while True:
631                                 sys.stdout.write("MOVE?\n")
632                                 try:
633                                         p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
634                                 except:
635                                         sys.stderr.write("ILLEGAL GIBBERISH\n")
636                                         continue
637
638         # Are you sure you want to quit?
639         def quit(self, final_result):
640                 if graphics == None:            
641                         sys.stdout.write("QUIT " + final_result + "\n")
642
643         # Completely useless function
644         def update(self, result):
645                 if isinstance(graphics, GraphicsThread):
646                         pass
647                 else:
648                         sys.stdout.write(result + "\n") 
649
650
651 # Player that makes random moves
652 class AgentRandom(Player):
653         def __init__(self, name, colour):
654                 Player.__init__(self, name, colour)
655                 self.choice = None
656
657                 self.board = Board(style = "agent")
658
659         def select(self):
660                 while True:
661                         self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
662                         all_moves = []
663                         # Check that the piece has some possibility to move
664                         tmp = self.choice.current_type
665                         if tmp == "unknown": # For unknown pieces, try both types
666                                 for t in self.choice.types:
667                                         if t == "unknown":
668                                                 continue
669                                         self.choice.current_type = t
670                                         all_moves += self.board.possible_moves(self.choice)
671                         else:
672                                 all_moves = self.board.possible_moves(self.choice)
673                         self.choice.current_type = tmp
674                         if len(all_moves) > 0:
675                                 break
676                 return [self.choice.x, self.choice.y]
677
678         def get_move(self):
679                 moves = self.board.possible_moves(self.choice)
680                 move = moves[random.randint(0, len(moves)-1)]
681                 return move
682
683         def update(self, result):
684                 #sys.stderr.write(sys.argv[0] + " : Update board for AgentRandom\n")
685                 self.board.update(result)
686                 self.board.verify()
687
688         def quit(self, final_result):
689                 pass
690
691
692 # --- player.py --- #
693 import multiprocessing
694
695 # Hacky alternative to using select for timing out players
696
697 # WARNING: Do not wrap around HumanPlayer or things breakify
698
699 class Sleeper(multiprocessing.Process):
700         def __init__(self, timeout):
701                 multiprocessing.Process.__init__(self)
702                 self.timeout = timeout
703
704         def run(self):
705                 time.sleep(self.timeout)
706
707
708 class Worker(multiprocessing.Process):
709         def __init__(self, function, args, q):
710                 multiprocessing.Process.__init__(self)
711                 self.function = function
712                 self.args = args
713                 self.q = q
714
715         def run(self):
716                 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args) 
717                 self.q.put(self.function(*self.args))
718                 
719                 
720
721 def TimeoutFunction(function, args, timeout):
722         q = multiprocessing.Queue()
723         w = Worker(function, args, q)
724         s = Sleeper(timeout)
725         w.start()
726         s.start()
727         while True: # Busy loop of crappyness
728                 if not w.is_alive():
729                         s.terminate()
730                         result = q.get()
731                         w.join()
732                         #print "TimeoutFunction gets " + str(result)
733                         return result
734                 elif not s.is_alive():
735                         w.terminate()
736                         s.join()
737                         raise Exception("UNRESPONSIVE")
738
739         
740                 
741
742 # A player that wraps another player and times out its moves
743 # Uses threads
744 # A (crappy) alternative to the use of select()
745 class TimeoutPlayer(Player):
746         def __init__(self, base_player, timeout):
747                 Player.__init__(self, base_player.name, base_player.colour)
748                 self.base_player = base_player
749                 self.timeout = timeout
750                 
751         def select(self):
752                 return TimeoutFunction(self.base_player.select, [], self.timeout)
753                 
754         
755         def get_move(self):
756                 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
757
758         def update(self, result):
759                 return TimeoutFunction(self.base_player.update, [result], self.timeout)
760
761         def quit(self, final_result):
762                 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
763 # --- timeout_player.py --- #
764 import socket
765 import select
766
767 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
768 network_timeout_delay = 1.0 # Maximum time between two characters being received
769
770 class Network():
771         def __init__(self, colour, address = None):
772                 self.socket = socket.socket()
773                 #self.socket.setblocking(0)
774
775                 if colour == "white":
776                         self.port = 4562
777                 else:
778                         self.port = 4563
779
780                 self.src = None
781
782         #       print str(self) + " listens on port " + str(self.port)
783
784                 if address == None:
785                         self.host = socket.gethostname()
786                         self.socket.bind((self.host, self.port))
787                         self.socket.listen(5)   
788
789                         self.src, self.address = self.socket.accept()
790                         self.src.send("ok\n")
791                         if self.get_response() == "QUIT":
792                                 self.src.close()
793                 else:
794                         self.host = address
795                         self.socket.connect((address, self.port))
796                         self.src = self.socket
797                         self.src.send("ok\n")
798                         if self.get_response() == "QUIT":
799                                 self.src.close()
800
801         def get_response(self):
802                 # Timeout the start of the message (first character)
803                 if network_timeout_start > 0.0:
804                         ready = select.select([self.src], [], [], network_timeout_start)[0]
805                 else:
806                         ready = [self.src]
807                 if self.src in ready:
808                         s = self.src.recv(1)
809                 else:
810                         raise Exception("UNRESPONSIVE")
811
812
813                 while s[len(s)-1] != '\n':
814                         # Timeout on each character in the message
815                         if network_timeout_delay > 0.0:
816                                 ready = select.select([self.src], [], [], network_timeout_delay)[0]
817                         else:
818                                 ready = [self.src]
819                         if self.src in ready:
820                                 s += self.src.recv(1) 
821                         else:
822                                 raise Exception("UNRESPONSIVE")
823
824                 return s.strip(" \r\n")
825
826         def send_message(self,s):
827                 if network_timeout_start > 0.0:
828                         ready = select.select([], [self.src], [], network_timeout_start)[1]
829                 else:
830                         ready = [self.src]
831
832                 if self.src in ready:
833                         self.src.send(s + "\n")
834                 else:
835                         raise Exception("UNRESPONSIVE")
836
837         def check_quit(self, s):
838                 s = s.split(" ")
839                 if s[0] == "QUIT":
840                         with game.lock:
841                                 game.final_result = " ".join(s[1:]) + " " + str(opponent(self.colour))
842                         game.stop()
843                         return True
844
845                 
846
847 class NetworkSender(Player,Network):
848         def __init__(self, base_player, address = None):
849                 self.base_player = base_player
850                 Player.__init__(self, base_player.name, base_player.colour)
851
852                 self.address = address
853
854         def connect(self):
855                 Network.__init__(self, self.base_player.colour, self.address)
856
857
858
859         def select(self):
860                 [x,y] = self.base_player.select()
861                 choice = self.board.grid[x][y]
862                 s = str(x) + " " + str(y)
863                 #print str(self) + ".select sends " + s
864                 self.send_message(s)
865                 return [x,y]
866
867         def get_move(self):
868                 [x,y] = self.base_player.get_move()
869                 s = str(x) + " " + str(y)
870                 #print str(self) + ".get_move sends " + s
871                 self.send_message(s)
872                 return [x,y]
873
874         def update(self, s):
875                 self.base_player.update(s)
876                 s = s.split(" ")
877                 [x,y] = map(int, s[0:2])
878                 selected = self.board.grid[x][y]
879                 if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
880                         s = " ".join(s[0:3])
881                         for i in range(2):
882                                 if selected.types_revealed[i] == True:
883                                         s += " " + str(selected.types[i])
884                                 else:
885                                         s += " unknown"
886                         #print str(self) + ".update sends " + s
887                         self.send_message(s)
888                                 
889
890         def quit(self, final_result):
891                 self.base_player.quit(final_result)
892                 #self.src.send("QUIT " + str(final_result) + "\n")
893                 self.src.close()
894
895 class NetworkReceiver(Player,Network):
896         def __init__(self, colour, address=None):
897                 
898                 Player.__init__(self, address, colour)
899
900                 self.address = address
901
902                 self.board = None
903
904         def connect(self):
905                 Network.__init__(self, self.colour, self.address)
906                         
907
908         def select(self):
909                 
910                 s = self.get_response()
911                 #print str(self) + ".select gets " + s
912                 [x,y] = map(int,s.split(" "))
913                 if x == -1 and y == -1:
914                         #print str(self) + ".select quits the game"
915                         with game.lock:
916                                 game.final_state = "network terminated " + self.colour
917                         game.stop()
918                 return [x,y]
919         def get_move(self):
920                 s = self.get_response()
921                 #print str(self) + ".get_move gets " + s
922                 [x,y] = map(int,s.split(" "))
923                 if x == -1 and y == -1:
924                         #print str(self) + ".get_move quits the game"
925                         with game.lock:
926                                 game.final_state = "network terminated " + self.colour
927                         game.stop()
928                 return [x,y]
929
930         def update(self, result):
931                 
932                 result = result.split(" ")
933                 [x,y] = map(int, result[0:2])
934                 selected = self.board.grid[x][y]
935                 if selected != None and selected.colour == self.colour and len(result) > 2 and not "->" in result:
936                         s = self.get_response()
937                         #print str(self) + ".update - receives " + str(s)
938                         s = s.split(" ")
939                         selected.choice = int(s[2])
940                         for i in range(2):
941                                 selected.types[i] = str(s[3+i])
942                                 if s[3+i] == "unknown":
943                                         selected.types_revealed[i] = False
944                                 else:
945                                         selected.types_revealed[i] = True
946                         selected.current_type = selected.types[selected.choice] 
947                 else:
948                         pass
949                         #print str(self) + ".update - ignore result " + str(result)                     
950                 
951
952         def quit(self, final_result):
953                 self.src.close()
954         
955 # --- network.py --- #
956 import threading
957
958 # A thread that can be stopped!
959 # Except it can only be stopped if it checks self.stopped() periodically
960 # So it can sort of be stopped
961 class StoppableThread(threading.Thread):
962         def __init__(self):
963                 threading.Thread.__init__(self)
964                 self._stop = threading.Event()
965
966         def stop(self):
967                 self._stop.set()
968
969         def stopped(self):
970                 return self._stop.isSet()
971 # --- thread_util.py --- #
972
973 # A thread that runs the game
974 class GameThread(StoppableThread):
975         def __init__(self, board, players):
976                 StoppableThread.__init__(self)
977                 self.board = board
978                 self.players = players
979                 self.state = {"turn" : None} # The game state
980                 self.error = 0 # Whether the thread exits with an error
981                 self.lock = threading.RLock() #lock for access of self.state
982                 self.cond = threading.Condition() # conditional for some reason, I forgot
983                 self.final_result = ""
984
985         # Run the game (run in new thread with start(), run in current thread with run())
986         def run(self):
987                 result = ""
988                 while not self.stopped():
989                         
990                         for p in self.players:
991                                 with self.lock:
992                                         if isinstance(p, NetworkSender):
993                                                 self.state["turn"] = p.base_player # "turn" contains the player who's turn it is
994                                         else:
995                                                 self.state["turn"] = p
996                                 #try:
997                                 if True:
998                                         [x,y] = p.select() # Player selects a square
999                                         if self.stopped():
1000                                                 break
1001
1002                                         
1003                                                 
1004
1005                                         result = self.board.select(x, y, colour = p.colour)                             
1006                                         for p2 in self.players:
1007                                                 p2.update(result) # Inform players of what happened
1008
1009
1010
1011                                         target = self.board.grid[x][y]
1012                                         if isinstance(graphics, GraphicsThread):
1013                                                 with graphics.lock:
1014                                                         graphics.state["moves"] = self.board.possible_moves(target)
1015                                                         graphics.state["select"] = target
1016
1017                                         time.sleep(turn_delay)
1018
1019
1020                                         if len(self.board.possible_moves(target)) == 0:
1021                                                 #print "Piece cannot move"
1022                                                 target.deselect()
1023                                                 if isinstance(graphics, GraphicsThread):
1024                                                         with graphics.lock:
1025                                                                 graphics.state["moves"] = None
1026                                                                 graphics.state["select"] = None
1027                                                                 graphics.state["dest"] = None
1028                                                 continue
1029
1030                                         try:
1031                                                 [x2,y2] = p.get_move() # Player selects a destination
1032                                         except:
1033                                                 self.stop()
1034
1035                                         if self.stopped():
1036                                                 break
1037
1038                                         result = self.board.update_move(x, y, x2, y2)
1039                                         for p2 in self.players:
1040                                                 p2.update(str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)) # Inform players of what happened
1041
1042                                         if isinstance(graphics, GraphicsThread):
1043                                                 with graphics.lock:
1044                                                         graphics.state["moves"] = [[x2,y2]]
1045
1046                                         time.sleep(turn_delay)
1047
1048                                         if isinstance(graphics, GraphicsThread):
1049                                                 with graphics.lock:
1050                                                         graphics.state["select"] = None
1051                                                         graphics.state["dest"] = None
1052                                                         graphics.state["moves"] = None
1053
1054                         # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
1055                         #       except Exception,e:
1056                         #               result = e.message
1057                         #               #sys.stderr.write(result + "\n")
1058                         #               
1059                         #               self.stop()
1060                         #               with self.lock:
1061                         #                       self.final_result = self.state["turn"].colour + " " + e.message
1062
1063                                 if self.board.king["black"] == None:
1064                                         if self.board.king["white"] == None:
1065                                                 with self.lock:
1066                                                         self.final_result = self.state["turn"].colour + " DRAW"
1067                                         else:
1068                                                 with self.lock:
1069                                                         self.final_result = "white"
1070                                         self.stop()
1071                                 elif self.board.king["white"] == None:
1072                                         with self.lock:
1073                                                 self.final_result = "black"
1074                                         self.stop()
1075                                                 
1076
1077                                 if self.stopped():
1078                                         break
1079
1080
1081                 for p2 in self.players:
1082                         p2.quit(self.final_result)
1083
1084                 graphics.stop()
1085
1086         
1087
1088
1089 def opponent(colour):
1090         if colour == "white":
1091                 return "black"
1092         else:
1093                 return "white"
1094 # --- game.py --- #
1095 import pygame
1096 import os
1097
1098 # Dictionary that stores the unicode character representations of the different pieces
1099 # Chess was clearly the reason why unicode was invented
1100 # For some reason none of the pygame chess implementations I found used them!
1101 piece_char = {"white" : {"king" : u'\u2654',
1102                          "queen" : u'\u2655',
1103                          "rook" : u'\u2656',
1104                          "bishop" : u'\u2657',
1105                          "knight" : u'\u2658',
1106                          "pawn" : u'\u2659',
1107                          "unknown" : '?'},
1108                 "black" : {"king" : u'\u265A',
1109                          "queen" : u'\u265B',
1110                          "rook" : u'\u265C',
1111                          "bishop" : u'\u265D',
1112                          "knight" : u'\u265E',
1113                          "pawn" : u'\u265F',
1114                          "unknown" : '?'}}
1115
1116 images = {"white" : {}, "black" : {}}
1117 small_images = {"white" : {}, "black" : {}}
1118
1119 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
1120
1121         # Get the font sizes
1122         l_size = 5*(grid_sz[0] / 8)
1123         s_size = 3*(grid_sz[0] / 8)
1124
1125         for c in piece_char.keys():
1126                 
1127                 if c == "black":
1128                         for p in piece_char[c].keys():
1129                                 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
1130                                 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})         
1131                 elif c == "white":
1132                         for p in piece_char[c].keys():
1133                                 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1134                                 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1135                                 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1136                                 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1137         
1138
1139 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
1140         if not os.path.exists(image_dir):
1141                 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
1142         for c in piece_char.keys():
1143                 for p in piece_char[c].keys():
1144                         images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
1145                         small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
1146 # --- images.py --- #
1147 import pygame
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157 # A thread to make things pretty
1158 class GraphicsThread(StoppableThread):
1159         def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1160                 StoppableThread.__init__(self)
1161                 
1162                 self.board = board
1163                 pygame.init()
1164                 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1165                 pygame.display.set_caption(title)
1166
1167                 #print "Initialised properly"
1168                 
1169                 self.grid_sz = grid_sz[:]
1170                 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
1171                 self.error = 0
1172                 self.lock = threading.RLock()
1173                 self.cond = threading.Condition()
1174
1175                 #print "Test font"
1176                 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
1177
1178                 #create_images(grid_sz)
1179                 create_images(grid_sz)
1180
1181                 """
1182                 for c in images.keys():
1183                         for p in images[c].keys():
1184                                 images[c][p] = images[c][p].convert(self.window)
1185                                 small_images[c][p] = small_images[c][p].convert(self.window)
1186                 """
1187
1188                 
1189         
1190
1191
1192         # On the run from the world
1193         def run(self):
1194                 
1195                 while not self.stopped():
1196                         
1197                         #print "Display grid"
1198                         self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
1199
1200                         #print "Display overlay"
1201                         self.overlay()
1202
1203                         #print "Display pieces"
1204                         self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board                
1205
1206                         pygame.display.flip()
1207
1208                         for event in pygame.event.get():
1209                                 if event.type == pygame.QUIT:
1210                                         if isinstance(game, GameThread):
1211                                                 with game.lock:
1212                                                         game.final_result = ""
1213                                                         if game.state["turn"] != None:
1214                                                                 game.final_result = game.state["turn"].colour + " "
1215                                                         game.final_result += "terminated"
1216                                                 game.stop()
1217                                         self.stop()
1218                                         break
1219                                 elif event.type == pygame.MOUSEBUTTONDOWN:
1220                                         self.mouse_down(event)
1221                                 elif event.type == pygame.MOUSEBUTTONUP:
1222                                         self.mouse_up(event)
1223                                         
1224
1225                                 
1226                                                                 
1227                                                 
1228                                                 
1229                 self.message("Game ends, result \""+str(game.final_result) + "\"")
1230                 time.sleep(1)
1231
1232                 # Wake up anyone who is sleeping
1233                 self.cond.acquire()
1234                 self.cond.notify()
1235                 self.cond.release()
1236
1237                 pygame.quit() # Time to say goodbye
1238
1239         # Mouse release event handler
1240         def mouse_up(self, event):
1241                 if event.button == 3:
1242                         with self.lock:
1243                                 self.state["overlay"] = None
1244                 elif event.button == 2:
1245                         with self.lock:
1246                                 self.state["coverage"] = None   
1247
1248         # Mouse click event handler
1249         def mouse_down(self, event):
1250                 if event.button == 1:
1251                         m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
1252                         if isinstance(game, GameThread):
1253                                 with game.lock:
1254                                         p = game.state["turn"]
1255                         else:
1256                                         p = None
1257                                         
1258                                         
1259                         if isinstance(p, HumanPlayer):
1260                                 with self.lock:
1261                                         s = self.board.grid[m[0]][m[1]]
1262                                         select = self.state["select"]
1263                                 if select == None:
1264                                         if s != None and s.colour != p.colour:
1265                                                 self.message("Wrong colour") # Look at all this user friendliness!
1266                                                 time.sleep(1)
1267                                                 return
1268                                         # Notify human player of move
1269                                         self.cond.acquire()
1270                                         with self.lock:
1271                                                 self.state["select"] = s
1272                                                 self.state["dest"] = None
1273                                         self.cond.notify()
1274                                         self.cond.release()
1275                                         return
1276
1277                                 if select == None:
1278                                         return
1279                                                 
1280                                         
1281                                 if self.state["moves"] == None:
1282                                         return
1283
1284                                 if not m in self.state["moves"]:
1285                                         self.message("Illegal Move") # I still think last year's mouse interface was adequate
1286                                         time.sleep(2)
1287                                         return
1288                                                 
1289                                 with self.lock:
1290                                         if self.state["dest"] == None:
1291                                                 self.cond.acquire()
1292                                                 self.state["dest"] = m
1293                                                 self.state["select"] = None
1294                                                 self.state["moves"] = None
1295                                                 self.cond.notify()
1296                                                 self.cond.release()
1297                 elif event.button == 3:
1298                         m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1299                         if isinstance(game, GameThread):
1300                                 with game.lock:
1301                                         p = game.state["turn"]
1302                         else:
1303                                 p = None
1304                                         
1305                                         
1306                         if isinstance(p, HumanPlayer):
1307                                 with self.lock:
1308                                         self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
1309
1310                 elif event.button == 2:
1311                         m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
1312                         if isinstance(game, GameThread):
1313                                 with game.lock:
1314                                         p = game.state["turn"]
1315                         else:
1316                                 p = None
1317                         
1318                         
1319                         if isinstance(p, HumanPlayer):
1320                                 with self.lock:
1321                                         self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
1322                                 
1323         # Draw the overlay
1324         def overlay(self):
1325
1326                 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
1327                 # Draw square over the selected piece
1328                 with self.lock:
1329                         select = self.state["select"]
1330                 if select != None:
1331                         mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
1332                         square_img.fill(pygame.Color(0,255,0,64))
1333                         self.window.blit(square_img, mp)
1334                 # If a piece is selected, draw all reachable squares
1335                 # (This quality user interface has been patented)
1336                 with self.lock:
1337                         m = self.state["moves"]
1338                 if m != None:
1339                         square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
1340                         for move in m:
1341                                 mp = [self.grid_sz[i] * move[i] for i in range(2)]
1342                                 self.window.blit(square_img, mp)
1343                 # If a piece is overlayed, show all squares that it has a probability to reach
1344                 with self.lock:
1345                         m = self.state["overlay"]
1346                 if m != None:
1347                         for x in range(w):
1348                                 for y in range(h):
1349                                         if m[x][y] > 0.0:
1350                                                 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
1351                                                 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
1352                                                 self.window.blit(square_img, mp)
1353                                                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
1354                                                 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
1355                                                 self.window.blit(text, mp)
1356                                 
1357                 # If a square is selected, highlight all pieces that have a probability to reach it
1358                 with self.lock:                         
1359                         m = self.state["coverage"]
1360                 if m != None:
1361                         for p in m:
1362                                 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
1363                                 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
1364                                 self.window.blit(square_img, mp)
1365                                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
1366                                 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
1367                                 self.window.blit(text, mp)
1368                         # Draw a square where the mouse is
1369                 # This also serves to indicate who's turn it is
1370                 
1371                 if isinstance(game, GameThread):
1372                         with game.lock:
1373                                 turn = game.state["turn"]
1374                 else:
1375                         turn = None
1376
1377                 if isinstance(turn, HumanPlayer):
1378                         mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
1379                         square_img.fill(pygame.Color(0,0,255,128))
1380                         if turn.colour == "white":
1381                                 c = pygame.Color(255,255,255)
1382                         else:
1383                                 c = pygame.Color(0,0,0)
1384                         pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
1385                         self.window.blit(square_img, mp)
1386
1387         # Message in a bottle
1388         def message(self, string, pos = None, colour = None, font_size = 20):
1389                 #print "Drawing message..."
1390                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
1391                 if colour == None:
1392                         colour = pygame.Color(0,0,0)
1393                 
1394                 text = font.render(string, 1, colour)
1395         
1396
1397                 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
1398                 s.fill(pygame.Color(128,128,128))
1399
1400                 tmp = self.window.get_size()
1401
1402                 if pos == None:
1403                         pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
1404                 else:
1405                         pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
1406                 
1407
1408                 rect = (pos[0], pos[1], text.get_width(), text.get_height())
1409         
1410                 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
1411                 self.window.blit(s, pos)
1412                 self.window.blit(text, pos)
1413
1414                 pygame.display.flip()
1415
1416         def getstr(self, prompt = None):
1417                 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
1418                 s.blit(self.window, (0,0))
1419                 result = ""
1420
1421                 while True:
1422                         #print "LOOP"
1423                         if prompt != None:
1424                                 self.message(prompt)
1425                                 self.message(result, pos = (0, 1))
1426         
1427                         pygame.event.pump()
1428                         for event in pygame.event.get():
1429                                 if event.type == pygame.QUIT:
1430                                         return None
1431                                 if event.type == pygame.KEYDOWN:
1432                                         if event.key == pygame.K_BACKSPACE:
1433                                                 result = result[0:len(result)-1]
1434                                                 self.window.blit(s, (0,0)) # Revert the display
1435                                                 continue
1436                                 
1437                                                 
1438                                         try:
1439                                                 if event.unicode == '\r':
1440                                                         return result
1441                                         
1442                                                 result += str(event.unicode)
1443                                         except:
1444                                                 continue
1445
1446
1447         # Function to pick a button
1448         def SelectButton(self, choices, prompt = None, font_size=20):
1449
1450                 #print "Select button called!"
1451                 self.board.display_grid(self.window, self.grid_sz)
1452                 if prompt != None:
1453                         self.message(prompt)
1454                 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
1455                 targets = []
1456                 sz = self.window.get_size()
1457
1458                 
1459                 for i in range(len(choices)):
1460                         c = choices[i]
1461                         
1462                         text = font.render(c, 1, pygame.Color(0,0,0))
1463                         p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
1464                         targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
1465
1466                 while True:
1467                         mp =pygame.mouse.get_pos()
1468                         for i in range(len(choices)):
1469                                 c = choices[i]
1470                                 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
1471                                         font_colour = pygame.Color(255,0,0)
1472                                         box_colour = pygame.Color(0,0,255,128)
1473                                 else:
1474                                         font_colour = pygame.Color(0,0,0)
1475                                         box_colour = pygame.Color(128,128,128)
1476                                 
1477                                 text = font.render(c, 1, font_colour)
1478                                 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
1479                                 s.fill(box_colour)
1480                                 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
1481                                 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
1482                                 self.window.blit(s, targets[i][0:2])
1483                                 
1484         
1485                         pygame.display.flip()
1486
1487                         for event in pygame.event.get():
1488                                 if event.type == pygame.QUIT:
1489                                         return None
1490                                 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
1491                                         for i in range(len(targets)):
1492                                                 t = targets[i]
1493                                                 if event.pos[0] > t[0] and event.pos[0] < t[2]:
1494                                                         if event.pos[1] > t[1] and event.pos[1] < t[3]:
1495                                                                 return i
1496                                                 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
1497                 
1498
1499         # Function to pick players in a nice GUI way
1500         def SelectPlayers(self, players = []):
1501
1502
1503                 #print "SelectPlayers called"
1504                 
1505                 missing = ["white", "black"]
1506                 for p in players:
1507                         missing.remove(p.colour)
1508
1509                 for colour in missing:
1510                         
1511                         
1512                         choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
1513                         if choice == 0:
1514                                 players.append(HumanPlayer("human", colour))
1515                         elif choice == 1:
1516                                 if True:
1517                                         import Tkinter
1518                                         from tkFileDialog import askopenfilename
1519                                         root = Tkinter.Tk() # Need a root to make Tkinter behave
1520                                         root.withdraw() # Some sort of magic incantation
1521                                         path = askopenfilename(parent=root, initialdir="../agents",title=
1522 'Choose an agent.')
1523                                         if path == "":
1524                                                 return self.SelectPlayers()
1525                                         players.append(make_player(path, colour))       
1526                                 else:
1527                                         print "Exception was " + str(e.message)
1528                                         p = None
1529                                         while p == None:
1530                                                 self.board.display_grid(self.window, self.grid_sz)
1531                                                 pygame.display.flip()
1532                                                 path = self.getstr(prompt = "Enter path:")
1533                                                 if path == None:
1534                                                         return None
1535
1536                                                 if path == "":
1537                                                         return self.SelectPlayers()
1538
1539                                                 try:
1540                                                         p = make_player(path, colour)
1541                                                 except:
1542                                                         self.board.display_grid(self.window, self.grid_sz)
1543                                                         pygame.display.flip()
1544                                                         self.message("Invalid path!")
1545                                                         time.sleep(1)
1546                                                         p = None
1547                                         players.append(p)
1548                         elif choice == 2:
1549                                 address = ""
1550                                 while address == "":
1551                                         self.board.display_grid(self.window, self.grid_sz)
1552                                         
1553                                         address = self.getstr(prompt = "Address? (leave blank for server)")
1554                                         if address == None:
1555                                                 return None
1556                                         if address == "":
1557                                                 address = None
1558                                                 continue
1559                                         try:
1560                                                 map(int, address.split("."))
1561                                         except:
1562                                                 self.board.display_grid(self.window, self.grid_sz)
1563                                                 self.message("Invalid IPv4 address!")
1564                                                 address = ""
1565
1566                                 players.append(NetworkReceiver(colour, address))
1567                         else:
1568                                 return None
1569                 #print str(self) + ".SelectPlayers returns " + str(players)
1570                 return players
1571                         
1572                                 
1573                         
1574 # --- graphics.py --- #
1575 #!/usr/bin/python -u
1576
1577 # Do you know what the -u does? It unbuffers stdin and stdout
1578 # I can't remember why, but last year things broke without that
1579
1580 """
1581         UCC::Progcomp 2013 Quantum Chess game
1582         @author Sam Moore [SZM] "matches"
1583         @copyright The University Computer Club, Incorporated
1584                 (ie: You can copy it for not for profit purposes)
1585 """
1586
1587 # system python modules or whatever they are called
1588 import sys
1589 import os
1590 import time
1591
1592 turn_delay = 0.5
1593 [game, graphics] = [None, None]
1594
1595 def make_player(name, colour):
1596         if name[0] == '@':
1597                 if name[1:] == "human":
1598                         return HumanPlayer(name, colour)
1599                 s = name[1:].split(":")
1600                 if s[0] == "network":
1601                         address = None
1602                         if len(s) > 1:
1603                                 address = s[1]
1604                         return NetworkReceiver(colour, address)
1605
1606         else:
1607                 return AgentPlayer(name, colour)
1608                         
1609
1610
1611 # The main function! It does the main stuff!
1612 def main(argv):
1613
1614         # Apparently python will silently treat things as local unless you do this
1615         # Anyone who says "You should never use a global variable" can die in a fire
1616         global game
1617         global graphics
1618         
1619         global turn_delay
1620         global agent_timeout
1621         global log_file
1622         global src_file
1623
1624
1625
1626         
1627         style = "quantum"
1628         colour = "white"
1629         graphics_enabled = True
1630
1631         players = []
1632         i = 0
1633         while i < len(argv)-1:
1634                 i += 1
1635                 arg = argv[i]
1636                 if arg[0] != '-':
1637                         players.append(make_player(arg, colour))
1638                         if colour == "white":
1639                                 colour = "black"
1640                         elif colour == "black":
1641                                 pass
1642                         else:
1643                                 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
1644                         continue
1645
1646                 # Option parsing goes here
1647                 if arg[1] == '-' and arg[2:] == "classical":
1648                         style = "classical"
1649                 elif arg[1] == '-' and arg[2:] == "quantum":
1650                         style = "quantum"
1651                 elif (arg[1] == '-' and arg[2:] == "graphics"):
1652                         graphics_enabled = not graphics_enabled
1653                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
1654                         # Load game from file
1655                         if len(arg[2:].split("=")) == 1:
1656                                 src_file = sys.stdout
1657                         else:
1658                                 src_file = arg[2:].split("=")[1]
1659                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
1660                         # Log file
1661                         if len(arg[2:].split("=")) == 1:
1662                                 log_file = sys.stdout
1663                         else:
1664                                 log_file = arg[2:].split("=")[1]
1665                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
1666                         # Delay
1667                         if len(arg[2:].split("=")) == 1:
1668                                 turn_delay = 0
1669                         else:
1670                                 turn_delay = float(arg[2:].split("=")[1])
1671
1672                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
1673                         # Timeout
1674                         if len(arg[2:].split("=")) == 1:
1675                                 agent_timeout = -1
1676                         else:
1677                                 agent_timeout = float(arg[2:].split("=")[1])
1678                                 
1679                 elif (arg[1] == '-' and arg[2:] == "help"):
1680                         # Help
1681                         os.system("less data/help.txt") # The best help function
1682                         return 0
1683
1684
1685         # Create the board
1686         board = Board(style)
1687
1688
1689         # Initialise GUI
1690         if graphics_enabled == True:
1691                 try:
1692                         graphics = GraphicsThread(board, grid_sz = [64,64]) # Construct a GraphicsThread!
1693
1694                 except Exception,e:
1695                         graphics = None
1696                         sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
1697                         graphics_enabled = False
1698
1699         # If there are no players listed, display a nice pretty menu
1700         if len(players) != 2:
1701                 if graphics != None:
1702                         players = graphics.SelectPlayers(players)
1703                 else:
1704                         sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
1705                         return 44
1706
1707         # If there are still no players, quit
1708         if players == None or len(players) != 2:
1709                 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
1710                 return 45
1711
1712
1713         # Wrap NetworkSender players around original players if necessary
1714         for i in range(len(players)):
1715                 if isinstance(players[i], NetworkReceiver):
1716                         players[i].board = board # Network players need direct access to the board
1717                         for j in range(len(players)):
1718                                 if j == i:
1719                                         continue
1720                                 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
1721                                         continue
1722                                 players[j] = NetworkSender(players[j], players[i].address)
1723                                 players[j].board = board
1724
1725         # Connect the networked players
1726         for p in players:
1727                 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
1728                         if graphics != None:
1729                                 graphics.board.display_grid(graphics.window, graphics.grid_sz)
1730                                 graphics.message("Connecting to " + p.colour + " player...")
1731                         p.connect()
1732
1733         
1734         # If using windows, select won't work; use horrible TimeoutPlayer hack
1735         if agent_timeout > 0 and platform.system() == "Windows":
1736                 sys.stderr.write(sys.argv[0] + " : Warning - You are using Windows\n")
1737                 sys.stderr.write(sys.argv[0] + " :         - Timeouts will be implemented with a terrible hack.\n")
1738
1739                 for i in range(len(players)):
1740                         if isinstance(players[i], AgentPlayer):
1741                                 players[i] = TimeoutPlayer(players[i], agent_timeout)
1742
1743         # Could potentially wrap TimeoutPlayer around internal classes...
1744         # But that would suck
1745
1746                 
1747                         
1748
1749
1750         # Construct a GameThread! Make it global! Damn the consequences!
1751         game = GameThread(board, players) 
1752
1753
1754         
1755         if graphics != None:
1756                 game.start() # This runs in a new thread
1757                 graphics.run()
1758                 game.join()
1759                 return game.error + graphics.error
1760         else:
1761                 game.run()
1762                 return game.error
1763
1764 # This is how python does a main() function...
1765 if __name__ == "__main__":
1766         sys.exit(main(sys.argv))
1767 # --- main.py --- #
1768 # EOF - created from make on Mon Jan 28 22:52:28 WST 2013

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