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}
8 # Class to represent a quantum chess 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)
19 self.last_state = None
21 self.move_pattern = None
23 self.possible_moves = {}
26 def init_from_copy(self, c):
27 self.colour = c.colour
30 self.types = c.types[:]
31 self.current_type = c.current_type
32 self.choice = c.choice
34 self.last_state = None
35 self.move_pattern = None
39 # Make a string for the piece (used for debug)
41 return str(self.colour) + " " + str(self.current_type) + " " + str(self.types) + " at " + str(self.x) + ","+str(self.y)
43 # Draw the piece in a pygame surface
44 def draw(self, window, grid_sz = [80,80], style="quantum"):
46 # First draw the image corresponding to self.current_type
47 img = images[self.colour][self.current_type]
49 if style == "classical":
50 offset = [-rect.width/2, -rect.height/2]
52 offset = [-rect.width/2,-3*rect.height/4]
53 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 if style == "classical":
59 # Draw the two possible types underneath the current_type image
60 for i in range(len(self.types)):
61 if always_reveal_states == True or self.types[i][0] != '?':
62 if self.types[i][0] == '?':
63 img = small_images[self.colour][self.types[i][1:]]
65 img = small_images[self.colour][self.types[i]]
67 img = small_images[self.colour]["unknown"] # If the type hasn't been revealed, show a placeholder
71 offset = [-rect.width/2,-rect.height/2]
74 target = (self.x * grid_sz[0] + grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])
76 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])
78 window.blit(img, target) # Blit shit
80 # Collapses the wave function!
82 if self.current_type == "unknown" or not self.choice in [0,1]:
83 self.choice = random.randint(0,1)
84 if self.types[self.choice][0] == '?':
85 self.types[self.choice] = self.types[self.choice][1:]
86 self.current_type = self.types[self.choice]
89 # Uncollapses (?) the wave function!
91 #print "Deselect called"
92 if (self.x + self.y) % 2 != 0:
93 if (self.types[0] != self.types[1]) or (self.types[0][0] == '?' or self.types[1][0] == '?'):
94 self.current_type = "unknown"
97 self.choice = 0 # Both the two types are the same
99 # The sad moment when you realise that you do not understand anything about a subject you studied for 4 years...
101 [w,h] = [8,8] # Width and height of board(s)
103 always_reveal_states = False
105 # Class to represent a quantum chess board
107 # Initialise; if master=True then the secondary piece types are assigned
108 # Otherwise, they are left as unknown
109 # So you can use this class in Agent programs, and fill in the types as they are revealed
110 def __init__(self, style="agent"):
112 self.pieces = {"white" : [], "black" : []}
113 self.grid = [[None] * w for _ in range(h)] # 2D List (you can get arrays in python, somehow, but they scare me)
114 self.unrevealed_types = {"white" : piece_types.copy(), "black" : piece_types.copy()}
115 self.king = {"white" : None, "black" : None} # We need to keep track of the king, because he is important
116 self.max_moves = None
119 for c in ["black", "white"]:
120 del self.unrevealed_types[c]["unknown"]
125 # Add all the pieces with known primary types
126 for i in range(0, 2):
128 s = ["black", "white"][i]
132 c.append(Piece(s, 0, y, ["rook"]))
133 c.append(Piece(s, 1, y, ["knight"]))
134 c.append(Piece(s, 2, y, ["bishop"]))
135 k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
136 k.current_type = "king"
139 c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
140 c.append(Piece(s, 5, y, ["bishop"]))
141 c.append(Piece(s, 6, y, ["knight"]))
142 c.append(Piece(s, 7, y, ["rook"]))
150 for x in range(0, w):
151 c.append(Piece(s, x, y, ["pawn"]))
154 types_left.update(piece_types)
155 del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
156 del types_left["unknown"] # We certainly don't want these!
159 self.grid[piece.x][piece.y] = piece
161 if len(piece.types) > 1:
163 if style == "agent": # Assign placeholder "unknown" secondary type
164 piece.types.append("unknown")
167 elif style == "quantum":
168 # The master allocates the secondary types
169 choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
170 types_left[choice] -= 1
171 if types_left[choice] <= 0:
172 del types_left[choice]
173 piece.types.append('?' + choice)
174 elif style == "classical":
175 piece.types.append(piece.types[0])
176 piece.current_type = piece.types[0]
180 newboard = Board(master = False)
181 newpieces = newboard.pieces["white"] + newboard.pieces["black"]
182 mypieces = self.pieces["white"] + self.pieces["black"]
184 for i in range(len(mypieces)):
185 newpieces[i].init_from_copy(mypieces[i])
187 # Reset the board from a string
188 def reset_board(self, s):
189 self.pieces = {"white" : [], "black" : []}
190 self.king = {"white" : None, "black" : None}
191 self.grid = [[None] * w for _ in range(h)]
194 self.grid[x][y] = None
196 for line in s.split("\n"):
202 tokens = line.split(" ")
203 [x, y] = map(int, tokens[len(tokens)-1].split(","))
204 current_type = tokens[1]
205 types = map(lambda e : e.strip(" '[],"), line.split('[')[1].split(']')[0].split(','))
207 target = Piece(tokens[0], x, y, types)
208 target.current_type = current_type
211 target.choice = types.index(current_type)
215 self.pieces[tokens[0]].append(target)
216 if target.current_type == "king":
217 self.king[tokens[0]] = target
219 self.grid[x][y] = target
222 def display_grid(self, window = None, grid_sz = [80,80]):
224 return # I was considering implementing a text only display, then I thought "Fuck that"
226 # The indentation is getting seriously out of hand...
227 for x in range(0, w):
228 for y in range(0, h):
230 c = pygame.Color(200,200,200)
232 c = pygame.Color(64,64,64)
233 pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))
235 def display_pieces(self, window = None, grid_sz = [80,80]):
238 for p in self.pieces["white"] + self.pieces["black"]:
239 p.draw(window, grid_sz, self.style)
241 # Draw the board in a pygame window
242 def display(self, window = None):
243 self.display_grid(window)
244 self.display_pieces(window)
252 if self.grid[x][y] == None:
254 if (self.grid[x][y].x != x or self.grid[x][y].y != y):
255 raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))
257 # Select a piece on the board (colour is the colour of whoever is doing the selecting)
258 def select(self, x,y, colour=None):
259 if not self.on_board(x, y): # Get on board everyone!
260 raise Exception("BOUNDS " + str(x) + ","+str(y))
262 piece = self.grid[x][y]
264 raise Exception("EMPTY")
266 if colour != None and piece.colour != colour:
267 raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
269 # I'm not quite sure why I made this return a string, but screw logical design
270 return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)
273 # Update the board when a piece has been selected
274 # "type" is apparently reserved, so I'll use "state"
275 def update_select(self, x, y, type_index, state, sanity=True, deselect=True):
276 #debug(str(self) + " update_select called")
277 piece = self.grid[x][y]
278 if piece.types[type_index] == "unknown":
279 if not state in self.unrevealed_types[piece.colour].keys() and sanity == True:
280 raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
281 self.unrevealed_types[piece.colour][state] -= 1
282 if self.unrevealed_types[piece.colour][state] <= 0:
283 del self.unrevealed_types[piece.colour][state]
285 piece.types[type_index] = state
286 piece.current_type = state
288 if deselect == True and len(self.possible_moves(piece)) <= 0:
289 piece.deselect() # Piece can't move; deselect it
291 # Piece needs to recalculate moves
292 piece.possible_moves = None
294 # Update the board when a piece has been moved
295 def update_move(self, x, y, x2, y2, sanity=True):
296 #debug(str(self) + " update_move called \""+str(x)+ " " + str(y) + " -> " + str(x2) + " " + str(y2) + "\"")
297 piece = self.grid[x][y]
298 #print "Moving " + str(x) + "," + str(y) + " to " + str(x2) + "," + str(y2) + "; possible_moves are " + str(self.possible_moves(piece))
300 if not [x2,y2] in self.possible_moves(piece) and sanity == True:
301 raise Exception("ILLEGAL move " + str(x2)+","+str(y2))
303 self.grid[x][y] = None
304 taken = self.grid[x2][y2]
306 if taken.current_type == "king":
307 self.king[taken.colour] = None
308 self.pieces[taken.colour].remove(taken)
309 self.grid[x2][y2] = piece
313 # If the piece is a pawn, and it reaches the final row, it becomes a queen
314 # I know you are supposed to get a choice
315 # But that would be effort
316 if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
317 if self.style == "classical":
318 piece.types[0] = "queen"
319 piece.types[1] = "queen"
321 piece.types[piece.choice] = "queen"
322 piece.current_type = "queen"
324 piece.deselect() # Uncollapse (?) the wavefunction!
327 # All other pieces need to recalculate moves
328 for p in self.pieces["white"] + self.pieces["black"]:
329 p.possible_moves = None
333 # Update the board from a string
334 # Guesses what to do based on the format of the string
335 def update(self, result, sanity=True, deselect=True):
336 #debug(str(self) + " update called \""+str(result)+"\"")
337 # String always starts with 'x y'
339 s = result.split(" ")
340 [x,y] = map(int, s[0:2])
342 raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations
344 piece = self.grid[x][y]
345 if piece == None and sanity == True:
346 raise Exception("EMPTY " + str(x) + " " + str(y))
348 # If a piece is being moved, the third token is '->'
349 # We could get away with just using four integers, but that wouldn't look as cool
351 # Last two tokens are the destination
353 [x2,y2] = map(int, s[3:])
355 raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm
357 # Move the piece (take opponent if possible)
358 self.update_move(x, y, x2, y2, sanity)
361 # Otherwise we will just assume a piece has been selected
363 type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
364 state = s[3] # The last token is a string identifying the type
366 raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit
370 self.update_select(x, y, type_index, state, sanity=sanity, deselect=deselect)
374 # Gets each piece that could reach the given square and the probability that it could reach that square
375 # Will include allied pieces that defend the attacker
376 def coverage(self, x, y, colour = None, reject_allied = True):
380 pieces = self.pieces["white"] + self.pieces["black"]
382 pieces = self.pieces[colour]
385 prob = self.probability_grid(p, reject_allied)[x][y]
387 result.update({p : prob})
396 # Associates each square with a probability that the piece could move into it
397 # Look, I'm doing all the hard work for you here...
398 def probability_grid(self, p, reject_allied = True):
400 result = [[0.0] * w for _ in range(h)]
401 if not isinstance(p, Piece):
404 if p.current_type != "unknown":
405 #sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
406 for point in self.possible_moves(p, reject_allied):
407 result[point[0]][point[1]] = 1.0
411 for i in range(len(p.types)):
413 prob = 1.0 / float(len(p.types))
414 if t == "unknown" or p.types[i][0] == '?':
416 for t2 in self.unrevealed_types[p.colour].keys():
417 total_types += self.unrevealed_types[p.colour][t2]
419 for t2 in self.unrevealed_types[p.colour].keys():
420 prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
422 for point in self.possible_moves(p, reject_allied, state=t2):
423 result[point[0]][point[1]] += prob2 * prob
427 for point in self.possible_moves(p, reject_allied, state=t):
428 result[point[0]][point[1]] += prob
431 #p.current_type = "unknown"
434 def prob_is_type(self, p, state):
437 for i in range(len(p.types)):
442 if t == "unknown" or p.types[i][0] == '?':
444 for t2 in self.unrevealed_types[p.colour].keys():
445 total_prob += self.unrevealed_types[p.colour][t2]
446 for t2 in self.unrevealed_types[p.colour].keys():
448 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
452 # Get all squares that the piece could move into
453 # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
454 # reject_allied indicates whether squares occupied by allied pieces will be removed
455 # (set to false to check for defense)
456 def possible_moves(self, p, reject_allied = True, state=None):
458 raise Exception("SANITY: No piece")
462 if state != None and state != p.current_type:
463 old_type = p.current_type
464 p.current_type = state
465 result = self.possible_moves(p, reject_allied, state=None)
466 p.current_type = old_type
476 if p.current_type == "unknown":
477 raise Exception("SANITY: Unknown state for piece: "+str(p))
478 # The below commented out code causes things to break badly
483 # result += self.possible_moves(p)
484 #p.current_type = "unknown"
487 if p.current_type == "king":
488 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]]
489 elif p.current_type == "queen":
490 for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
491 result += self.scan(p.x, p.y, d[0], d[1])
492 elif p.current_type == "bishop":
493 for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
494 result += self.scan(p.x, p.y, d[0], d[1])
495 elif p.current_type == "rook":
496 for d in [[-1,0],[1,0],[0,-1],[0,1]]:
497 result += self.scan(p.x, p.y, d[0], d[1])
498 elif p.current_type == "knight":
499 # I would use two lines, but I'm not sure how python likes that
500 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]]
501 elif p.current_type == "pawn":
502 if p.colour == "white":
504 # Pawn can't move forward into occupied square
505 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
506 result = [[p.x,p.y-1]]
507 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
508 if not self.on_board(f[0], f[1]):
510 if self.grid[f[0]][f[1]] != None: # Pawn can take diagonally
513 # Slightly embarrassing if the pawn jumps over someone on its first move...
514 if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
515 result.append([p.x, p.y-2])
517 # Vice versa for the black pawn
518 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
519 result = [[p.x,p.y+1]]
521 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
522 if not self.on_board(f[0], f[1]):
524 if self.grid[f[0]][f[1]] != None:
525 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
528 if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
529 result.append([p.x, p.y+2])
531 #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
533 # Remove illegal moves
534 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
535 for point in result[:]:
537 if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
538 result.remove(point) # Remove locations outside the board
540 g = self.grid[point[0]][point[1]]
542 if g != None and (g.colour == p.colour and reject_allied == True):
543 result.remove(point) # Remove allied pieces
547 p.possible_moves = result
551 # Scans in a direction until it hits a piece, returns all squares in the line
552 # (includes the final square (which contains a piece), but not the original square)
553 def scan(self, x, y, vx, vy):
561 if not self.on_board(xx, yy):
565 g = self.grid[xx][yy]
571 # Returns "white", "black" or "DRAW" if the game should end
572 def end_condition(self):
573 if self.king["white"] == None:
574 if self.king["black"] == None:
575 return "DRAW" # This shouldn't happen
577 elif self.king["black"] == None:
579 elif len(self.pieces["white"]) == 1 and len(self.pieces["black"]) == 1:
581 elif self.max_moves != None and self.moves > self.max_moves:
586 # I typed the full statement about 30 times before writing this function...
587 def on_board(self, x, y):
588 return (x >= 0 and x < w) and (y >= 0 and y < h)
590 # Pushes a move temporarily
591 def push_move(self, piece, x, y):
592 target = self.grid[x][y]
593 self.move_stack.append([piece, target, piece.x, piece.y, x, y])
594 [piece.x, piece.y] = [x, y]
595 self.grid[x][y] = piece
596 self.grid[piece.x][piece.y] = None
598 for p in self.pieces["white"] + self.pieces["black"]:
599 p.possible_moves = None
603 #print str(self.move_stack)
604 [piece, target, x1, y1, x2, y2] = self.move_stack[len(self.move_stack)-1]
605 self.move_stack = self.move_stack[:-1]
608 self.grid[x1][y1] = piece
612 self.grid[x2][y2] = target
614 for p in self.pieces["white"] + self.pieces["black"]:
615 p.possible_moves = None
623 agent_timeout = -1.0 # Timeout in seconds for AI players to make moves
624 # WARNING: Won't work for windows based operating systems
626 if platform.system() == "Windows":
627 agent_timeout = -1 # Hence this
629 # A player who can't play
631 def __init__(self, name, colour):
635 def update(self, result):
638 def reset_board(self, s):
642 return self.name + "<"+str(self.colour)+">"
644 def base_player(self):
647 # Player that runs from another process
648 class ExternalAgent(Player):
651 def __init__(self, name, colour):
652 Player.__init__(self, name, colour)
653 self.p = subprocess.Popen(name,bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,universal_newlines=True)
655 self.send_message(colour)
657 def send_message(self, s):
658 if agent_timeout > 0.0:
659 ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
661 ready = [self.p.stdin]
662 if self.p.stdin in ready:
663 #sys.stderr.write("Writing \'" + s + "\' to " + str(self.p) + "\n")
665 self.p.stdin.write(s + "\n")
667 raise Exception("UNRESPONSIVE")
669 raise Exception("TIMEOUT")
671 def get_response(self):
672 if agent_timeout > 0.0:
673 ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
675 ready = [self.p.stdout]
676 if self.p.stdout in ready:
677 #sys.stderr.write("Reading from " + str(self.p) + " 's stdout...\n")
679 result = self.p.stdout.readline().strip(" \t\r\n")
680 #sys.stderr.write("Read \'" + result + "\' from " + str(self.p) + "\n")
682 except: # Exception, e:
683 raise Exception("UNRESPONSIVE")
685 raise Exception("TIMEOUT")
689 self.send_message("SELECTION?")
690 line = self.get_response()
693 m = re.match("\s*(\d+)\s+(\d+)\s*", line)
694 result = map(int, [m.group(1), m.group(2)])
696 raise Exception("GIBBERISH \"" + str(line) + "\"")
699 def update(self, result):
700 #print "Update " + str(result) + " called for AgentPlayer"
701 self.send_message(result)
706 self.send_message("MOVE?")
707 line = self.get_response()
710 m = re.match("\s*(\d+)\s+(\d+)\s*", line)
711 result = map(int, [m.group(1), m.group(2)])
714 raise Exception("GIBBERISH \"" + str(line) + "\"")
717 def reset_board(self, s):
718 self.send_message("BOARD")
719 for line in s.split("\n"):
720 self.send_message(line.strip(" \r\n"))
721 self.send_message("END BOARD")
723 def quit(self, final_result):
725 self.send_message("QUIT " + final_result)
729 # So you want to be a player here?
730 class HumanPlayer(Player):
731 def __init__(self, name, colour):
732 Player.__init__(self, name, colour)
734 # Select your preferred account
736 if isinstance(graphics, GraphicsThread):
737 # Basically, we let the graphics thread do some shit and then return that information to the game thread
738 graphics.cond.acquire()
739 # We wait for the graphics thread to select a piece
740 while graphics.stopped() == False and graphics.state["select"] == None:
741 graphics.cond.wait() # The difference between humans and machines is that humans sleep
742 select = graphics.state["select"]
745 graphics.cond.release()
746 if graphics.stopped():
748 return [select.x, select.y]
750 # Since I don't display the board in this case, I'm not sure why I filled it in...
752 sys.stdout.write("SELECTION?\n")
754 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
756 sys.stderr.write("ILLEGAL GIBBERISH\n")
758 # It's your move captain
760 if isinstance(graphics, GraphicsThread):
761 graphics.cond.acquire()
762 while graphics.stopped() == False and graphics.state["dest"] == None:
764 graphics.cond.release()
766 return graphics.state["dest"]
770 sys.stdout.write("MOVE?\n")
772 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
774 sys.stderr.write("ILLEGAL GIBBERISH\n")
777 # Are you sure you want to quit?
778 def quit(self, final_result):
780 sys.stdout.write("QUIT " + final_result + "\n")
782 # Completely useless function
783 def update(self, result):
784 if isinstance(graphics, GraphicsThread):
787 sys.stdout.write(result + "\n")
791 # Default internal player (makes random moves)
792 class InternalAgent(Player):
793 def __init__(self, name, colour):
794 Player.__init__(self, name, colour)
797 self.board = Board(style = "agent")
801 def update(self, result):
803 self.board.update(result)
807 def reset_board(self, s):
808 self.board.reset_board(s)
810 def quit(self, final_result):
813 class AgentRandom(InternalAgent):
814 def __init__(self, name, colour):
815 InternalAgent.__init__(self, name, colour)
819 self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
821 # Check that the piece has some possibility to move
822 tmp = self.choice.current_type
823 if tmp == "unknown": # For unknown pieces, try both types
824 for t in self.choice.types:
827 self.choice.current_type = t
828 all_moves += self.board.possible_moves(self.choice)
830 all_moves = self.board.possible_moves(self.choice)
831 self.choice.current_type = tmp
832 if len(all_moves) > 0:
834 return [self.choice.x, self.choice.y]
837 moves = self.board.possible_moves(self.choice)
838 move = moves[random.randint(0, len(moves)-1)]
842 # Terrible, terrible hacks
844 def run_agent(agent):
845 #sys.stderr.write(sys.argv[0] + " : Running agent " + str(agent) + "\n")
847 line = sys.stdin.readline().strip(" \r\n")
848 if line == "SELECTION?":
849 #sys.stderr.write(sys.argv[0] + " : Make selection\n")
850 [x,y] = agent.select() # Gets your agent's selection
851 #sys.stderr.write(sys.argv[0] + " : Selection was " + str(agent.choice) + "\n")
852 sys.stdout.write(str(x) + " " + str(y) + "\n")
853 elif line == "MOVE?":
854 #sys.stderr.write(sys.argv[0] + " : Make move\n")
855 [x,y] = agent.get_move() # Gets your agent's move
856 sys.stdout.write(str(x) + " " + str(y) + "\n")
857 elif line.split(" ")[0] == "QUIT":
858 #sys.stderr.write(sys.argv[0] + " : Quitting\n")
859 agent.quit(" ".join(line.split(" ")[1:])) # Quits the game
861 elif line.split(" ")[0] == "BOARD":
863 line = sys.stdin.readline().strip(" \r\n")
864 while line != "END BOARD":
866 line = sys.stdin.readline().strip(" \r\n")
867 agent.board.reset_board(s)
870 agent.update(line) # Updates agent.board
876 class ExternalWrapper(ExternalAgent):
877 def __init__(self, agent):
878 run = "python -u -c \"import sys;import os;from qchess import *;agent = " + agent.__class__.__name__ + "('" + agent.name + "','"+agent.colour+"');sys.stdin.readline();sys.exit(run_agent(agent))\""
880 ExternalAgent.__init__(self, run, agent.colour)
884 # --- player.py --- #
888 class AgentBishop(AgentRandom): # Inherits from AgentRandom (in qchess)
889 def __init__(self, name, colour):
890 InternalAgent.__init__(self, name, colour)
891 self.value = {"pawn" : 1, "bishop" : 3, "knight" : 3, "rook" : 5, "queen" : 9, "king" : 100, "unknown" : 4}
893 self.aggression = 2.0 # Multiplier for scoring due to aggressive actions
894 self.defence = 1.0 # Multiplier for scoring due to defensive actions
896 self.depth = 0 # Current depth
897 self.max_depth = 2 # Recurse this many times (for some reason, makes more mistakes when this is increased???)
898 self.recurse_for = -1 # Recurse for the best few moves each times (less than 0 = all moves)
900 for p in self.board.pieces["white"] + self.board.pieces["black"]:
902 p.selected_moves = None
906 def get_value(self, piece):
909 return float(self.value[piece.types[0]] + self.value[piece.types[1]]) / 2.0
911 # Score possible moves for the piece
913 def prioritise_moves(self, piece):
915 #sys.stderr.write(sys.argv[0] + " : " + str(self) + " prioritise called for " + str(piece) + "\n")
919 grid = self.board.probability_grid(piece)
920 #sys.stderr.write("\t Probability grid " + str(grid) + "\n")
924 if grid[x][y] < 0.3: # Throw out moves with < 30% probability
925 #sys.stderr.write("\tReject " + str(x) + "," + str(y) + " (" + str(grid[x][y]) + ")\n")
928 target = self.board.grid[x][y]
933 # Get total probability that the move is protected
934 self.board.push_move(piece, x, y)
938 defenders = self.board.coverage(x, y, piece.colour, reject_allied = False)
940 for d in defenders.keys():
941 d_prob += defenders[d]
942 if len(defenders.keys()) > 0:
943 d_prob /= float(len(defenders.keys()))
948 # Get total probability that the move is threatened
949 attackers = self.board.coverage(x, y, opponent(piece.colour), reject_allied = False)
951 for a in attackers.keys():
952 a_prob += attackers[a]
953 if len(attackers.keys()) > 0:
954 a_prob /= float(len(attackers.keys()))
959 self.board.pop_move()
964 value = self.aggression * (1.0 + d_prob) * self.get_value(target) - self.defence * (1.0 - d_prob) * a_prob * self.get_value(piece)
966 # Adjust score based on movement of piece out of danger
967 attackers = self.board.coverage(piece.x, piece.y, opponent(piece.colour))
969 for a in attackers.keys():
970 s_prob += attackers[a]
971 if len(attackers.keys()) > 0:
972 s_prob /= float(len(attackers.keys()))
976 value += self.defence * s_prob * self.get_value(piece)
978 # Adjust score based on probability that the move is actually possible
979 moves.append([[x, y], grid[x][y] * value])
981 moves.sort(key = lambda e : e[1], reverse = True)
982 #sys.stderr.write(sys.argv[0] + ": Moves for " + str(piece) + " are " + str(moves) + "\n")
984 piece.last_moves = moves
985 piece.selected_moves = None
992 def select_best(self, colour):
996 for p in self.board.pieces[colour]:
997 self.choice = p # Temporarily pick that piece
998 m = self.prioritise_moves(p)
1000 all_moves.update({p : m[0]})
1002 if len(all_moves.items()) <= 0:
1006 opts = all_moves.items()
1007 opts.sort(key = lambda e : e[1][1], reverse = True)
1009 if self.depth >= self.max_depth:
1011 return list(opts[0])
1013 if self.recurse_for >= 0:
1014 opts = opts[0:self.recurse_for]
1015 #sys.stderr.write(sys.argv[0] + " : Before recurse, options are " + str(opts) + "\n")
1017 # Take the best few moves, and recurse
1018 for choice in opts[0:self.recurse_for]:
1019 [xx,yy] = [choice[0].x, choice[0].y] # Remember position
1020 [nx,ny] = choice[1][0] # Target
1021 [choice[0].x, choice[0].y] = [nx, ny] # Set position
1022 target = self.board.grid[nx][ny] # Remember piece in spot
1023 self.board.grid[xx][yy] = None # Remove piece
1024 self.board.grid[nx][ny] = choice[0] # Replace with moving piece
1027 best_enemy_move = self.select_best(opponent(choice[0].colour))
1028 choice[1][1] -= best_enemy_move[1][1] / float(self.depth + 1.0)
1030 [choice[0].x, choice[0].y] = [xx, yy] # Restore position
1031 self.board.grid[nx][ny] = target # Restore taken piece
1032 self.board.grid[xx][yy] = choice[0] # Restore moved piece
1036 opts.sort(key = lambda e : e[1][1], reverse = True)
1037 #sys.stderr.write(sys.argv[0] + " : After recurse, options are " + str(opts) + "\n")
1040 return list(opts[0])
1044 # Returns [x,y] of selected piece
1046 #sys.stderr.write("Getting choice...")
1047 self.choice = self.select_best(self.colour)[0]
1049 #sys.stderr.write(" Done " + str(self.choice)+"\n")
1050 return [self.choice.x, self.choice.y]
1052 # Returns [x,y] of square to move selected piece into
1054 #sys.stderr.write("Choice is " + str(self.choice) + "\n")
1055 self.choice.selected_moves = self.choice.last_moves
1056 moves = self.prioritise_moves(self.choice)
1060 return AgentRandom.get_move(self)
1062 # --- agent_bishop.py --- #
1063 import multiprocessing
1065 # Hacky alternative to using select for timing out players
1067 # WARNING: Do not wrap around HumanPlayer or things breakify
1068 # WARNING: Do not use in general or things breakify
1070 class Sleeper(multiprocessing.Process):
1071 def __init__(self, timeout):
1072 multiprocessing.Process.__init__(self)
1073 self.timeout = timeout
1076 time.sleep(self.timeout)
1079 class Worker(multiprocessing.Process):
1080 def __init__(self, function, args, q):
1081 multiprocessing.Process.__init__(self)
1082 self.function = function
1087 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args)
1088 self.q.put(self.function(*self.args))
1092 def TimeoutFunction(function, args, timeout):
1093 q = multiprocessing.Queue()
1094 w = Worker(function, args, q)
1095 s = Sleeper(timeout)
1098 while True: # Busy loop of crappyness
1099 if not w.is_alive():
1103 #print "TimeoutFunction gets " + str(result)
1105 elif not s.is_alive():
1108 raise Exception("TIMEOUT")
1113 # A player that wraps another player and times out its moves
1115 # A (crappy) alternative to the use of select()
1116 class TimeoutPlayer(Player):
1117 def __init__(self, base_player, timeout):
1118 Player.__init__(self, base_player.name, base_player.colour)
1119 self.base_player = base_player
1120 self.timeout = timeout
1123 return TimeoutFunction(self.base_player.select, [], self.timeout)
1127 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
1129 def update(self, result):
1130 return TimeoutFunction(self.base_player.update, [result], self.timeout)
1132 def quit(self, final_result):
1133 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
1134 # --- timeout_player.py --- #
1138 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
1139 network_timeout_delay = 1.0 # Maximum time between two characters being received
1141 class NetworkPlayer(Player):
1142 def __init__(self, colour, network, player):
1143 Player.__init__(self, "@network:"+str(network.address), colour)
1144 self.player = player
1145 self.network = network
1148 return "NetworkPlayer<"+str(self.colour)+","+str(self.player)+">"
1151 #debug(str(self) + " select called")
1152 if self.player != None:
1153 s = self.player.select()
1154 self.send_message(str(s[0]) + " " + str(s[1]))
1156 s = map(int, self.get_response().split(" "))
1157 for p in game.players:
1158 if p != self and isinstance(p, NetworkPlayer) and p.player == None:
1159 p.network.send_message(str(s[0]) + " " + str(s[1]))
1161 game.final_result = "network terminate"
1165 def send_message(self, message):
1166 #debug(str(self) + " send_message(\""+str(message)+"\") called")
1167 self.network.send_message(message)
1169 def get_response(self):
1170 #debug(str(self) + " get_response() called")
1171 s = self.network.get_response()
1172 #debug(str(self) + " get_response() returns \""+str(s)+"\"")
1177 #debug(str(self) + " get_move called")
1178 if self.player != None:
1179 s = self.player.get_move()
1180 self.send_message(str(s[0]) + " " + str(s[1]))
1182 s = map(int, self.get_response().split(" "))
1183 for p in game.players:
1184 if p != self and isinstance(p, NetworkPlayer) and p.player == None:
1185 p.network.send_message(str(s[0]) + " " + str(s[1]))
1188 game.final_result = "network terminate"
1192 def update(self, result):
1193 #debug(str(self) + " update(\""+str(result)+"\") called")
1194 if self.network.server == True:
1195 if self.player == None:
1196 self.send_message(result)
1197 elif self.player != None:
1198 result = self.get_response()
1199 if result == "-1 -1":
1200 game.final_result = "network terminate"
1203 self.board.update(result, deselect=False)
1207 if self.player != None:
1208 result = self.player.update(result)
1214 def base_player(self):
1215 if self.player == None:
1218 return self.player.base_player()
1220 def quit(self, result):
1222 self.send_message("-1 -1")
1227 def __init__(self, address = (None,4562)):
1228 self.socket = socket.socket()
1229 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1230 #self.socket.setblocking(0)
1231 self.address = address
1232 self.server = (address[0] == None)
1235 self.connected = False
1238 #debug(str(self) + "Tries to connect")
1239 self.connected = True
1240 if self.address[0] == None:
1241 self.host = "0.0.0.0" #socket.gethostname() # Breaks things???
1242 self.socket.bind((self.host, self.address[1]))
1243 self.socket.listen(5)
1245 self.src, self.actual_address = self.socket.accept()
1247 self.src.send("ok\n")
1248 s = self.get_response()
1254 self.__init__(colour, (self.address[0], int(s)), baseplayer)
1259 self.socket.connect(self.address)
1260 self.src = self.socket
1261 self.src.send("ok\n")
1262 s = self.get_response()
1268 self.__init__(colour, (self.address[0], int(s)), baseplayer)
1274 return "@network:"+str(self.address)
1276 def get_response(self):
1278 # Timeout the start of the message (first character)
1279 if network_timeout_start > 0.0:
1280 ready = select.select([self.src], [], [], network_timeout_start)[0]
1283 if self.src in ready:
1284 s = self.src.recv(1)
1286 raise Exception("UNRESPONSIVE")
1289 while s[len(s)-1] != '\n':
1290 # Timeout on each character in the message
1291 if network_timeout_delay > 0.0:
1292 ready = select.select([self.src], [], [], network_timeout_delay)[0]
1295 if self.src in ready:
1296 s += self.src.recv(1)
1298 raise Exception("UNRESPONSIVE")
1301 return s.strip(" \r\n")
1303 def send_message(self,s):
1304 if network_timeout_start > 0.0:
1305 ready = select.select([], [self.src], [], network_timeout_start)[1]
1309 if self.src in ready:
1310 self.src.send(s + "\n")
1312 raise Exception("UNRESPONSIVE")
1319 # --- network.py --- #
1322 # A thread that can be stopped!
1323 # Except it can only be stopped if it checks self.stopped() periodically
1324 # So it can sort of be stopped
1325 class StoppableThread(threading.Thread):
1327 threading.Thread.__init__(self)
1328 self._stop = threading.Event()
1334 return self._stop.isSet()
1335 # --- thread_util.py --- #
1341 def __init__(self, log, name):
1345 self.log.write("# Log starts " + str(datetime.datetime.now()) + "\n")
1348 now = datetime.datetime.now()
1349 self.log.write(str(now) + " : " + s + "\n")
1350 self.logged.append((now, s))
1352 def setup(self, board, players):
1355 self.log.write("# " + str(p.colour) + " : " + str(p.name) + "\n")
1357 self.log.write("# Initial board\n")
1358 for x in range(0, w):
1359 for y in range(0, h):
1360 if board.grid[x][y] != None:
1361 self.log.write(str(board.grid[x][y]) + "\n")
1363 self.log.write("# Start game\n")
1366 self.log.write("# EOF\n")
1367 if self.log != sys.stdout:
1370 class ShortLog(LogFile):
1371 def __init__(self, file_name):
1373 self.log = sys.stdout
1375 self.log = open(file_name, "w", 0)
1376 LogFile.__init__(self, self.log, "@"+file_name)
1377 self.file_name = file_name
1381 now = datetime.datetime.now()
1382 self.logged.append((now, s))
1385 if self.log != sys.stdout:
1387 self.log = open(self.file_name, "w", 0)
1388 self.log.write("# Short log updated " + str(datetime.datetime.now()) + "\n")
1389 LogFile.setup(self, game.board, game.players)
1391 elif self.phase == 1:
1392 for message in self.logged[len(self.logged)-2:]:
1393 self.log.write(str(message[0]) + " : " + message[1] + "\n")
1395 self.phase = (self.phase + 1) % 2
1399 ending = self.logged[len(self.logged)-1]
1400 self.log.write(str(ending[0]) + " : " + ending[1] + "\n")
1401 self.log.write("# EOF\n")
1402 if self.log != sys.stdout:
1406 class HeadRequest(urllib2.Request):
1407 def get_method(self):
1410 class HttpGetter(StoppableThread):
1411 def __init__(self, address):
1412 StoppableThread.__init__(self)
1413 self.address = address
1414 self.log = urllib2.urlopen(address)
1416 self.lock = threading.RLock() #lock for access of self.state
1417 self.cond = threading.Condition() # conditional
1420 while not self.stopped():
1421 line = self.log.readline()
1423 date_mod = datetime.datetime.strptime(self.log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1426 next_log = urllib2.urlopen(HeadRequest(self.address))
1427 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1428 while date_new <= date_mod and not self.stopped():
1429 next_log = urllib2.urlopen(HeadRequest(self.address))
1430 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1434 self.log = urllib2.urlopen(self.address)
1435 line = self.log.readline()
1438 self.lines.append(line)
1439 self.cond.notifyAll()
1442 #sys.stderr.write(" HttpGetter got \'" + str(line) + "\'\n")
1451 def __init__(self, address):
1452 self.getter = HttpGetter(address)
1456 self.getter.cond.acquire()
1457 while len(self.getter.lines) == 0:
1458 self.getter.cond.wait()
1460 result = self.getter.lines[0]
1461 self.getter.lines = self.getter.lines[1:]
1462 self.getter.cond.release()
1471 def __init__(self, filename):
1472 self.f = open(filename, "r", 0)
1473 self.filename = filename
1474 self.mod = os.path.getmtime(filename)
1478 line = self.f.readline()
1481 mod2 = os.path.getmtime(self.filename)
1483 #sys.stderr.write("File changed!\n")
1486 self.f = open(self.filename, "r", 0)
1488 new_line = self.f.readline()
1490 if " ".join(new_line.split(" ")[0:3]) != "# Short log":
1491 for i in range(self.count):
1492 new_line = self.f.readline()
1493 #sys.stderr.write("Read back " + str(i) + ": " + str(new_line) + "\n")
1494 new_line = self.f.readline()
1512 sys.stderr.write("# DEBUG: " + s + "\n")
1515 def log_init(board, players):
1517 l.setup(board, players)
1525 # A thread that runs the game
1526 class GameThread(StoppableThread):
1527 def __init__(self, board, players, server = True):
1528 StoppableThread.__init__(self)
1530 self.players = players
1531 self.state = {"turn" : None} # The game state
1532 self.error = 0 # Whether the thread exits with an error
1533 self.lock = threading.RLock() #lock for access of self.state
1534 self.cond = threading.Condition() # conditional for some reason, I forgot
1535 self.final_result = ""
1536 self.server = server
1543 # Run the game (run in new thread with start(), run in current thread with run())
1546 while not self.stopped():
1548 for p in self.players:
1550 self.state["turn"] = p.base_player()
1553 [x,y] = p.select() # Player selects a square
1555 #debug("Quitting in select")
1558 if isinstance(p, NetworkPlayer):
1559 if p.network.server == True:
1560 result = self.board.select(x, y, colour = p.colour)
1565 result = self.board.select(x, y, colour = p.colour)
1567 result = p.update(result)
1570 for p2 in self.players:
1573 p2.update(result) # Inform players of what happened
1583 target = self.board.grid[x][y]
1584 if isinstance(graphics, GraphicsThread):
1586 graphics.state["moves"] = self.board.possible_moves(target)
1587 graphics.state["select"] = target
1589 time.sleep(turn_delay)
1592 if len(self.board.possible_moves(target)) == 0:
1593 #print "Piece cannot move"
1595 if isinstance(graphics, GraphicsThread):
1597 graphics.state["moves"] = None
1598 graphics.state["select"] = None
1599 graphics.state["dest"] = None
1603 [x2,y2] = p.get_move() # Player selects a destination
1608 #debug("Quitting in get_move")
1611 if isinstance(p, NetworkPlayer):
1612 if p.network.server == True:
1613 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1614 self.board.update_move(x, y, x2, y2)
1619 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1620 self.board.update_move(x, y, x2, y2)
1622 result = p.update(result)
1625 for p2 in self.players:
1628 p2.update(result) # Inform players of what happened
1642 if isinstance(graphics, GraphicsThread):
1644 graphics.state["moves"] = [[x2,y2]]
1646 time.sleep(turn_delay)
1648 if isinstance(graphics, GraphicsThread):
1650 graphics.state["select"] = None
1651 graphics.state["dest"] = None
1652 graphics.state["moves"] = None
1654 # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
1655 # except Exception,e:
1656 # result = e.message
1657 # #sys.stderr.write(result + "\n")
1661 # self.final_result = self.state["turn"].colour + " " + e.message
1663 end = self.board.end_condition()
1667 self.final_result = self.state["turn"].colour + " " + end
1669 self.final_result = end
1676 for p2 in self.players:
1677 p2.quit(self.final_result)
1679 log(self.final_result)
1681 if isinstance(graphics, GraphicsThread):
1685 # A thread that replays a log file
1686 class ReplayThread(GameThread):
1687 def __init__(self, players, src, end=False,max_moves=None):
1688 self.board = Board(style="empty")
1689 self.board.max_moves = max_moves
1690 GameThread.__init__(self, self.board, players)
1694 self.reset_board(self.src.readline())
1696 def reset_board(self, line):
1699 while line != "# Start game" and line != "# EOF":
1702 line = self.src.readline().strip(" \r\n")
1706 line = self.src.readline().strip(" \r\n")
1709 self_str += line + "\n"
1711 if self.players[0].name == "dummy" and self.players[1].name == "dummy":
1712 line = self.src.readline().strip(" \r\n")
1715 tokens = line.split(" ")
1716 types = map(lambda e : e.strip("[] ,'"), tokens[2:4])
1717 for i in range(len(types)):
1718 if types[i][0] == "?":
1719 types[i] = "unknown"
1721 agent_str += tokens[0] + " " + tokens[1] + " " + str(types) + " ".join(tokens[4:]) + "\n"
1722 line = self.src.readline().strip(" \r\n")
1724 for p in self.players:
1725 p.reset_board(agent_str)
1728 self.board.reset_board(self_str)
1734 line = self.src.readline().strip(" \r\n")
1735 while line != "# EOF":
1747 line = self.src.readline().strip(" \r\n")
1750 tokens = line.split(" ")
1751 if tokens[0] == "white" or tokens[0] == "black":
1752 self.reset_board(line)
1754 line = self.src.readline().strip(" \r\n")
1757 move = line.split(":")
1758 move = move[len(move)-1].strip(" \r\n")
1759 tokens = move.split(" ")
1763 [x,y] = map(int, tokens[0:2])
1771 target = self.board.grid[x][y]
1773 if target.colour == "white":
1774 self.state["turn"] = self.players[0]
1776 self.state["turn"] = self.players[1]
1778 move_piece = (tokens[2] == "->")
1780 [x2,y2] = map(int, tokens[len(tokens)-2:])
1782 if isinstance(graphics, GraphicsThread):
1784 graphics.state["select"] = target
1787 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
1788 if isinstance(graphics, GraphicsThread):
1790 if target.current_type != "unknown":
1791 graphics.state["moves"] = self.board.possible_moves(target)
1793 graphics.state["moves"] = None
1794 time.sleep(turn_delay)
1796 self.board.update_move(x, y, x2, y2)
1797 if isinstance(graphics, GraphicsThread):
1799 graphics.state["moves"] = [[x2,y2]]
1800 time.sleep(turn_delay)
1802 graphics.state["select"] = None
1803 graphics.state["moves"] = None
1804 graphics.state["dest"] = None
1810 for p in self.players:
1814 line = self.src.readline().strip(" \r\n")
1817 end = self.board.end_condition()
1819 self.final_result = end
1837 if self.end and isinstance(graphics, GraphicsThread):
1839 pass # Let the user stop the display
1840 elif not self.end and self.board.end_condition() == None:
1842 # Work out the last move
1844 t = last_line.split(" ")
1845 if t[len(t)-2] == "black":
1846 self.players.reverse()
1847 elif t[len(t)-2] == "white":
1849 elif self.state["turn"] != None and self.state["turn"].colour == "white":
1850 self.players.reverse()
1853 game = GameThread(self.board, self.players)
1860 def opponent(colour):
1861 if colour == "white":
1872 # Dictionary that stores the unicode character representations of the different pieces
1873 # Chess was clearly the reason why unicode was invented
1874 # For some reason none of the pygame chess implementations I found used them!
1875 piece_char = {"white" : {"king" : u'\u2654',
1876 "queen" : u'\u2655',
1878 "bishop" : u'\u2657',
1879 "knight" : u'\u2658',
1882 "black" : {"king" : u'\u265A',
1883 "queen" : u'\u265B',
1885 "bishop" : u'\u265D',
1886 "knight" : u'\u265E',
1890 images = {"white" : {}, "black" : {}}
1891 small_images = {"white" : {}, "black" : {}}
1893 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
1895 # Get the font sizes
1896 l_size = 5*(grid_sz[0] / 8)
1897 s_size = 3*(grid_sz[0] / 8)
1899 for c in piece_char.keys():
1902 for p in piece_char[c].keys():
1903 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
1904 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})
1906 for p in piece_char[c].keys():
1907 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1908 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1909 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1910 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1913 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
1914 if not os.path.exists(image_dir):
1915 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
1916 for c in piece_char.keys():
1917 for p in piece_char[c].keys():
1918 images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
1919 small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
1920 # --- images.py --- #
1921 graphics_enabled = True
1925 os.environ["SDL_VIDEO_ALLOW_SCREENSAVER"] = "1"
1927 graphics_enabled = False
1933 # A thread to make things pretty
1934 class GraphicsThread(StoppableThread):
1935 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1936 StoppableThread.__init__(self)
1940 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1941 pygame.display.set_caption(title)
1943 #print "Initialised properly"
1945 self.grid_sz = grid_sz[:]
1946 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
1948 self.lock = threading.RLock()
1949 self.cond = threading.Condition()
1950 self.sleep_timeout = None
1951 self.last_event = time.time()
1952 self.blackout = False
1955 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
1958 create_images(grid_sz)
1961 for c in images.keys():
1962 for p in images[c].keys():
1963 images[c][p] = images[c][p].convert(self.window)
1964 small_images[c][p] = small_images[c][p].convert(self.window)
1971 # On the run from the world
1974 while not self.stopped():
1976 if self.sleep_timeout == None or (time.time() - self.last_event) < self.sleep_timeout:
1978 #print "Display grid"
1979 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
1981 #print "Display overlay"
1984 #print "Display pieces"
1985 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
1986 self.blackout = False
1988 elif pygame.mouse.get_focused() and not self.blackout:
1989 os.system("xset dpms force off")
1990 self.blackout = True
1991 self.window.fill((0,0,0))
1993 pygame.display.flip()
1995 for event in pygame.event.get():
1996 self.last_event = time.time()
1997 if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_q):
1998 if isinstance(game, GameThread):
2000 game.final_result = ""
2001 if game.state["turn"] != None:
2002 game.final_result = game.state["turn"].colour + " "
2003 game.final_result += "terminated"
2007 elif event.type == pygame.MOUSEBUTTONDOWN:
2008 self.mouse_down(event)
2010 elif event.type == pygame.MOUSEBUTTONUP:
2011 self.mouse_up(event)
2020 self.message("Game ends, result \""+str(game.final_result) + "\"")
2023 # Wake up anyone who is sleeping
2028 pygame.quit() # Time to say goodbye
2030 # Mouse release event handler
2031 def mouse_up(self, event):
2032 if event.button == 3:
2034 self.state["overlay"] = None
2035 elif event.button == 2:
2037 self.state["coverage"] = None
2039 # Mouse click event handler
2040 def mouse_down(self, event):
2041 if event.button == 1:
2042 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
2043 if isinstance(game, GameThread):
2045 p = game.state["turn"]
2050 if isinstance(p, HumanPlayer):
2052 s = self.board.grid[m[0]][m[1]]
2053 select = self.state["select"]
2055 if s != None and s.colour != p.colour:
2056 self.message("Wrong colour") # Look at all this user friendliness!
2059 # Notify human player of move
2062 self.state["select"] = s
2063 self.state["dest"] = None
2072 if self.state["moves"] == None:
2075 if not m in self.state["moves"]:
2076 self.message("Illegal Move") # I still think last year's mouse interface was adequate
2081 if self.state["dest"] == None:
2083 self.state["dest"] = m
2084 self.state["select"] = None
2085 self.state["moves"] = None
2088 elif event.button == 3:
2089 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2090 if isinstance(game, GameThread):
2092 p = game.state["turn"]
2097 if isinstance(p, HumanPlayer):
2099 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
2101 elif event.button == 2:
2102 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2103 if isinstance(game, GameThread):
2105 p = game.state["turn"]
2110 if isinstance(p, HumanPlayer):
2112 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
2117 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
2118 # Draw square over the selected piece
2120 select = self.state["select"]
2122 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
2123 square_img.fill(pygame.Color(0,255,0,64))
2124 self.window.blit(square_img, mp)
2125 # If a piece is selected, draw all reachable squares
2126 # (This quality user interface has been patented)
2128 m = self.state["moves"]
2130 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
2132 mp = [self.grid_sz[i] * move[i] for i in range(2)]
2133 self.window.blit(square_img, mp)
2134 # If a piece is overlayed, show all squares that it has a probability to reach
2136 m = self.state["overlay"]
2141 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
2142 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
2143 self.window.blit(square_img, mp)
2144 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2145 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
2146 self.window.blit(text, mp)
2148 # If a square is selected, highlight all pieces that have a probability to reach it
2150 m = self.state["coverage"]
2153 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
2154 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
2155 self.window.blit(square_img, mp)
2156 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2157 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
2158 self.window.blit(text, mp)
2159 # Draw a square where the mouse is
2160 # This also serves to indicate who's turn it is
2162 if isinstance(game, GameThread):
2164 turn = game.state["turn"]
2168 if isinstance(turn, HumanPlayer):
2169 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
2170 square_img.fill(pygame.Color(0,0,255,128))
2171 if turn.colour == "white":
2172 c = pygame.Color(255,255,255)
2174 c = pygame.Color(0,0,0)
2175 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
2176 self.window.blit(square_img, mp)
2178 # Message in a bottle
2179 def message(self, string, pos = None, colour = None, font_size = 20):
2180 #print "Drawing message..."
2181 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2183 colour = pygame.Color(0,0,0)
2185 text = font.render(string, 1, colour)
2188 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
2189 s.fill(pygame.Color(128,128,128))
2191 tmp = self.window.get_size()
2194 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
2196 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
2199 rect = (pos[0], pos[1], text.get_width(), text.get_height())
2201 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
2202 self.window.blit(s, pos)
2203 self.window.blit(text, pos)
2205 pygame.display.flip()
2207 def getstr(self, prompt = None):
2208 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
2209 s.blit(self.window, (0,0))
2215 self.message(prompt)
2216 self.message(result, pos = (0, 1))
2219 for event in pygame.event.get():
2220 if event.type == pygame.QUIT:
2222 if event.type == pygame.KEYDOWN:
2223 if event.key == pygame.K_BACKSPACE:
2224 result = result[0:len(result)-1]
2225 self.window.blit(s, (0,0)) # Revert the display
2230 if event.unicode == '\r':
2233 result += str(event.unicode)
2238 # Function to pick a button
2239 def SelectButton(self, choices, prompt = None, font_size=20):
2241 #print "Select button called!"
2242 self.board.display_grid(self.window, self.grid_sz)
2244 self.message(prompt)
2245 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2247 sz = self.window.get_size()
2250 for i in range(len(choices)):
2253 text = font.render(c, 1, pygame.Color(0,0,0))
2254 p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
2255 targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
2258 mp =pygame.mouse.get_pos()
2259 for i in range(len(choices)):
2261 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
2262 font_colour = pygame.Color(255,0,0)
2263 box_colour = pygame.Color(0,0,255,128)
2265 font_colour = pygame.Color(0,0,0)
2266 box_colour = pygame.Color(128,128,128)
2268 text = font.render(c, 1, font_colour)
2269 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
2271 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
2272 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
2273 self.window.blit(s, targets[i][0:2])
2276 pygame.display.flip()
2278 for event in pygame.event.get():
2279 if event.type == pygame.QUIT:
2281 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
2282 for i in range(len(targets)):
2284 if event.pos[0] > t[0] and event.pos[0] < t[2]:
2285 if event.pos[1] > t[1] and event.pos[1] < t[3]:
2287 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
2290 # Function to choose between dedicated server or normal play
2291 def SelectServer(self):
2293 choice = self.SelectButton(["Normal", "Join Eigenserver"],prompt="Game type?")
2296 choice = self.SelectButton(["progcomp.ucc", "other"], prompt="Address?")
2298 return "progcomp.ucc.asn.au"
2300 return self.getstr(prompt = "Enter address:")
2302 # Function to pick players in a nice GUI way
2303 def SelectPlayers(self, players = []):
2306 #print "SelectPlayers called"
2308 missing = ["white", "black"]
2310 missing.remove(p.colour)
2312 for colour in missing:
2315 choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
2317 players.append(HumanPlayer("human", colour))
2320 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2321 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2322 internal_agents.remove(('InternalAgent', InternalAgent))
2323 if len(internal_agents) > 0:
2324 choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
2329 agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
2330 players.append(agent[1](agent[0], colour))
2334 from tkFileDialog import askopenfilename
2335 root = Tkinter.Tk() # Need a root to make Tkinter behave
2336 root.withdraw() # Some sort of magic incantation
2337 path = askopenfilename(parent=root, initialdir="../agents",title=
2340 return self.SelectPlayers()
2341 players.append(make_player(path, colour))
2346 self.board.display_grid(self.window, self.grid_sz)
2347 pygame.display.flip()
2348 path = self.getstr(prompt = "Enter path:")
2353 return self.SelectPlayers()
2356 p = make_player(path, colour)
2358 self.board.display_grid(self.window, self.grid_sz)
2359 pygame.display.flip()
2360 self.message("Invalid path!")
2366 while address == "":
2367 self.board.display_grid(self.window, self.grid_sz)
2369 address = self.getstr(prompt = "Address? (leave blank for server)")
2376 map(int, address.split("."))
2378 self.board.display_grid(self.window, self.grid_sz)
2379 self.message("Invalid IPv4 address!")
2382 players.append(NetworkReceiver(colour, address))
2385 #print str(self) + ".SelectPlayers returns " + str(players)
2390 # --- graphics.py --- #
2391 def dedicated_server():
2400 log("Getting clients...")
2402 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2403 s.bind(("0.0.0.0", 4562))
2407 log("Got white player")
2409 args = ["python", "qchess.py", "--no-graphics", "@network::"+str(4600+2*len(games)), "@network::"+str(4600+2*len(games))]
2410 if len(log_files) != 0:
2413 args.append("--log")
2415 args.append("--log="+str(l.name)+"_"+str(gameID))
2417 g = subprocess.Popen(args, stdout=subprocess.PIPE)
2421 ss[0].send("white " + str(4600 + 2*(len(games)-1)))
2422 ss[0].shutdown(socket.SHUT_RD)
2428 log("Got black player")
2431 ss[0].send("black " + str(4600 + 2*(len(games)-1)))
2432 ss[0].shutdown(socket.SHUT_RD)
2435 s.shutdown(socket.SHUT_RDWR)
2439 while len(games) > max_games:
2440 #log("Too many games; waiting for game to finish...")
2441 ready = select.select(map(lambda e : e.stdout, games),[], [])
2443 s = r.readline().strip(" \r\n").split(" ")
2444 if s[0] == "white" or s[0] == "black":
2447 log("Game " + str(g) + " has finished")
2457 s.connect((addr, 4562))
2459 [colour,port] = s.recv(1024).strip(" \r\n").split(" ")
2461 #debug("Colour: " + colour + ", port: " + port)
2463 s.shutdown(socket.SHUT_RDWR)
2466 if colour == "white":
2467 p = subprocess.Popen(["python", "qchess.py", "@human", "@network:"+addr+":"+port])
2469 p = subprocess.Popen(["python", "qchess.py", "@network:"+addr+":"+port, "@human"])
2471 return 0# --- server.py --- #
2472 #!/usr/bin/python -u
2474 # Do you know what the -u does? It unbuffers stdin and stdout
2475 # I can't remember why, but last year things broke without that
2478 UCC::Progcomp 2013 Quantum Chess game
2479 @author Sam Moore [SZM] "matches"
2480 @copyright The University Computer Club, Incorporated
2481 (ie: You can copy it for not for profit purposes)
2484 # system python modules or whatever they are called
2490 sleep_timeout = None
2491 [game, graphics] = [None, None]
2493 def make_player(name, colour):
2495 if name[1:] == "human":
2496 return HumanPlayer(name, colour)
2497 s = name[1:].split(":")
2498 if s[0] == "network":
2509 if colour == "black":
2511 elif colour == "white":
2514 return NetworkPlayer(colour, Network((ip, port)), None)
2515 if s[0] == "internal":
2518 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2519 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2520 internal_agents.remove(('InternalAgent', InternalAgent))
2523 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
2524 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2527 for a in internal_agents:
2529 return a[1](name, colour)
2531 sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
2532 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2537 return ExternalAgent(name, colour)
2541 # The main function! It does the main stuff!
2544 # Apparently python will silently treat things as local unless you do this
2545 # Anyone who says "You should never use a global variable" can die in a fire
2550 global agent_timeout
2553 global graphics_enabled
2554 global always_reveal_states
2555 global sleep_timeout
2566 # Get the important warnings out of the way
2567 if platform.system() == "Windows":
2568 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
2569 if platform.release() == "Vista":
2570 sys.stderr.write(sys.argv[0] + " : God help you.\n")
2575 while i < len(argv)-1:
2579 p = make_player(arg, colour)
2580 if not isinstance(p, Player):
2581 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
2584 if colour == "white":
2586 elif colour == "black":
2589 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
2592 # Option parsing goes here
2593 if arg[1] == '-' and arg[2:] == "classical":
2595 elif arg[1] == '-' and arg[2:] == "quantum":
2597 elif arg[1] == '-' and arg[2:] == "reveal":
2598 always_reveal_states = True
2599 elif (arg[1] == '-' and arg[2:] == "graphics"):
2600 graphics_enabled = True
2601 elif (arg[1] == '-' and arg[2:] == "no-graphics"):
2602 graphics_enabled = False
2603 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
2604 # Load game from file
2605 if len(arg[2:].split("=")) == 1:
2606 src_file = sys.stdin
2608 f = arg[2:].split("=")[1]
2609 if f[0:7] == "http://":
2610 src_file = HttpReplay(f)
2612 src_file = FileReplay(f.split(":")[0])
2614 if len(f.split(":")) == 2:
2615 max_moves = int(f.split(":")[1])
2617 elif (arg[1] == '-' and arg[2:].split("=")[0] == "server"):
2618 #debug("Server: " + str(arg[2:]))
2619 if len(arg[2:].split("=")) <= 1:
2622 server_addr = arg[2:].split("=")[1]
2624 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
2626 if len(arg[2:].split("=")) == 1:
2627 log_files.append(LogFile(sys.stdout,""))
2629 f = arg[2:].split("=")[1]
2631 log_files.append(LogFile(sys.stdout, ""))
2633 log_files.append(ShortLog(f[1:]))
2635 log_files.append(LogFile(open(f, "w", 0), f))
2636 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
2638 if len(arg[2:].split("=")) == 1:
2641 turn_delay = float(arg[2:].split("=")[1])
2643 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
2645 if len(arg[2:].split("=")) == 1:
2648 agent_timeout = float(arg[2:].split("=")[1])
2649 elif (arg[1] == '-' and arg[2:].split("=")[0] == "blackout"):
2650 # Screen saver delay
2651 if len(arg[2:].split("=")) == 1:
2654 sleep_timeout = float(arg[2:].split("=")[1])
2656 elif (arg[1] == '-' and arg[2:] == "help"):
2658 os.system("less data/help.txt") # The best help function
2663 #debug("server_addr = " + str(server_addr))
2665 if server_addr != None:
2666 if server_addr == True:
2667 return dedicated_server()
2669 return client(server_addr)
2674 # Construct a GameThread! Make it global! Damn the consequences!
2676 if src_file != None:
2677 # Hack to stop ReplayThread from exiting
2678 #if len(players) == 0:
2679 # players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
2681 # Normally the ReplayThread exits if there are no players
2682 # TODO: Decide which behaviour to use, and fix it
2683 end = (len(players) == 0)
2685 players = [Player("dummy", "white"), Player("dummy", "black")]
2686 elif len(players) != 2:
2687 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2688 if graphics_enabled:
2689 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
2691 game = ReplayThread(players, src_file, end=end, max_moves=max_moves)
2693 board = Board(style)
2694 board.max_moves = max_moves
2695 game = GameThread(board, players)
2701 if graphics_enabled == True:
2703 graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
2705 graphics.sleep_timeout = sleep_timeout
2709 sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
2710 graphics_enabled = False
2712 # If there are no players listed, display a nice pretty menu
2713 if len(players) != 2:
2714 if graphics != None:
2716 server_addr = graphics.SelectServer()
2717 if server_addr != None:
2718 if server_addr == True:
2719 return dedicated_server()
2721 return client(server_addr)
2723 players = graphics.SelectPlayers(players)
2725 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2728 # If there are still no players, quit
2729 if players == None or len(players) != 2:
2730 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
2735 if isinstance(p, NetworkPlayer):
2736 for i in range(len(old)):
2737 if old[i] == p or isinstance(old[i], NetworkPlayer):
2739 players[i] = NetworkPlayer(old[i].colour, p.network, old[i])
2743 if isinstance(p, NetworkPlayer):
2744 p.board = game.board
2745 if not p.network.connected:
2746 if not p.network.server:
2751 # If using windows, select won't work; use horrible TimeoutPlayer hack
2752 if agent_timeout > 0:
2753 if platform.system() == "Windows":
2754 for i in range(len(players)):
2755 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
2756 players[i] = TimeoutPlayer(players[i], agent_timeout)
2760 # InternalAgents get wrapped to an ExternalAgent when there is a timeout
2761 # This is not confusing at all.
2762 for i in range(len(players)):
2763 if isinstance(players[i], InternalAgent):
2764 players[i] = ExternalWrapper(players[i])
2772 log_init(game.board, players)
2775 if graphics != None:
2776 game.start() # This runs in a new thread
2782 error = game.error + graphics.error
2791 if src_file != None and src_file != sys.stdin:
2794 sys.stdout.write(game.final_result + "\n")
2805 # This is how python does a main() function...
2806 if __name__ == "__main__":
2809 retcode = main(sys.argv)
2810 except KeyboardInterrupt:
2811 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
2812 if isinstance(graphics, StoppableThread):
2814 graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
2816 if isinstance(game, StoppableThread):
2821 #except Exception, e:
2822 # sys.stderr.write(sys.argv[0] + " : " + e.message + "\n")
2837 # EOF - created from make on Sat Apr 20 12:19:31 WST 2013