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

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