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):
435 if p.current_type != 0:
436 if state == p.current_type:
443 for i in range(len(p.types)):
448 if t == "unknown" or p.types[i][0] == '?':
450 for t2 in self.unrevealed_types[p.colour].keys():
451 total_prob += self.unrevealed_types[p.colour][t2]
452 for t2 in self.unrevealed_types[p.colour].keys():
454 result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
458 # Get all squares that the piece could move into
459 # This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
460 # reject_allied indicates whether squares occupied by allied pieces will be removed
461 # (set to false to check for defense)
462 def possible_moves(self, p, reject_allied = True, state=None):
464 raise Exception("SANITY: No piece")
468 if state != None and state != p.current_type:
469 old_type = p.current_type
470 p.current_type = state
471 result = self.possible_moves(p, reject_allied, state=None)
472 p.current_type = old_type
482 if p.current_type == "unknown":
483 raise Exception("SANITY: Unknown state for piece: "+str(p))
484 # The below commented out code causes things to break badly
489 # result += self.possible_moves(p)
490 #p.current_type = "unknown"
493 if p.current_type == "king":
494 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]]
495 elif p.current_type == "queen":
496 for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
497 result += self.scan(p.x, p.y, d[0], d[1])
498 elif p.current_type == "bishop":
499 for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
500 result += self.scan(p.x, p.y, d[0], d[1])
501 elif p.current_type == "rook":
502 for d in [[-1,0],[1,0],[0,-1],[0,1]]:
503 result += self.scan(p.x, p.y, d[0], d[1])
504 elif p.current_type == "knight":
505 # I would use two lines, but I'm not sure how python likes that
506 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]]
507 elif p.current_type == "pawn":
508 if p.colour == "white":
510 # Pawn can't move forward into occupied square
511 if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
512 result = [[p.x,p.y-1]]
513 for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
514 if not self.on_board(f[0], f[1]):
516 if self.grid[f[0]][f[1]] != None: # Pawn can take diagonally
519 # Slightly embarrassing if the pawn jumps over someone on its first move...
520 if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
521 result.append([p.x, p.y-2])
523 # Vice versa for the black pawn
524 if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
525 result = [[p.x,p.y+1]]
527 for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
528 if not self.on_board(f[0], f[1]):
530 if self.grid[f[0]][f[1]] != None:
531 #sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
534 if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
535 result.append([p.x, p.y+2])
537 #sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")
539 # Remove illegal moves
540 # Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
541 for point in result[:]:
543 if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
544 result.remove(point) # Remove locations outside the board
546 g = self.grid[point[0]][point[1]]
548 if g != None and (g.colour == p.colour and reject_allied == True):
549 result.remove(point) # Remove allied pieces
553 p.possible_moves = result
557 # Scans in a direction until it hits a piece, returns all squares in the line
558 # (includes the final square (which contains a piece), but not the original square)
559 def scan(self, x, y, vx, vy):
567 if not self.on_board(xx, yy):
571 g = self.grid[xx][yy]
577 # Returns "white", "black" or "DRAW" if the game should end
578 def end_condition(self):
579 if self.king["white"] == None:
580 if self.king["black"] == None:
581 return "DRAW" # This shouldn't happen
583 elif self.king["black"] == None:
585 elif len(self.pieces["white"]) == 1 and len(self.pieces["black"]) == 1:
587 elif self.max_moves != None and self.moves > self.max_moves:
592 # I typed the full statement about 30 times before writing this function...
593 def on_board(self, x, y):
594 return (x >= 0 and x < w) and (y >= 0 and y < h)
598 # Pushes a move temporarily
599 def push_move(self, piece, x, y):
600 target = self.grid[x][y]
601 self.move_stack.append([piece, target, piece.x, piece.y, x, y])
602 [piece.x, piece.y] = [x, y]
603 self.grid[x][y] = piece
604 self.grid[piece.x][piece.y] = None
606 for p in self.pieces["white"] + self.pieces["black"]:
607 p.possible_moves = None
611 #print str(self.move_stack)
612 [piece, target, x1, y1, x2, y2] = self.move_stack[len(self.move_stack)-1]
613 self.move_stack = self.move_stack[:-1]
616 self.grid[x1][y1] = piece
620 self.grid[x2][y2] = target
622 for p in self.pieces["white"] + self.pieces["black"]:
623 p.possible_moves = None
631 agent_timeout = -1.0 # Timeout in seconds for AI players to make moves
632 # WARNING: Won't work for windows based operating systems
634 if platform.system() == "Windows":
635 agent_timeout = -1 # Hence this
637 # A player who can't play
639 def __init__(self, name, colour):
643 def update(self, result):
646 def reset_board(self, s):
650 return self.name + "<"+str(self.colour)+">"
652 def base_player(self):
657 def open_fifo(name, mode, timeout=None):
659 return open(name, mode)
662 class Worker(threading.Thread):
664 threading.Thread.__init__(self)
666 self.exception = None
671 self.result = open(name, mode)
681 while time.time() - start < timeout:
682 if w.is_alive() == False:
684 if w.exception != None:
691 #sys.stderr.write("FIFO_TIMEOUT!\n")
692 # Recursive to deal with possible race condition
695 f = open_fifo(name, "w", 1)
697 f = open_fifo(name, "r", 1)
701 #sys.stderr.write("Opened other end!\n")
708 raise Exception("FIFO_TIMEOUT")
711 if w.exception != None:
716 # Player that runs through a fifo
717 class FifoPlayer(Player):
721 def __init__(self, name, colour):
722 Player.__init__(self, name, colour)
723 os.mkfifo(self.name+".in")
724 os.mkfifo(self.name+".out")
730 def update(self, result):
731 sys.stderr.write("update fifo called\n")
733 self.fifo_out = open_fifo(self.name+".out", "w", FifoPlayer.timeout)
735 raise Exception("FIFO_TIMEOUT")
737 self.fifo_out.write(result +"\n")
738 self.fifo_out.close()
742 sys.stderr.write("select fifo called\n")
744 self.fifo_out = open_fifo(self.name+".out", "w", FifoPlayer.timeout)
746 #sys.stderr.write("TIMEOUT\n")
747 raise Exception("FIFO_TIMEOUT")
750 self.fifo_out.write("SELECT?\n")
751 self.fifo_out.close()
752 self.fifo_in = open_fifo(self.name+".in", "r", FifoPlayer.timeout)
753 s = map(int, self.fifo_in.readline().strip(" \r\n").split(" "))
758 sys.stderr.write("get_move fifo called\n")
760 self.fifo_out = open_fifo(self.name+".out", "w", FifoPlayer.timeout)
762 raise Exception("FIFO_TIMEOUT")
764 self.fifo_out.write("MOVE?\n")
765 self.fifo_out.close()
766 self.fifo_in = open_fifo(self.name+".in", "r", FifoPlayer.timeout)
767 s = map(int, self.fifo_in.readline().strip(" \r\n").split(" "))
771 def quit(self, result):
773 self.fifo_out = open_fifo(self.name+".out", "w", FifoPlayer.timeout)
775 os.remove(self.name+".in")
776 os.remove(self.name+".out")
777 #raise Exception("FIFO_TIMEOUT")
780 self.fifo_out.write(result + "\n")
781 self.fifo_out.close()
782 os.remove(self.name+".in")
783 os.remove(self.name+".out")
785 # Player that runs from another process
786 class ExternalAgent(Player):
789 def __init__(self, name, colour):
790 Player.__init__(self, name, colour)
791 self.p = subprocess.Popen(name,bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,universal_newlines=True)
793 self.send_message(colour)
795 def send_message(self, s):
796 if agent_timeout > 0.0:
797 ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
799 ready = [self.p.stdin]
800 if self.p.stdin in ready:
801 #sys.stderr.write("Writing \'" + s + "\' to " + str(self.p) + "\n")
803 self.p.stdin.write(s + "\n")
805 raise Exception("UNRESPONSIVE")
807 raise Exception("TIMEOUT")
809 def get_response(self):
810 if agent_timeout > 0.0:
811 ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
813 ready = [self.p.stdout]
814 if self.p.stdout in ready:
815 #sys.stderr.write("Reading from " + str(self.p) + " 's stdout...\n")
817 result = self.p.stdout.readline().strip(" \t\r\n")
818 #sys.stderr.write("Read \'" + result + "\' from " + str(self.p) + "\n")
820 except: # Exception, e:
821 raise Exception("UNRESPONSIVE")
823 raise Exception("TIMEOUT")
827 self.send_message("SELECTION?")
828 line = self.get_response()
831 m = re.match("\s*(\d+)\s+(\d+)\s*", line)
832 result = map(int, [m.group(1), m.group(2)])
834 raise Exception("GIBBERISH \"" + str(line) + "\"")
837 def update(self, result):
838 #print "Update " + str(result) + " called for AgentPlayer"
839 self.send_message(result)
844 self.send_message("MOVE?")
845 line = self.get_response()
848 m = re.match("\s*(\d+)\s+(\d+)\s*", line)
849 result = map(int, [m.group(1), m.group(2)])
852 raise Exception("GIBBERISH \"" + str(line) + "\"")
855 def reset_board(self, s):
856 self.send_message("BOARD")
857 for line in s.split("\n"):
858 self.send_message(line.strip(" \r\n"))
859 self.send_message("END BOARD")
861 def quit(self, final_result):
863 self.send_message("QUIT " + final_result)
867 # So you want to be a player here?
868 class HumanPlayer(Player):
869 def __init__(self, name, colour):
870 Player.__init__(self, name, colour)
872 # Select your preferred account
874 if isinstance(graphics, GraphicsThread):
875 # Basically, we let the graphics thread do some shit and then return that information to the game thread
876 graphics.cond.acquire()
877 # We wait for the graphics thread to select a piece
878 while graphics.stopped() == False and graphics.state["select"] == None:
879 graphics.cond.wait() # The difference between humans and machines is that humans sleep
880 select = graphics.state["select"]
883 graphics.cond.release()
884 if graphics.stopped():
886 return [select.x, select.y]
888 # Since I don't display the board in this case, I'm not sure why I filled it in...
890 sys.stdout.write("SELECTION?\n")
892 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
894 sys.stderr.write("ILLEGAL GIBBERISH\n")
896 # It's your move captain
898 if isinstance(graphics, GraphicsThread):
899 graphics.cond.acquire()
900 while graphics.stopped() == False and graphics.state["dest"] == None:
902 graphics.cond.release()
904 return graphics.state["dest"]
908 sys.stdout.write("MOVE?\n")
910 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
912 sys.stderr.write("ILLEGAL GIBBERISH\n")
915 # Are you sure you want to quit?
916 def quit(self, final_result):
918 sys.stdout.write("QUIT " + final_result + "\n")
920 # Completely useless function
921 def update(self, result):
922 if isinstance(graphics, GraphicsThread):
925 sys.stdout.write(result + "\n")
929 # Default internal player (makes random moves)
930 class InternalAgent(Player):
931 def __init__(self, name, colour):
932 Player.__init__(self, name, colour)
935 self.board = Board(style = "agent")
939 def update(self, result):
941 self.board.update(result)
945 def reset_board(self, s):
946 self.board.reset_board(s)
948 def quit(self, final_result):
951 class AgentRandom(InternalAgent):
952 def __init__(self, name, colour):
953 InternalAgent.__init__(self, name, colour)
957 self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
959 # Check that the piece has some possibility to move
960 tmp = self.choice.current_type
961 if tmp == "unknown": # For unknown pieces, try both types
962 for t in self.choice.types:
965 self.choice.current_type = t
966 all_moves += self.board.possible_moves(self.choice)
968 all_moves = self.board.possible_moves(self.choice)
969 self.choice.current_type = tmp
970 if len(all_moves) > 0:
972 return [self.choice.x, self.choice.y]
975 moves = self.board.possible_moves(self.choice)
976 move = moves[random.randint(0, len(moves)-1)]
980 # Terrible, terrible hacks
982 def run_agent(agent):
983 #sys.stderr.write(sys.argv[0] + " : Running agent " + str(agent) + "\n")
985 line = sys.stdin.readline().strip(" \r\n")
986 if line == "SELECTION?":
987 #sys.stderr.write(sys.argv[0] + " : Make selection\n")
988 [x,y] = agent.select() # Gets your agent's selection
989 #sys.stderr.write(sys.argv[0] + " : Selection was " + str(agent.choice) + "\n")
990 sys.stdout.write(str(x) + " " + str(y) + "\n")
991 elif line == "MOVE?":
992 #sys.stderr.write(sys.argv[0] + " : Make move\n")
993 [x,y] = agent.get_move() # Gets your agent's move
994 sys.stdout.write(str(x) + " " + str(y) + "\n")
995 elif line.split(" ")[0] == "QUIT":
996 #sys.stderr.write(sys.argv[0] + " : Quitting\n")
997 agent.quit(" ".join(line.split(" ")[1:])) # Quits the game
999 elif line.split(" ")[0] == "BOARD":
1001 line = sys.stdin.readline().strip(" \r\n")
1002 while line != "END BOARD":
1004 line = sys.stdin.readline().strip(" \r\n")
1005 agent.board.reset_board(s)
1008 agent.update(line) # Updates agent.board
1014 class ExternalWrapper(ExternalAgent):
1015 def __init__(self, agent):
1016 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))\""
1018 ExternalAgent.__init__(self, run, agent.colour)
1022 # --- player.py --- #
1026 class AgentBishop(AgentRandom): # Inherits from AgentRandom (in qchess)
1027 def __init__(self, name, colour,value={"pawn" : 1, "bishop" : 3, "knight" : 3, "rook" : 5, "queen" : 9, "king" : 100, "unknown" : 2}):
1028 InternalAgent.__init__(self, name, colour)
1030 self.aggression = 2.0 # Multiplier for scoring due to aggressive actions
1031 self.defence = 1.0 # Multiplier for scoring due to defensive actions
1033 self.depth = 0 # Current depth
1034 self.max_depth = 2 # Recurse this many times (for some reason, makes more mistakes when this is increased???)
1035 self.recurse_for = -1 # Recurse for the best few moves each times (less than 0 = all moves)
1037 for p in self.board.pieces["white"] + self.board.pieces["black"]:
1039 p.selected_moves = None
1043 def get_value(self, piece):
1046 return float(self.value[piece.types[0]] + self.value[piece.types[1]]) / 2.0
1048 # Score possible moves for the piece
1050 def prioritise_moves(self, piece):
1052 #sys.stderr.write(sys.argv[0] + " : " + str(self) + " prioritise called for " + str(piece) + "\n")
1056 grid = self.board.probability_grid(piece)
1057 #sys.stderr.write("\t Probability grid " + str(grid) + "\n")
1061 if grid[x][y] < 0.3: # Throw out moves with < 30% probability
1062 #sys.stderr.write("\tReject " + str(x) + "," + str(y) + " (" + str(grid[x][y]) + ")\n")
1065 target = self.board.grid[x][y]
1070 # Get total probability that the move is protected
1071 self.board.push_move(piece, x, y)
1075 defenders = self.board.coverage(x, y, piece.colour, reject_allied = False)
1077 for d in defenders.keys():
1078 d_prob += defenders[d]
1079 if len(defenders.keys()) > 0:
1080 d_prob /= float(len(defenders.keys()))
1085 # Get total probability that the move is threatened
1086 attackers = self.board.coverage(x, y, opponent(piece.colour), reject_allied = False)
1088 for a in attackers.keys():
1089 a_prob += attackers[a]
1090 if len(attackers.keys()) > 0:
1091 a_prob /= float(len(attackers.keys()))
1096 self.board.pop_move()
1101 value = self.aggression * (1.0 + d_prob) * self.get_value(target) - self.defence * (1.0 - d_prob) * a_prob * self.get_value(piece)
1103 # Adjust score based on movement of piece out of danger
1104 attackers = self.board.coverage(piece.x, piece.y, opponent(piece.colour))
1106 for a in attackers.keys():
1107 s_prob += attackers[a]
1108 if len(attackers.keys()) > 0:
1109 s_prob /= float(len(attackers.keys()))
1113 value += self.defence * s_prob * self.get_value(piece)
1115 # Adjust score based on probability that the move is actually possible
1116 moves.append([[x, y], grid[x][y] * value])
1118 moves.sort(key = lambda e : e[1], reverse = True)
1119 #sys.stderr.write(sys.argv[0] + ": Moves for " + str(piece) + " are " + str(moves) + "\n")
1121 piece.last_moves = moves
1122 piece.selected_moves = None
1129 def select_best(self, colour):
1133 for p in self.board.pieces[colour]:
1134 self.choice = p # Temporarily pick that piece
1135 m = self.prioritise_moves(p)
1137 all_moves.update({p : m[0]})
1139 if len(all_moves.items()) <= 0:
1143 opts = all_moves.items()
1144 opts.sort(key = lambda e : e[1][1], reverse = True)
1146 if self.depth >= self.max_depth:
1148 return list(opts[0])
1150 if self.recurse_for >= 0:
1151 opts = opts[0:self.recurse_for]
1152 #sys.stderr.write(sys.argv[0] + " : Before recurse, options are " + str(opts) + "\n")
1154 # Take the best few moves, and recurse
1155 for choice in opts[0:self.recurse_for]:
1156 [xx,yy] = [choice[0].x, choice[0].y] # Remember position
1157 [nx,ny] = choice[1][0] # Target
1158 [choice[0].x, choice[0].y] = [nx, ny] # Set position
1159 target = self.board.grid[nx][ny] # Remember piece in spot
1160 self.board.grid[xx][yy] = None # Remove piece
1161 self.board.grid[nx][ny] = choice[0] # Replace with moving piece
1164 best_enemy_move = self.select_best(opponent(choice[0].colour))
1165 choice[1][1] -= best_enemy_move[1][1] / float(self.depth + 1.0)
1167 [choice[0].x, choice[0].y] = [xx, yy] # Restore position
1168 self.board.grid[nx][ny] = target # Restore taken piece
1169 self.board.grid[xx][yy] = choice[0] # Restore moved piece
1173 opts.sort(key = lambda e : e[1][1], reverse = True)
1174 #sys.stderr.write(sys.argv[0] + " : After recurse, options are " + str(opts) + "\n")
1177 return list(opts[0])
1181 # Returns [x,y] of selected piece
1183 #sys.stderr.write("Getting choice...")
1184 self.choice = self.select_best(self.colour)[0]
1186 #sys.stderr.write(" Done " + str(self.choice)+"\n")
1187 return [self.choice.x, self.choice.y]
1189 # Returns [x,y] of square to move selected piece into
1191 #sys.stderr.write("Choice is " + str(self.choice) + "\n")
1192 self.choice.selected_moves = self.choice.last_moves
1193 moves = self.prioritise_moves(self.choice)
1197 return AgentRandom.get_move(self)
1199 # --- agent_bishop.py --- #
1200 import multiprocessing
1202 # Hacky alternative to using select for timing out players
1204 # WARNING: Do not wrap around HumanPlayer or things breakify
1205 # WARNING: Do not use in general or things breakify
1207 class Sleeper(multiprocessing.Process):
1208 def __init__(self, timeout):
1209 multiprocessing.Process.__init__(self)
1210 self.timeout = timeout
1213 time.sleep(self.timeout)
1216 class Worker(multiprocessing.Process):
1217 def __init__(self, function, args, q):
1218 multiprocessing.Process.__init__(self)
1219 self.function = function
1224 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args)
1226 self.q.put(self.function(*self.args))
1232 def TimeoutFunction(function, args, timeout):
1233 q = multiprocessing.Queue()
1234 w = Worker(function, args, q)
1235 s = Sleeper(timeout)
1238 while True: # Busy loop of crappyness
1239 if not w.is_alive():
1243 #print "TimeoutFunction gets " + str(result)
1245 elif not s.is_alive():
1248 raise Exception("TIMEOUT")
1253 # A player that wraps another player and times out its moves
1255 # A (crappy) alternative to the use of select()
1256 class TimeoutPlayer(Player):
1257 def __init__(self, base_player, timeout):
1258 Player.__init__(self, base_player.name, base_player.colour)
1259 self.base_player = base_player
1260 self.timeout = timeout
1263 return TimeoutFunction(self.base_player.select, [], self.timeout)
1267 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
1269 def update(self, result):
1270 return TimeoutFunction(self.base_player.update, [result], self.timeout)
1272 def quit(self, final_result):
1273 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
1274 # --- timeout_player.py --- #
1278 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
1279 network_timeout_delay = 1.0 # Maximum time between two characters being received
1281 class NetworkPlayer(Player):
1282 def __init__(self, colour, network, player):
1283 Player.__init__(self, "@network:"+str(network.address), colour)
1284 self.player = player
1285 self.network = network
1288 return "NetworkPlayer<"+str(self.colour)+","+str(self.player)+">"
1291 #debug(str(self) + " select called")
1292 if self.player != None:
1293 s = self.player.select()
1294 self.send_message(str(s[0]) + " " + str(s[1]))
1296 s = map(int, self.get_response().split(" "))
1297 for p in game.players:
1298 if p != self and isinstance(p, NetworkPlayer) and p.player == None:
1299 p.network.send_message(str(s[0]) + " " + str(s[1]))
1301 game.final_result = "network terminate"
1305 def send_message(self, message):
1306 #debug(str(self) + " send_message(\""+str(message)+"\") called")
1307 self.network.send_message(message)
1309 def get_response(self):
1310 #debug(str(self) + " get_response() called")
1311 s = self.network.get_response()
1312 #debug(str(self) + " get_response() returns \""+str(s)+"\"")
1317 #debug(str(self) + " get_move called")
1318 if self.player != None:
1319 s = self.player.get_move()
1320 self.send_message(str(s[0]) + " " + str(s[1]))
1322 s = map(int, self.get_response().split(" "))
1323 for p in game.players:
1324 if p != self and isinstance(p, NetworkPlayer) and p.player == None:
1325 p.network.send_message(str(s[0]) + " " + str(s[1]))
1328 game.final_result = "network terminate"
1332 def update(self, result):
1333 #debug(str(self) + " update(\""+str(result)+"\") called")
1334 if self.network.server == True:
1335 if self.player == None:
1336 self.send_message(result)
1337 elif self.player != None:
1338 result = self.get_response()
1339 if result == "-1 -1":
1340 game.final_result = "network terminate"
1343 self.board.update(result, deselect=False)
1347 if self.player != None:
1348 result = self.player.update(result)
1354 def base_player(self):
1355 if self.player == None:
1358 return self.player.base_player()
1360 def quit(self, result):
1362 self.send_message("-1 -1")
1367 def __init__(self, address = (None,4562)):
1368 self.socket = socket.socket()
1369 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1370 #self.socket.setblocking(0)
1371 self.address = address
1372 self.server = (address[0] == None)
1375 self.connected = False
1378 #debug(str(self) + "Tries to connect")
1379 self.connected = True
1380 if self.address[0] == None:
1381 self.host = "0.0.0.0" #socket.gethostname() # Breaks things???
1382 self.socket.bind((self.host, self.address[1]))
1383 self.socket.listen(5)
1385 self.src, self.actual_address = self.socket.accept()
1387 self.src.send("ok\n")
1388 s = self.get_response()
1394 self.__init__(colour, (self.address[0], int(s)), baseplayer)
1399 self.socket.connect(self.address)
1400 self.src = self.socket
1401 self.src.send("ok\n")
1402 s = self.get_response()
1408 self.__init__(colour, (self.address[0], int(s)), baseplayer)
1414 return "@network:"+str(self.address)
1416 def get_response(self):
1418 # Timeout the start of the message (first character)
1419 if network_timeout_start > 0.0:
1420 ready = select.select([self.src], [], [], network_timeout_start)[0]
1423 if self.src in ready:
1424 s = self.src.recv(1)
1426 raise Exception("UNRESPONSIVE")
1429 while s[len(s)-1] != '\n':
1430 # Timeout on each character in the message
1431 if network_timeout_delay > 0.0:
1432 ready = select.select([self.src], [], [], network_timeout_delay)[0]
1435 if self.src in ready:
1436 s += self.src.recv(1)
1438 raise Exception("UNRESPONSIVE")
1441 return s.strip(" \r\n")
1443 def send_message(self,s):
1444 if network_timeout_start > 0.0:
1445 ready = select.select([], [self.src], [], network_timeout_start)[1]
1449 if self.src in ready:
1450 self.src.send(s + "\n")
1452 raise Exception("UNRESPONSIVE")
1459 # --- network.py --- #
1462 # A thread that can be stopped!
1463 # Except it can only be stopped if it checks self.stopped() periodically
1464 # So it can sort of be stopped
1465 class StoppableThread(threading.Thread):
1467 threading.Thread.__init__(self)
1468 self._stop = threading.Event()
1474 return self._stop.isSet()# --- thread_util.py --- #
1480 def __init__(self, log, name):
1484 self.log.write("# Log starts " + str(datetime.datetime.now()) + "\n")
1487 now = datetime.datetime.now()
1488 self.log.write(str(now) + " : " + s + "\n")
1489 self.logged.append((now, s))
1491 def setup(self, board, players):
1494 self.log.write("# " + str(p.colour) + " : " + str(p.name) + "\n")
1496 self.log.write("# Initial board\n")
1497 for x in range(0, w):
1498 for y in range(0, h):
1499 if board.grid[x][y] != None:
1500 self.log.write(str(board.grid[x][y]) + "\n")
1502 self.log.write("# Start game\n")
1505 self.log.write("# EOF\n")
1506 if self.log != sys.stdout:
1509 class ShortLog(LogFile):
1510 def __init__(self, file_name):
1512 self.log = sys.stdout
1514 self.log = open(file_name, "w", 0)
1515 LogFile.__init__(self, self.log, "@"+file_name)
1516 self.file_name = file_name
1520 now = datetime.datetime.now()
1521 self.logged.append((now, s))
1524 if self.log != sys.stdout:
1526 self.log = open(self.file_name, "w", 0)
1527 self.log.write("# Short log updated " + str(datetime.datetime.now()) + "\n")
1528 LogFile.setup(self, game.board, game.players)
1530 elif self.phase == 1:
1531 for message in self.logged[len(self.logged)-2:]:
1532 self.log.write(str(message[0]) + " : " + message[1] + "\n")
1534 self.phase = (self.phase + 1) % 2
1538 ending = self.logged[len(self.logged)-1]
1539 self.log.write(str(ending[0]) + " : " + ending[1] + "\n")
1540 self.log.write("# EOF\n")
1541 if self.log != sys.stdout:
1545 class HeadRequest(urllib2.Request):
1546 def get_method(self):
1549 class HttpGetter(StoppableThread):
1550 def __init__(self, address):
1551 StoppableThread.__init__(self)
1552 self.address = address
1553 self.log = urllib2.urlopen(address)
1555 self.lock = threading.RLock() #lock for access of self.state
1556 self.cond = threading.Condition() # conditional
1559 while not self.stopped():
1560 line = self.log.readline()
1562 date_mod = datetime.datetime.strptime(self.log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1565 next_log = urllib2.urlopen(HeadRequest(self.address))
1566 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1567 while date_new <= date_mod and not self.stopped():
1568 next_log = urllib2.urlopen(HeadRequest(self.address))
1569 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1573 self.log = urllib2.urlopen(self.address)
1574 line = self.log.readline()
1577 self.lines.append(line)
1578 self.cond.notifyAll()
1581 #sys.stderr.write(" HttpGetter got \'" + str(line) + "\'\n")
1590 def __init__(self, address):
1591 self.getter = HttpGetter(address)
1595 self.getter.cond.acquire()
1596 while len(self.getter.lines) == 0:
1597 self.getter.cond.wait()
1599 result = self.getter.lines[0]
1600 self.getter.lines = self.getter.lines[1:]
1601 self.getter.cond.release()
1610 def __init__(self, filename):
1611 self.f = open(filename, "r", 0)
1612 self.filename = filename
1613 self.mod = os.path.getmtime(filename)
1617 line = self.f.readline()
1620 mod2 = os.path.getmtime(self.filename)
1622 #sys.stderr.write("File changed!\n")
1625 self.f = open(self.filename, "r", 0)
1627 new_line = self.f.readline()
1629 if " ".join(new_line.split(" ")[0:3]) != "# Short log":
1630 for i in range(self.count):
1631 new_line = self.f.readline()
1632 #sys.stderr.write("Read back " + str(i) + ": " + str(new_line) + "\n")
1633 new_line = self.f.readline()
1651 sys.stderr.write("# DEBUG: " + s + "\n")
1654 def log_init(board, players):
1656 l.setup(board, players)
1664 # A thread that runs the game
1665 class GameThread(StoppableThread):
1666 def __init__(self, board, players, server = True):
1667 StoppableThread.__init__(self)
1669 self.players = players
1670 self.state = {"turn" : None} # The game state
1671 self.error = 0 # Whether the thread exits with an error
1672 self.lock = threading.RLock() #lock for access of self.state
1673 self.cond = threading.Condition() # conditional for some reason, I forgot
1674 self.final_result = ""
1675 self.server = server
1682 # Run the game (run in new thread with start(), run in current thread with run())
1685 while not self.stopped():
1687 for p in self.players:
1689 self.state["turn"] = p.base_player()
1692 [x,y] = p.select() # Player selects a square
1694 #debug("Quitting in select")
1697 if isinstance(p, NetworkPlayer):
1698 if p.network.server == True:
1699 result = self.board.select(x, y, colour = p.colour)
1704 result = self.board.select(x, y, colour = p.colour)
1706 result = p.update(result)
1709 for p2 in self.players:
1712 p2.update(result) # Inform players of what happened
1722 target = self.board.grid[x][y]
1723 if isinstance(graphics, GraphicsThread):
1725 graphics.state["moves"] = self.board.possible_moves(target)
1726 graphics.state["select"] = target
1728 time.sleep(turn_delay)
1731 if len(self.board.possible_moves(target)) == 0:
1732 #print "Piece cannot move"
1734 if isinstance(graphics, GraphicsThread):
1736 graphics.state["moves"] = None
1737 graphics.state["select"] = None
1738 graphics.state["dest"] = None
1742 [x2,y2] = p.get_move() # Player selects a destination
1747 #debug("Quitting in get_move")
1750 if isinstance(p, NetworkPlayer):
1751 if p.network.server == True:
1752 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1753 self.board.update_move(x, y, x2, y2)
1758 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1759 self.board.update_move(x, y, x2, y2)
1761 result = p.update(result)
1764 for p2 in self.players:
1767 p2.update(result) # Inform players of what happened
1781 if isinstance(graphics, GraphicsThread):
1783 graphics.state["moves"] = [[x2,y2]]
1785 time.sleep(turn_delay)
1787 if isinstance(graphics, GraphicsThread):
1789 graphics.state["select"] = None
1790 graphics.state["dest"] = None
1791 graphics.state["moves"] = None
1794 end = self.board.end_condition()
1798 self.final_result = self.state["turn"].colour + " " + end
1800 self.final_result = end
1808 sys.stderr.write("qchess.py exception: "+result + "\n")
1813 self.final_result = self.state["turn"].colour + " " + e.message
1818 for p2 in self.players:
1819 p2.quit(self.final_result)
1821 log(self.final_result)
1823 if isinstance(graphics, GraphicsThread):
1827 # A thread that replays a log file
1828 class ReplayThread(GameThread):
1829 def __init__(self, players, src, end=False,max_moves=None):
1830 self.board = Board(style="empty")
1831 self.board.max_moves = max_moves
1832 GameThread.__init__(self, self.board, players)
1836 self.reset_board(self.src.readline())
1838 def reset_board(self, line):
1841 while line != "# Start game" and line != "# EOF":
1844 line = self.src.readline().strip(" \r\n")
1848 line = self.src.readline().strip(" \r\n")
1851 self_str += line + "\n"
1853 if self.players[0].name == "dummy" and self.players[1].name == "dummy":
1854 line = self.src.readline().strip(" \r\n")
1857 tokens = line.split(" ")
1858 types = map(lambda e : e.strip("[] ,'"), tokens[2:4])
1859 for i in range(len(types)):
1860 if types[i][0] == "?":
1861 types[i] = "unknown"
1863 agent_str += tokens[0] + " " + tokens[1] + " " + str(types) + " ".join(tokens[4:]) + "\n"
1864 line = self.src.readline().strip(" \r\n")
1866 for p in self.players:
1867 p.reset_board(agent_str)
1870 self.board.reset_board(self_str)
1876 line = self.src.readline().strip(" \r\n")
1877 while line != "# EOF":
1889 line = self.src.readline().strip(" \r\n")
1892 tokens = line.split(" ")
1893 if tokens[0] == "white" or tokens[0] == "black":
1894 self.reset_board(line)
1896 line = self.src.readline().strip(" \r\n")
1899 move = line.split(":")
1900 move = move[len(move)-1].strip(" \r\n")
1901 tokens = move.split(" ")
1905 [x,y] = map(int, tokens[0:2])
1913 target = self.board.grid[x][y]
1915 if target.colour == "white":
1916 self.state["turn"] = self.players[0]
1918 self.state["turn"] = self.players[1]
1920 move_piece = (tokens[2] == "->")
1922 [x2,y2] = map(int, tokens[len(tokens)-2:])
1924 if isinstance(graphics, GraphicsThread):
1926 graphics.state["select"] = target
1929 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
1930 if isinstance(graphics, GraphicsThread):
1932 if target.current_type != "unknown":
1933 graphics.state["moves"] = self.board.possible_moves(target)
1935 graphics.state["moves"] = None
1936 time.sleep(turn_delay)
1938 self.board.update_move(x, y, x2, y2)
1939 if isinstance(graphics, GraphicsThread):
1941 graphics.state["moves"] = [[x2,y2]]
1942 time.sleep(turn_delay)
1944 graphics.state["select"] = None
1945 graphics.state["moves"] = None
1946 graphics.state["dest"] = None
1952 for p in self.players:
1956 line = self.src.readline().strip(" \r\n")
1959 end = self.board.end_condition()
1961 self.final_result = end
1979 if self.end and isinstance(graphics, GraphicsThread):
1981 pass # Let the user stop the display
1982 elif not self.end and self.board.end_condition() == None:
1984 # Work out the last move
1986 t = last_line.split(" ")
1987 if t[len(t)-2] == "black":
1988 self.players.reverse()
1989 elif t[len(t)-2] == "white":
1991 elif self.state["turn"] != None and self.state["turn"].colour == "white":
1992 self.players.reverse()
1995 game = GameThread(self.board, self.players)
2002 def opponent(colour):
2003 if colour == "white":
2014 # Dictionary that stores the unicode character representations of the different pieces
2015 # Chess was clearly the reason why unicode was invented
2016 # For some reason none of the pygame chess implementations I found used them!
2017 piece_char = {"white" : {"king" : u'\u2654',
2018 "queen" : u'\u2655',
2020 "bishop" : u'\u2657',
2021 "knight" : u'\u2658',
2024 "black" : {"king" : u'\u265A',
2025 "queen" : u'\u265B',
2027 "bishop" : u'\u265D',
2028 "knight" : u'\u265E',
2032 images = {"white" : {}, "black" : {}}
2033 small_images = {"white" : {}, "black" : {}}
2035 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
2037 # Get the font sizes
2038 l_size = 5*(grid_sz[0] / 8)
2039 s_size = 3*(grid_sz[0] / 8)
2041 for c in piece_char.keys():
2044 for p in piece_char[c].keys():
2045 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
2046 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})
2048 for p in piece_char[c].keys():
2049 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
2050 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
2051 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
2052 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
2055 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
2056 if not os.path.exists(image_dir):
2057 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
2058 for c in piece_char.keys():
2059 for p in piece_char[c].keys():
2060 images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
2061 small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
2062 # --- images.py --- #
2063 graphics_enabled = True
2067 os.environ["SDL_VIDEO_ALLOW_SCREENSAVER"] = "1"
2069 graphics_enabled = False
2075 # A thread to make things pretty
2076 class GraphicsThread(StoppableThread):
2077 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
2078 StoppableThread.__init__(self)
2082 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
2083 pygame.display.set_caption(title)
2085 #print "Initialised properly"
2087 self.grid_sz = grid_sz[:]
2088 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
2090 self.lock = threading.RLock()
2091 self.cond = threading.Condition()
2092 self.sleep_timeout = None
2093 self.last_event = time.time()
2094 self.blackout = False
2097 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
2100 create_images(grid_sz)
2103 for c in images.keys():
2104 for p in images[c].keys():
2105 images[c][p] = images[c][p].convert(self.window)
2106 small_images[c][p] = small_images[c][p].convert(self.window)
2113 # On the run from the world
2116 while not self.stopped():
2118 if self.sleep_timeout == None or (time.time() - self.last_event) < self.sleep_timeout:
2120 #print "Display grid"
2121 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
2123 #print "Display overlay"
2126 #print "Display pieces"
2127 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
2128 self.blackout = False
2130 elif pygame.mouse.get_focused() and not self.blackout:
2131 os.system("xset dpms force off")
2132 self.blackout = True
2133 self.window.fill((0,0,0))
2135 pygame.display.flip()
2137 for event in pygame.event.get():
2138 self.last_event = time.time()
2139 if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_q):
2140 if isinstance(game, GameThread):
2142 game.final_result = ""
2143 if game.state["turn"] != None:
2144 game.final_result = game.state["turn"].colour + " "
2145 game.final_result += "terminated"
2149 elif event.type == pygame.MOUSEBUTTONDOWN:
2150 self.mouse_down(event)
2152 elif event.type == pygame.MOUSEBUTTONUP:
2153 self.mouse_up(event)
2162 self.message("Game ends, result \""+str(game.final_result) + "\"")
2165 # Wake up anyone who is sleeping
2170 pygame.quit() # Time to say goodbye
2172 # Mouse release event handler
2173 def mouse_up(self, event):
2174 if event.button == 3:
2176 self.state["overlay"] = None
2177 elif event.button == 2:
2179 self.state["coverage"] = None
2181 # Mouse click event handler
2182 def mouse_down(self, event):
2183 if event.button == 1:
2184 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
2185 if isinstance(game, GameThread):
2187 p = game.state["turn"]
2192 if isinstance(p, HumanPlayer):
2194 s = self.board.grid[m[0]][m[1]]
2195 select = self.state["select"]
2197 if s != None and s.colour != p.colour:
2198 self.message("Wrong colour") # Look at all this user friendliness!
2201 # Notify human player of move
2204 self.state["select"] = s
2205 self.state["dest"] = None
2214 if self.state["moves"] == None:
2217 if not m in self.state["moves"]:
2218 self.message("Illegal Move") # I still think last year's mouse interface was adequate
2223 if self.state["dest"] == None:
2225 self.state["dest"] = m
2226 self.state["select"] = None
2227 self.state["moves"] = None
2230 elif event.button == 3:
2231 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2232 if isinstance(game, GameThread):
2234 p = game.state["turn"]
2239 if isinstance(p, HumanPlayer):
2241 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
2243 elif event.button == 2:
2244 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2245 if isinstance(game, GameThread):
2247 p = game.state["turn"]
2252 if isinstance(p, HumanPlayer):
2254 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
2259 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
2260 # Draw square over the selected piece
2262 select = self.state["select"]
2264 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
2265 square_img.fill(pygame.Color(0,255,0,64))
2266 self.window.blit(square_img, mp)
2267 # If a piece is selected, draw all reachable squares
2268 # (This quality user interface has been patented)
2270 m = self.state["moves"]
2272 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
2274 mp = [self.grid_sz[i] * move[i] for i in range(2)]
2275 self.window.blit(square_img, mp)
2276 # If a piece is overlayed, show all squares that it has a probability to reach
2278 m = self.state["overlay"]
2283 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
2284 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
2285 self.window.blit(square_img, mp)
2286 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2287 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
2288 self.window.blit(text, mp)
2290 # If a square is selected, highlight all pieces that have a probability to reach it
2292 m = self.state["coverage"]
2295 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
2296 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
2297 self.window.blit(square_img, mp)
2298 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2299 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
2300 self.window.blit(text, mp)
2301 # Draw a square where the mouse is
2302 # This also serves to indicate who's turn it is
2304 if isinstance(game, GameThread):
2306 turn = game.state["turn"]
2310 if isinstance(turn, HumanPlayer):
2311 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
2312 square_img.fill(pygame.Color(0,0,255,128))
2313 if turn.colour == "white":
2314 c = pygame.Color(255,255,255)
2316 c = pygame.Color(0,0,0)
2317 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
2318 self.window.blit(square_img, mp)
2320 # Message in a bottle
2321 def message(self, string, pos = None, colour = None, font_size = 20):
2322 #print "Drawing message..."
2323 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2325 colour = pygame.Color(0,0,0)
2327 text = font.render(string, 1, colour)
2330 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
2331 s.fill(pygame.Color(128,128,128))
2333 tmp = self.window.get_size()
2336 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
2338 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
2341 rect = (pos[0], pos[1], text.get_width(), text.get_height())
2343 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
2344 self.window.blit(s, pos)
2345 self.window.blit(text, pos)
2347 pygame.display.flip()
2349 def getstr(self, prompt = None):
2350 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
2351 s.blit(self.window, (0,0))
2357 self.message(prompt)
2358 self.message(result, pos = (0, 1))
2361 for event in pygame.event.get():
2362 if event.type == pygame.QUIT:
2364 if event.type == pygame.KEYDOWN:
2365 if event.key == pygame.K_BACKSPACE:
2366 result = result[0:len(result)-1]
2367 self.window.blit(s, (0,0)) # Revert the display
2372 if event.unicode == '\r':
2375 result += str(event.unicode)
2380 # Function to pick a button
2381 def SelectButton(self, choices, prompt = None, font_size=20):
2383 #print "Select button called!"
2384 self.board.display_grid(self.window, self.grid_sz)
2386 self.message(prompt)
2387 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2389 sz = self.window.get_size()
2392 for i in range(len(choices)):
2395 text = font.render(c, 1, pygame.Color(0,0,0))
2396 p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
2397 targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
2400 mp =pygame.mouse.get_pos()
2401 for i in range(len(choices)):
2403 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
2404 font_colour = pygame.Color(255,0,0)
2405 box_colour = pygame.Color(0,0,255,128)
2407 font_colour = pygame.Color(0,0,0)
2408 box_colour = pygame.Color(128,128,128)
2410 text = font.render(c, 1, font_colour)
2411 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
2413 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
2414 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
2415 self.window.blit(s, targets[i][0:2])
2418 pygame.display.flip()
2420 for event in pygame.event.get():
2421 if event.type == pygame.QUIT:
2423 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
2424 for i in range(len(targets)):
2426 if event.pos[0] > t[0] and event.pos[0] < t[2]:
2427 if event.pos[1] > t[1] and event.pos[1] < t[3]:
2429 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
2432 # Function to choose between dedicated server or normal play
2433 def SelectServer(self):
2435 choice = self.SelectButton(["Normal", "Join Eigenserver"],prompt="Game type?")
2438 choice = self.SelectButton(["progcomp.ucc", "other"], prompt="Address?")
2440 return "progcomp.ucc.asn.au"
2442 return self.getstr(prompt = "Enter address:")
2444 # Function to pick players in a nice GUI way
2445 def SelectPlayers(self, players = []):
2448 #print "SelectPlayers called"
2450 missing = ["white", "black"]
2452 missing.remove(p.colour)
2454 for colour in missing:
2457 choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
2459 players.append(HumanPlayer("human", colour))
2462 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2463 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2464 internal_agents.remove(('InternalAgent', InternalAgent))
2465 if len(internal_agents) > 0:
2466 choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
2471 agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
2472 players.append(agent[1](agent[0], colour))
2476 from tkFileDialog import askopenfilename
2477 root = Tkinter.Tk() # Need a root to make Tkinter behave
2478 root.withdraw() # Some sort of magic incantation
2479 path = askopenfilename(parent=root, initialdir="../agents",title=
2482 return self.SelectPlayers()
2483 players.append(make_player(path, colour))
2488 self.board.display_grid(self.window, self.grid_sz)
2489 pygame.display.flip()
2490 path = self.getstr(prompt = "Enter path:")
2495 return self.SelectPlayers()
2498 p = make_player(path, colour)
2500 self.board.display_grid(self.window, self.grid_sz)
2501 pygame.display.flip()
2502 self.message("Invalid path!")
2508 while address == "":
2509 self.board.display_grid(self.window, self.grid_sz)
2511 address = self.getstr(prompt = "Address? (leave blank for server)")
2518 map(int, address.split("."))
2520 self.board.display_grid(self.window, self.grid_sz)
2521 self.message("Invalid IPv4 address!")
2524 players.append(NetworkReceiver(colour, address))
2527 #print str(self) + ".SelectPlayers returns " + str(players)
2532 # --- graphics.py --- #
2533 def dedicated_server():
2542 log("Getting clients...")
2544 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2545 s.bind(("0.0.0.0", 4562))
2549 log("Got white player")
2551 args = ["python", "qchess.py", "--no-graphics", "@network::"+str(4600+2*len(games)), "@network::"+str(4600+2*len(games))]
2552 if len(log_files) != 0:
2555 args.append("--log")
2557 args.append("--log="+str(l.name)+"_"+str(gameID))
2559 g = subprocess.Popen(args, stdout=subprocess.PIPE)
2563 ss[0].send("white " + str(4600 + 2*(len(games)-1)))
2564 ss[0].shutdown(socket.SHUT_RD)
2570 log("Got black player")
2573 ss[0].send("black " + str(4600 + 2*(len(games)-1)))
2574 ss[0].shutdown(socket.SHUT_RD)
2577 s.shutdown(socket.SHUT_RDWR)
2581 while len(games) > max_games:
2582 #log("Too many games; waiting for game to finish...")
2583 ready = select.select(map(lambda e : e.stdout, games),[], [])
2585 s = r.readline().strip(" \r\n").split(" ")
2586 if s[0] == "white" or s[0] == "black":
2589 log("Game " + str(g) + " has finished")
2594 def client(addr, player="@human"):
2599 s.connect((addr, 4562))
2601 [colour,port] = s.recv(1024).strip(" \r\n").split(" ")
2603 #debug("Colour: " + colour + ", port: " + port)
2605 s.shutdown(socket.SHUT_RDWR)
2608 if colour == "white":
2609 p = subprocess.Popen(["python", "qchess.py", player, "@network:"+addr+":"+port])
2611 p = subprocess.Popen(["python", "qchess.py", "@network:"+addr+":"+port, player])
2613 return 0# --- server.py --- #
2614 #!/usr/bin/python -u
2616 # Do you know what the -u does? It unbuffers stdin and stdout
2617 # I can't remember why, but last year things broke without that
2620 UCC::Progcomp 2013 Quantum Chess game
2621 @author Sam Moore [SZM] "matches"
2622 @copyright The University Computer Club, Incorporated
2623 (ie: You can copy it for not for profit purposes)
2626 # system python modules or whatever they are called
2632 sleep_timeout = None
2633 [game, graphics] = [None, None]
2635 def make_player(name, colour):
2637 if name[1:] == "human":
2638 return HumanPlayer(name, colour)
2639 s = name[1:].split(":")
2640 if s[0] == "network":
2651 if colour == "black":
2653 elif colour == "white":
2656 return NetworkPlayer(colour, Network((ip, port)), None)
2657 if s[0] == "internal":
2660 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2661 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2662 internal_agents.remove(('InternalAgent', InternalAgent))
2665 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
2666 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2669 for a in internal_agents:
2671 return a[1](name, colour)
2673 sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
2674 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2678 return FifoPlayer(s[1], colour)
2680 return FifoPlayer(str(os.getpid())+"."+colour, colour)
2683 return ExternalAgent(name, colour)
2687 # The main function! It does the main stuff!
2690 # Apparently python will silently treat things as local unless you do this
2691 # Anyone who says "You should never use a global variable" can die in a fire
2696 global agent_timeout
2699 global graphics_enabled
2700 global always_reveal_states
2701 global sleep_timeout
2712 # Get the important warnings out of the way
2713 if platform.system() == "Windows":
2714 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
2715 if platform.release() == "Vista":
2716 sys.stderr.write(sys.argv[0] + " : God help you.\n")
2721 while i < len(argv)-1:
2725 p = make_player(arg, colour)
2726 if not isinstance(p, Player):
2727 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
2730 if colour == "white":
2732 elif colour == "black":
2735 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
2738 # Option parsing goes here
2739 if arg[1] == '-' and arg[2:] == "classical":
2741 elif arg[1] == '-' and arg[2:] == "quantum":
2743 elif arg[1] == '-' and arg[2:] == "reveal":
2744 always_reveal_states = True
2745 elif (arg[1] == '-' and arg[2:] == "graphics"):
2746 graphics_enabled = True
2747 elif (arg[1] == '-' and arg[2:] == "no-graphics"):
2748 graphics_enabled = False
2749 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
2750 # Load game from file
2751 if len(arg[2:].split("=")) == 1:
2752 src_file = sys.stdin
2754 f = arg[2:].split("=")[1]
2755 if f[0:7] == "http://":
2756 src_file = HttpReplay(f)
2758 src_file = FileReplay(f.split(":")[0])
2760 if len(f.split(":")) == 2:
2761 max_moves = int(f.split(":")[1])
2763 elif (arg[1] == '-' and arg[2:].split("=")[0] == "server"):
2764 #debug("Server: " + str(arg[2:]))
2765 if len(arg[2:].split("=")) <= 1:
2768 server_addr = arg[2:].split("=")[1]
2770 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
2772 if len(arg[2:].split("=")) == 1:
2773 log_files.append(LogFile(sys.stdout,""))
2775 f = arg[2:].split("=")[1]
2777 log_files.append(LogFile(sys.stdout, ""))
2779 log_files.append(ShortLog(f[1:]))
2781 log_files.append(LogFile(open(f, "w", 0), f))
2782 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
2784 if len(arg[2:].split("=")) == 1:
2787 turn_delay = float(arg[2:].split("=")[1])
2789 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
2791 if len(arg[2:].split("=")) == 1:
2794 agent_timeout = float(arg[2:].split("=")[1])
2795 elif (arg[1] == '-' and arg[2:].split("=")[0] == "blackout"):
2796 # Screen saver delay
2797 if len(arg[2:].split("=")) == 1:
2800 sleep_timeout = float(arg[2:].split("=")[1])
2802 elif (arg[1] == '-' and arg[2:] == "help"):
2804 os.system("less data/help.txt") # The best help function
2809 #debug("server_addr = " + str(server_addr))
2811 if server_addr != None:
2812 if server_addr == True:
2813 return dedicated_server()
2815 if len(players) > 1:
2816 sys.stderr.write("Only a single player may be provided when --server is used\n")
2818 if len(players) == 1:
2819 return client(server_addr, players[0].name)
2821 return client(server_addr)
2826 # Construct a GameThread! Make it global! Damn the consequences!
2828 if src_file != None:
2829 # Hack to stop ReplayThread from exiting
2830 #if len(players) == 0:
2831 # players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
2833 # Normally the ReplayThread exits if there are no players
2834 # TODO: Decide which behaviour to use, and fix it
2835 end = (len(players) == 0)
2837 players = [Player("dummy", "white"), Player("dummy", "black")]
2838 elif len(players) != 2:
2839 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2840 if graphics_enabled:
2841 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
2843 game = ReplayThread(players, src_file, end=end, max_moves=max_moves)
2845 board = Board(style)
2846 board.max_moves = max_moves
2847 game = GameThread(board, players)
2853 if graphics_enabled == True:
2855 graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
2857 graphics.sleep_timeout = sleep_timeout
2861 sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
2862 graphics_enabled = False
2864 # If there are no players listed, display a nice pretty menu
2865 if len(players) != 2:
2866 if graphics != None:
2868 server_addr = graphics.SelectServer()
2869 if server_addr != None:
2870 pygame.quit() # Time to say goodbye
2871 if server_addr == True:
2872 return dedicated_server()
2874 return client(server_addr)
2876 players = graphics.SelectPlayers(players)
2878 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2881 # If there are still no players, quit
2882 if players == None or len(players) != 2:
2883 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
2888 if isinstance(p, NetworkPlayer):
2889 for i in range(len(old)):
2890 if old[i] == p or isinstance(old[i], NetworkPlayer):
2892 players[i] = NetworkPlayer(old[i].colour, p.network, old[i])
2896 if isinstance(p, NetworkPlayer):
2897 p.board = game.board
2898 if not p.network.connected:
2899 if not p.network.server:
2904 # If using windows, select won't work; use horrible TimeoutPlayer hack
2905 if agent_timeout > 0:
2906 if platform.system() == "Windows":
2907 for i in range(len(players)):
2908 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
2909 players[i] = TimeoutPlayer(players[i], agent_timeout)
2913 # InternalAgents get wrapped to an ExternalAgent when there is a timeout
2914 # This is not confusing at all.
2915 for i in range(len(players)):
2916 if isinstance(players[i], InternalAgent):
2917 players[i] = ExternalWrapper(players[i])
2925 log_init(game.board, players)
2928 if graphics != None:
2929 game.start() # This runs in a new thread
2935 error = game.error + graphics.error
2944 if src_file != None and src_file != sys.stdin:
2947 sys.stdout.write(game.final_result + "\n")
2958 # This is how python does a main() function...
2959 if __name__ == "__main__":
2962 retcode = main(sys.argv)
2963 except KeyboardInterrupt:
2964 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
2965 if isinstance(graphics, StoppableThread):
2967 graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
2969 if isinstance(game, StoppableThread):
2974 #except Exception, e:
2975 # sys.stderr.write(sys.argv[0] + " : " + e.message + "\n")
2990 # EOF - created from make on Sun May 19 12:36:10 WST 2013