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):
659 def open_fifo(name, mode, timeout=None):
661 return open(name, mode)
664 class Worker(threading.Thread):
666 threading.Thread.__init__(self)
668 self.exception = None
673 self.result = open(name, mode)
683 while time.time() - start < timeout:
684 if w.is_alive() == False:
686 if w.exception != None:
693 #sys.stderr.write("FIFO_TIMEOUT!\n")
694 # Recursive to deal with possible race condition
697 f = open_fifo(name, "w", 1)
699 f = open_fifo(name, "r", 1)
703 #sys.stderr.write("Opened other end!\n")
710 raise Exception("FIFO_TIMEOUT")
713 if w.exception != None:
718 # Player that runs through a fifo
719 class FifoPlayer(Player):
723 def __init__(self, name, colour):
724 Player.__init__(self, name, colour)
725 os.mkfifo(self.name+".in")
726 os.mkfifo(self.name+".out")
730 self.fifo_out = open_fifo(self.name+".out","w", FifoPlayer.timeout)
732 raise Exception("FIFO_TIMEOUT")
734 self.fifo_out.write("START "+colour+"\n")
735 self.fifo_out.close()
738 def update(self, result):
739 sys.stderr.write("update fifo called\n")
741 self.fifo_out = open_fifo(self.name+".out", "w", FifoPlayer.timeout)
743 raise Exception("FIFO_TIMEOUT")
745 self.fifo_out.write(result +"\n")
746 self.fifo_out.close()
750 sys.stderr.write("select fifo called\n")
752 self.fifo_out = open_fifo(self.name+".out", "w", FifoPlayer.timeout)
754 #sys.stderr.write("TIMEOUT\n")
755 raise Exception("FIFO_TIMEOUT")
758 self.fifo_out.write("SELECT?\n")
759 self.fifo_out.close()
760 self.fifo_in = open_fifo(self.name+".in", "r", FifoPlayer.timeout)
761 s = map(int, self.fifo_in.readline().strip(" \r\n").split(" "))
766 sys.stderr.write("get_move fifo called\n")
768 self.fifo_out = open_fifo(self.name+".out", "w", FifoPlayer.timeout)
770 raise Exception("FIFO_TIMEOUT")
772 self.fifo_out.write("MOVE?\n")
773 self.fifo_out.close()
774 self.fifo_in = open_fifo(self.name+".in", "r", FifoPlayer.timeout)
775 s = map(int, self.fifo_in.readline().strip(" \r\n").split(" "))
779 def quit(self, result):
781 self.fifo_out = open_fifo(self.name+".out", "w", FifoPlayer.timeout)
785 self.fifo_out.write(result + "\n")
786 self.fifo_out.close()
789 os.remove(self.name+".in")
790 os.remove(self.name+".out")
794 # Player that runs from another process
795 class ExternalAgent(Player):
798 def __init__(self, name, colour):
799 Player.__init__(self, name, colour)
800 #raise Exception("waht")
801 self.p = subprocess.Popen(name,bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,universal_newlines=True)
803 self.send_message(colour)
805 def send_message(self, s):
806 if agent_timeout > 0.0:
807 ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
809 ready = [self.p.stdin]
810 if self.p.stdin in ready:
811 #sys.stderr.write("Writing \'" + s + "\' to " + str(self.p) + "\n")
813 self.p.stdin.write(s + "\n")
815 raise Exception("UNRESPONSIVE")
817 raise Exception("TIMEOUT")
819 def get_response(self):
820 if agent_timeout > 0.0:
821 ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
823 ready = [self.p.stdout]
824 if self.p.stdout in ready:
825 #sys.stderr.write("Reading from " + str(self.p) + " 's stdout...\n")
827 result = self.p.stdout.readline().strip(" \t\r\n")
828 #sys.stderr.write("Read \'" + result + "\' from " + str(self.p) + "\n")
830 except: # Exception, e:
831 raise Exception("UNRESPONSIVE")
833 raise Exception("TIMEOUT")
837 self.send_message("SELECTION?")
838 line = self.get_response()
841 m = re.match("\s*(\d+)\s+(\d+)\s*", line)
842 result = map(int, [m.group(1), m.group(2)])
844 raise Exception("GIBBERISH \"" + str(line) + "\"")
847 def update(self, result):
848 #print "Update " + str(result) + " called for AgentPlayer"
849 self.send_message(result)
854 self.send_message("MOVE?")
855 line = self.get_response()
858 m = re.match("\s*(\d+)\s+(\d+)\s*", line)
859 result = map(int, [m.group(1), m.group(2)])
862 raise Exception("GIBBERISH \"" + str(line) + "\"")
865 def reset_board(self, s):
866 self.send_message("BOARD")
867 for line in s.split("\n"):
868 self.send_message(line.strip(" \r\n"))
869 self.send_message("END BOARD")
871 def quit(self, final_result):
873 self.send_message("QUIT " + final_result)
877 # So you want to be a player here?
878 class HumanPlayer(Player):
879 def __init__(self, name, colour):
880 Player.__init__(self, name, colour)
883 # Select your preferred account
885 if isinstance(graphics, GraphicsThread):
886 # Basically, we let the graphics thread do some shit and then return that information to the game thread
887 graphics.cond.acquire()
888 # We wait for the graphics thread to select a piece
889 while graphics.stopped() == False and graphics.state["select"] == None:
890 graphics.cond.wait() # The difference between humans and machines is that humans sleep
891 select = graphics.state["select"]
894 graphics.cond.release()
895 if graphics.stopped():
897 return [select.x, select.y]
899 # Since I don't display the board in this case, I'm not sure why I filled it in...
901 sys.stdout.write("SELECTION?\n")
903 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
906 sys.stderr.write("ILLEGAL GIBBERISH\n")
909 # It's your move captain
911 if isinstance(graphics, GraphicsThread):
912 graphics.cond.acquire()
913 while graphics.stopped() == False and graphics.state["dest"] == None:
915 graphics.cond.release()
917 return graphics.state["dest"]
921 sys.stdout.write("MOVE?\n")
923 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
926 sys.stderr.write("ILLEGAL GIBBERISH\n")
929 # Are you sure you want to quit?
930 def quit(self, final_result):
932 sys.stdout.write("QUIT " + final_result + "\n")
934 # Completely useless function
935 def update(self, result):
936 if isinstance(graphics, GraphicsThread):
939 sys.stdout.write(result + "\n")
943 # Default internal player (makes random moves)
944 class InternalAgent(Player):
945 def __init__(self, name, colour):
946 Player.__init__(self, name, colour)
949 self.board = Board(style = "agent")
952 return "@internal:"+self.name
954 def update(self, result):
956 self.board.update(result)
960 def reset_board(self, s):
961 self.board.reset_board(s)
963 def quit(self, final_result):
966 class AgentRandom(InternalAgent):
967 def __init__(self, name, colour):
968 InternalAgent.__init__(self, name, colour)
972 self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
974 # Check that the piece has some possibility to move
975 tmp = self.choice.current_type
976 if tmp == "unknown": # For unknown pieces, try both types
977 for t in self.choice.types:
980 self.choice.current_type = t
981 all_moves += self.board.possible_moves(self.choice)
983 all_moves = self.board.possible_moves(self.choice)
984 self.choice.current_type = tmp
985 if len(all_moves) > 0:
987 return [self.choice.x, self.choice.y]
990 moves = self.board.possible_moves(self.choice)
991 move = moves[random.randint(0, len(moves)-1)]
995 # Terrible, terrible hacks
997 def run_agent(agent):
998 #sys.stderr.write(sys.argv[0] + " : Running agent " + str(agent) + "\n")
1000 line = sys.stdin.readline().strip(" \r\n")
1001 if line == "SELECTION?":
1002 #sys.stderr.write(sys.argv[0] + " : Make selection\n")
1003 [x,y] = agent.select() # Gets your agent's selection
1004 #sys.stderr.write(sys.argv[0] + " : Selection was " + str(agent.choice) + "\n")
1005 sys.stdout.write(str(x) + " " + str(y) + "\n")
1006 elif line == "MOVE?":
1007 #sys.stderr.write(sys.argv[0] + " : Make move\n")
1008 [x,y] = agent.get_move() # Gets your agent's move
1009 sys.stdout.write(str(x) + " " + str(y) + "\n")
1010 elif line.split(" ")[0] == "QUIT":
1011 #sys.stderr.write(sys.argv[0] + " : Quitting\n")
1012 agent.quit(" ".join(line.split(" ")[1:])) # Quits the game
1014 elif line.split(" ")[0] == "BOARD":
1016 line = sys.stdin.readline().strip(" \r\n")
1017 while line != "END BOARD":
1019 line = sys.stdin.readline().strip(" \r\n")
1020 agent.board.reset_board(s)
1023 agent.update(line) # Updates agent.board
1029 class ExternalWrapper(ExternalAgent):
1030 def __init__(self, agent):
1031 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))\""
1033 ExternalAgent.__init__(self, run, agent.colour)
1037 # --- player.py --- #
1041 class AgentBishop(AgentRandom): # Inherits from AgentRandom (in qchess)
1042 def __init__(self, name, colour,value={"pawn" : 1, "bishop" : 3, "knight" : 3, "rook" : 5, "queen" : 9, "king" : 100, "unknown" : 2}):
1043 InternalAgent.__init__(self, name, colour)
1045 self.aggression = 2.0 # Multiplier for scoring due to aggressive actions
1046 self.defence = 1.0 # Multiplier for scoring due to defensive actions
1048 self.depth = 0 # Current depth
1049 self.max_depth = 2 # Recurse this many times (for some reason, makes more mistakes when this is increased???)
1050 self.recurse_for = -1 # Recurse for the best few moves each times (less than 0 = all moves)
1052 for p in self.board.pieces["white"] + self.board.pieces["black"]:
1054 p.selected_moves = None
1058 def get_value(self, piece):
1061 return float(self.value[piece.types[0]] + self.value[piece.types[1]]) / 2.0
1063 # Score possible moves for the piece
1065 def prioritise_moves(self, piece):
1067 #sys.stderr.write(sys.argv[0] + " : " + str(self) + " prioritise called for " + str(piece) + "\n")
1071 grid = self.board.probability_grid(piece)
1072 #sys.stderr.write("\t Probability grid " + str(grid) + "\n")
1076 if grid[x][y] < 0.3: # Throw out moves with < 30% probability
1077 #sys.stderr.write("\tReject " + str(x) + "," + str(y) + " (" + str(grid[x][y]) + ")\n")
1080 target = self.board.grid[x][y]
1085 # Get total probability that the move is protected
1086 self.board.push_move(piece, x, y)
1090 defenders = self.board.coverage(x, y, piece.colour, reject_allied = False)
1092 for d in defenders.keys():
1093 d_prob += defenders[d]
1094 if len(defenders.keys()) > 0:
1095 d_prob /= float(len(defenders.keys()))
1100 # Get total probability that the move is threatened
1101 attackers = self.board.coverage(x, y, opponent(piece.colour), reject_allied = False)
1103 for a in attackers.keys():
1104 a_prob += attackers[a]
1105 if len(attackers.keys()) > 0:
1106 a_prob /= float(len(attackers.keys()))
1111 self.board.pop_move()
1116 value = self.aggression * (1.0 + d_prob) * self.get_value(target) - self.defence * (1.0 - d_prob) * a_prob * self.get_value(piece)
1118 # Adjust score based on movement of piece out of danger
1119 attackers = self.board.coverage(piece.x, piece.y, opponent(piece.colour))
1121 for a in attackers.keys():
1122 s_prob += attackers[a]
1123 if len(attackers.keys()) > 0:
1124 s_prob /= float(len(attackers.keys()))
1128 value += self.defence * s_prob * self.get_value(piece)
1130 # Adjust score based on probability that the move is actually possible
1131 moves.append([[x, y], grid[x][y] * value])
1133 moves.sort(key = lambda e : e[1], reverse = True)
1134 #sys.stderr.write(sys.argv[0] + ": Moves for " + str(piece) + " are " + str(moves) + "\n")
1136 piece.last_moves = moves
1137 piece.selected_moves = None
1144 def select_best(self, colour):
1148 for p in self.board.pieces[colour]:
1149 self.choice = p # Temporarily pick that piece
1150 m = self.prioritise_moves(p)
1152 all_moves.update({p : m[0]})
1154 if len(all_moves.items()) <= 0:
1158 opts = all_moves.items()
1159 opts.sort(key = lambda e : e[1][1], reverse = True)
1161 if self.depth >= self.max_depth:
1163 return list(opts[0])
1165 if self.recurse_for >= 0:
1166 opts = opts[0:self.recurse_for]
1167 #sys.stderr.write(sys.argv[0] + " : Before recurse, options are " + str(opts) + "\n")
1169 # Take the best few moves, and recurse
1170 for choice in opts[0:self.recurse_for]:
1171 [xx,yy] = [choice[0].x, choice[0].y] # Remember position
1172 [nx,ny] = choice[1][0] # Target
1173 [choice[0].x, choice[0].y] = [nx, ny] # Set position
1174 target = self.board.grid[nx][ny] # Remember piece in spot
1175 self.board.grid[xx][yy] = None # Remove piece
1176 self.board.grid[nx][ny] = choice[0] # Replace with moving piece
1179 best_enemy_move = self.select_best(opponent(choice[0].colour))
1180 choice[1][1] -= best_enemy_move[1][1] / float(self.depth + 1.0)
1182 [choice[0].x, choice[0].y] = [xx, yy] # Restore position
1183 self.board.grid[nx][ny] = target # Restore taken piece
1184 self.board.grid[xx][yy] = choice[0] # Restore moved piece
1188 opts.sort(key = lambda e : e[1][1], reverse = True)
1189 #sys.stderr.write(sys.argv[0] + " : After recurse, options are " + str(opts) + "\n")
1192 return list(opts[0])
1196 # Returns [x,y] of selected piece
1198 #sys.stderr.write("Getting choice...")
1199 self.choice = self.select_best(self.colour)[0]
1201 #sys.stderr.write(" Done " + str(self.choice)+"\n")
1202 return [self.choice.x, self.choice.y]
1204 # Returns [x,y] of square to move selected piece into
1206 #sys.stderr.write("Choice is " + str(self.choice) + "\n")
1207 self.choice.selected_moves = self.choice.last_moves
1208 moves = self.prioritise_moves(self.choice)
1212 return AgentRandom.get_move(self)
1214 # --- agent_bishop.py --- #
1215 import multiprocessing
1217 # Hacky alternative to using select for timing out players
1219 # WARNING: Do not wrap around HumanPlayer or things breakify
1220 # WARNING: Do not use in general or things breakify
1222 class Sleeper(multiprocessing.Process):
1223 def __init__(self, timeout):
1224 multiprocessing.Process.__init__(self)
1225 self.timeout = timeout
1228 time.sleep(self.timeout)
1231 class Worker(multiprocessing.Process):
1232 def __init__(self, function, args, q):
1233 multiprocessing.Process.__init__(self)
1234 self.function = function
1239 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args)
1241 self.q.put(self.function(*self.args))
1247 def TimeoutFunction(function, args, timeout):
1248 q = multiprocessing.Queue()
1249 w = Worker(function, args, q)
1250 s = Sleeper(timeout)
1253 while True: # Busy loop of crappyness
1254 if not w.is_alive():
1258 #print "TimeoutFunction gets " + str(result)
1260 elif not s.is_alive():
1263 raise Exception("TIMEOUT")
1268 # A player that wraps another player and times out its moves
1270 # A (crappy) alternative to the use of select()
1271 class TimeoutPlayer(Player):
1272 def __init__(self, base_player, timeout):
1273 Player.__init__(self, base_player.name, base_player.colour)
1274 self.base_player = base_player
1275 self.timeout = timeout
1278 return TimeoutFunction(self.base_player.select, [], self.timeout)
1282 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
1284 def update(self, result):
1285 return TimeoutFunction(self.base_player.update, [result], self.timeout)
1287 def quit(self, final_result):
1288 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
1289 # --- timeout_player.py --- #
1293 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
1294 network_timeout_delay = 1.0 # Maximum time between two characters being received
1296 class NetworkPlayer(Player):
1297 def __init__(self, colour, network, player):
1298 Player.__init__(self, "@network:"+str(network.address), colour)
1299 self.player = player
1300 self.network = network
1303 return "NetworkPlayer<"+str(self.colour)+","+str(self.player)+">"
1306 #debug(str(self) + " select called")
1307 if self.player != None:
1308 s = self.player.select()
1309 self.send_message(str(s[0]) + " " + str(s[1]))
1311 s = map(int, self.get_response().split(" "))
1312 for p in game.players:
1313 if p != self and isinstance(p, NetworkPlayer) and p.player == None:
1314 p.network.send_message(str(s[0]) + " " + str(s[1]))
1316 game.final_result = "network terminate"
1320 def send_message(self, message):
1321 #debug(str(self) + " send_message(\""+str(message)+"\") called")
1322 self.network.send_message(message)
1324 def get_response(self):
1325 #debug(str(self) + " get_response() called")
1326 s = self.network.get_response()
1327 #debug(str(self) + " get_response() returns \""+str(s)+"\"")
1332 #debug(str(self) + " get_move called")
1333 if self.player != None:
1334 s = self.player.get_move()
1335 self.send_message(str(s[0]) + " " + str(s[1]))
1337 s = map(int, self.get_response().split(" "))
1338 for p in game.players:
1339 if p != self and isinstance(p, NetworkPlayer) and p.player == None:
1340 p.network.send_message(str(s[0]) + " " + str(s[1]))
1343 game.final_result = "network terminate"
1347 def update(self, result):
1348 #debug(str(self) + " update(\""+str(result)+"\") called")
1349 if self.network.server == True:
1350 if self.player == None:
1351 self.send_message(result)
1352 elif self.player != None:
1353 result = self.get_response()
1354 if result == "-1 -1":
1355 game.final_result = "network terminate"
1358 self.board.update(result, deselect=False)
1362 if self.player != None:
1363 result = self.player.update(result)
1369 def base_player(self):
1370 if self.player == None:
1373 return self.player.base_player()
1375 def quit(self, result):
1377 self.send_message("-1 -1")
1382 def __init__(self, address = (None,4562)):
1383 self.socket = socket.socket()
1384 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1385 #self.socket.setblocking(0)
1386 self.address = address
1387 self.server = (address[0] == None)
1390 self.connected = False
1393 #debug(str(self) + "Tries to connect")
1394 self.connected = True
1395 if self.address[0] == None:
1396 self.host = "0.0.0.0" #socket.gethostname() # Breaks things???
1397 self.socket.bind((self.host, self.address[1]))
1398 self.socket.listen(5)
1400 self.src, self.actual_address = self.socket.accept()
1402 self.src.send("ok\n")
1403 s = self.get_response()
1409 self.__init__(colour, (self.address[0], int(s)), baseplayer)
1414 self.socket.connect(self.address)
1415 self.src = self.socket
1416 self.src.send("ok\n")
1417 s = self.get_response()
1423 self.__init__(colour, (self.address[0], int(s)), baseplayer)
1429 return "@network:"+str(self.address)
1431 def get_response(self):
1433 # Timeout the start of the message (first character)
1434 if network_timeout_start > 0.0:
1435 ready = select.select([self.src], [], [], network_timeout_start)[0]
1438 if self.src in ready:
1439 s = self.src.recv(1)
1441 raise Exception("NET_UNRESPONSIVE")
1444 debug("Network get_response s = " + str(s))
1446 while s[len(s)-1] != '\n':
1447 # Timeout on each character in the message
1448 if network_timeout_delay > 0.0:
1449 ready = select.select([self.src], [], [], network_timeout_delay)[0]
1452 if self.src in ready:
1453 s += self.src.recv(1)
1455 raise Exception("NET_UNRESPONSIVE")
1458 return s.strip(" \r\n")
1460 def send_message(self,s):
1461 if network_timeout_start > 0.0:
1462 ready = select.select([], [self.src], [], network_timeout_start)[1]
1466 if self.src in ready:
1467 self.src.send(s + "\n")
1469 raise Exception("NET_UNRESPONSIVE")
1476 # --- network.py --- #
1479 # A thread that can be stopped!
1480 # Except it can only be stopped if it checks self.stopped() periodically
1481 # So it can sort of be stopped
1482 class StoppableThread(threading.Thread):
1484 threading.Thread.__init__(self)
1485 self._stop = threading.Event()
1491 return self._stop.isSet()# --- thread_util.py --- #
1497 def __init__(self, log, name):
1501 self.log.write("# Log starts " + str(datetime.datetime.now()) + "\n")
1504 now = datetime.datetime.now()
1505 self.log.write(str(now) + " : " + s + "\n")
1506 self.logged.append((now, s))
1508 def setup(self, board, players):
1511 self.log.write("# " + str(p.colour) + " : " + str(p.name) + "\n")
1513 self.log.write("# Initial board\n")
1514 for x in range(0, w):
1515 for y in range(0, h):
1516 if board.grid[x][y] != None:
1517 self.log.write(str(board.grid[x][y]) + "\n")
1519 self.log.write("# Start game\n")
1522 self.log.write("# EOF\n")
1523 if self.log != sys.stdout:
1526 class ShortLog(LogFile):
1527 def __init__(self, file_name):
1529 self.log = sys.stdout
1531 self.log = open(file_name, "w", 0)
1532 LogFile.__init__(self, self.log, "@"+file_name)
1533 self.file_name = file_name
1537 now = datetime.datetime.now()
1538 self.logged.append((now, s))
1541 if self.log != sys.stdout:
1543 self.log = open(self.file_name, "w", 0)
1544 self.log.write("# Short log updated " + str(datetime.datetime.now()) + "\n")
1545 LogFile.setup(self, game.board, game.players)
1547 elif self.phase == 1:
1548 for message in self.logged[len(self.logged)-2:]:
1549 self.log.write(str(message[0]) + " : " + message[1] + "\n")
1551 self.phase = (self.phase + 1) % 2
1555 ending = self.logged[len(self.logged)-1]
1556 self.log.write(str(ending[0]) + " : " + ending[1] + "\n")
1557 self.log.write("# EOF\n")
1558 if self.log != sys.stdout:
1562 class HeadRequest(urllib2.Request):
1563 def get_method(self):
1566 class HttpGetter(StoppableThread):
1567 def __init__(self, address):
1568 StoppableThread.__init__(self)
1569 self.address = address
1570 self.log = urllib2.urlopen(address)
1572 self.lock = threading.RLock() #lock for access of self.state
1573 self.cond = threading.Condition() # conditional
1576 while not self.stopped():
1577 line = self.log.readline()
1579 date_mod = datetime.datetime.strptime(self.log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1582 next_log = urllib2.urlopen(HeadRequest(self.address))
1583 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1584 while date_new <= date_mod and not self.stopped():
1585 next_log = urllib2.urlopen(HeadRequest(self.address))
1586 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1590 self.log = urllib2.urlopen(self.address)
1591 line = self.log.readline()
1594 self.lines.append(line)
1595 self.cond.notifyAll()
1598 #sys.stderr.write(" HttpGetter got \'" + str(line) + "\'\n")
1607 def __init__(self, address):
1608 self.getter = HttpGetter(address)
1612 self.getter.cond.acquire()
1613 while len(self.getter.lines) == 0:
1614 self.getter.cond.wait()
1616 result = self.getter.lines[0]
1617 self.getter.lines = self.getter.lines[1:]
1618 self.getter.cond.release()
1627 def __init__(self, filename):
1628 self.f = open(filename, "r", 0)
1629 self.filename = filename
1630 self.mod = os.path.getmtime(filename)
1634 line = self.f.readline()
1637 mod2 = os.path.getmtime(self.filename)
1639 #sys.stderr.write("File changed!\n")
1642 self.f = open(self.filename, "r", 0)
1644 new_line = self.f.readline()
1646 if " ".join(new_line.split(" ")[0:3]) != "# Short log":
1647 for i in range(self.count):
1648 new_line = self.f.readline()
1649 #sys.stderr.write("Read back " + str(i) + ": " + str(new_line) + "\n")
1650 new_line = self.f.readline()
1668 sys.stderr.write("# DEBUG: " + s + "\n")
1671 def log_init(board, players):
1673 l.setup(board, players)
1681 # A thread that runs the game
1682 class GameThread(StoppableThread):
1683 def __init__(self, board, players, server = True):
1684 StoppableThread.__init__(self)
1686 self.players = players
1687 self.state = {"turn" : None} # The game state
1688 self.error = 0 # Whether the thread exits with an error
1689 self.lock = threading.RLock() #lock for access of self.state
1690 self.cond = threading.Condition() # conditional for some reason, I forgot
1691 self.final_result = ""
1692 self.server = server
1693 self.retry_illegal = False
1698 # Run the game (run in new thread with start(), run in current thread with run())
1701 while not self.stopped():
1703 for p in self.players:
1705 self.state["turn"] = p.base_player()
1708 [x,y] = p.select() # Player selects a square
1710 #debug("Quitting in select")
1713 if isinstance(p, NetworkPlayer):
1714 if p.network.server == True:
1715 result = self.board.select(x, y, colour = p.colour)
1720 result = self.board.select(x, y, colour = p.colour)
1722 result = p.update(result)
1725 for p2 in self.players:
1728 p2.update(result) # Inform players of what happened
1738 target = self.board.grid[x][y]
1739 if isinstance(graphics, GraphicsThread):
1741 graphics.state["moves"] = self.board.possible_moves(target)
1742 graphics.state["select"] = target
1744 time.sleep(turn_delay)
1747 if len(self.board.possible_moves(target)) == 0:
1748 #print "Piece cannot move"
1750 if isinstance(graphics, GraphicsThread):
1752 graphics.state["moves"] = None
1753 graphics.state["select"] = None
1754 graphics.state["dest"] = None
1758 [x2,y2] = p.get_move() # Player selects a destination
1763 #debug("Quitting in get_move")
1766 if isinstance(p, NetworkPlayer):
1767 if p.network.server == True:
1768 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1769 self.board.update_move(x, y, x2, y2)
1774 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1775 self.board.update_move(x, y, x2, y2)
1777 result = p.update(result)
1780 for p2 in self.players:
1783 p2.update(result) # Inform players of what happened
1797 if isinstance(graphics, GraphicsThread):
1799 graphics.state["moves"] = [[x2,y2]]
1801 time.sleep(turn_delay)
1803 if isinstance(graphics, GraphicsThread):
1805 graphics.state["select"] = None
1806 graphics.state["dest"] = None
1807 graphics.state["moves"] = None
1810 end = self.board.end_condition()
1814 self.final_result = self.state["turn"].colour + " " + end
1816 self.final_result = end
1826 if self.retry_illegal:
1827 self.state["turn"].update(result);
1829 sys.stderr.write("qchess.py exception: "+result + "\n")
1832 self.final_result = self.state["turn"].colour + " " + e.message
1837 for p2 in self.players:
1838 p2.quit(self.final_result)
1840 log(self.final_result)
1842 if isinstance(graphics, GraphicsThread):
1846 # A thread that replays a log file
1847 class ReplayThread(GameThread):
1848 def __init__(self, players, src, end=False,max_moves=None):
1849 self.board = Board(style="empty")
1850 self.board.max_moves = max_moves
1851 GameThread.__init__(self, self.board, players)
1855 self.reset_board(self.src.readline())
1857 def reset_board(self, line):
1860 while line != "# Start game" and line != "# EOF":
1863 line = self.src.readline().strip(" \r\n")
1867 line = self.src.readline().strip(" \r\n")
1870 self_str += line + "\n"
1872 if self.players[0].name == "dummy" and self.players[1].name == "dummy":
1873 line = self.src.readline().strip(" \r\n")
1876 tokens = line.split(" ")
1877 types = map(lambda e : e.strip("[] ,'"), tokens[2:4])
1878 for i in range(len(types)):
1879 if types[i][0] == "?":
1880 types[i] = "unknown"
1882 agent_str += tokens[0] + " " + tokens[1] + " " + str(types) + " ".join(tokens[4:]) + "\n"
1883 line = self.src.readline().strip(" \r\n")
1885 for p in self.players:
1886 p.reset_board(agent_str)
1889 self.board.reset_board(self_str)
1895 line = self.src.readline().strip(" \r\n")
1896 while line != "# EOF":
1908 line = self.src.readline().strip(" \r\n")
1911 tokens = line.split(" ")
1912 if tokens[0] == "white" or tokens[0] == "black":
1913 self.reset_board(line)
1915 line = self.src.readline().strip(" \r\n")
1918 move = line.split(":")
1919 move = move[len(move)-1].strip(" \r\n")
1920 tokens = move.split(" ")
1924 [x,y] = map(int, tokens[0:2])
1932 target = self.board.grid[x][y]
1934 if target.colour == "white":
1935 self.state["turn"] = self.players[0]
1937 self.state["turn"] = self.players[1]
1939 move_piece = (tokens[2] == "->")
1941 [x2,y2] = map(int, tokens[len(tokens)-2:])
1943 if isinstance(graphics, GraphicsThread):
1945 graphics.state["select"] = target
1948 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
1949 if isinstance(graphics, GraphicsThread):
1951 if target.current_type != "unknown":
1952 graphics.state["moves"] = self.board.possible_moves(target)
1954 graphics.state["moves"] = None
1955 time.sleep(turn_delay)
1957 self.board.update_move(x, y, x2, y2)
1958 if isinstance(graphics, GraphicsThread):
1960 graphics.state["moves"] = [[x2,y2]]
1961 time.sleep(turn_delay)
1963 graphics.state["select"] = None
1964 graphics.state["moves"] = None
1965 graphics.state["dest"] = None
1971 for p in self.players:
1975 line = self.src.readline().strip(" \r\n")
1978 end = self.board.end_condition()
1980 self.final_result = end
1998 if self.end and isinstance(graphics, GraphicsThread):
2000 pass # Let the user stop the display
2001 elif not self.end and self.board.end_condition() == None:
2003 # Work out the last move
2005 t = last_line.split(" ")
2006 if t[len(t)-2] == "black":
2007 self.players.reverse()
2008 elif t[len(t)-2] == "white":
2010 elif self.state["turn"] != None and self.state["turn"].colour == "white":
2011 self.players.reverse()
2014 game = GameThread(self.board, self.players)
2021 def opponent(colour):
2022 if colour == "white":
2033 # Dictionary that stores the unicode character representations of the different pieces
2034 # Chess was clearly the reason why unicode was invented
2035 # For some reason none of the pygame chess implementations I found used them!
2036 piece_char = {"white" : {"king" : u'\u2654',
2037 "queen" : u'\u2655',
2039 "bishop" : u'\u2657',
2040 "knight" : u'\u2658',
2043 "black" : {"king" : u'\u265A',
2044 "queen" : u'\u265B',
2046 "bishop" : u'\u265D',
2047 "knight" : u'\u265E',
2051 images = {"white" : {}, "black" : {}}
2052 small_images = {"white" : {}, "black" : {}}
2054 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
2056 # Get the font sizes
2057 l_size = 5*(grid_sz[0] / 8)
2058 s_size = 3*(grid_sz[0] / 8)
2060 for c in piece_char.keys():
2063 for p in piece_char[c].keys():
2064 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
2065 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})
2067 for p in piece_char[c].keys():
2068 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
2069 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
2070 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
2071 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
2074 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
2075 if not os.path.exists(image_dir):
2076 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
2077 for c in piece_char.keys():
2078 for p in piece_char[c].keys():
2079 images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
2080 small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
2081 # --- images.py --- #
2082 graphics_enabled = True
2086 os.environ["SDL_VIDEO_ALLOW_SCREENSAVER"] = "1"
2088 graphics_enabled = False
2094 # A thread to make things pretty
2095 class GraphicsThread(StoppableThread):
2096 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
2097 StoppableThread.__init__(self)
2101 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
2102 pygame.display.set_caption(title)
2104 #print "Initialised properly"
2106 self.grid_sz = grid_sz[:]
2107 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
2109 self.lock = threading.RLock()
2110 self.cond = threading.Condition()
2111 self.sleep_timeout = None
2112 self.last_event = time.time()
2113 self.blackout = False
2116 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
2119 create_images(grid_sz)
2122 for c in images.keys():
2123 for p in images[c].keys():
2124 images[c][p] = images[c][p].convert(self.window)
2125 small_images[c][p] = small_images[c][p].convert(self.window)
2132 # On the run from the world
2135 while not self.stopped():
2137 if self.sleep_timeout == None or (time.time() - self.last_event) < self.sleep_timeout:
2139 #print "Display grid"
2140 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
2142 #print "Display overlay"
2145 #print "Display pieces"
2146 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
2147 self.blackout = False
2149 elif pygame.mouse.get_focused() and not self.blackout:
2150 os.system("xset dpms force off")
2151 self.blackout = True
2152 self.window.fill((0,0,0))
2154 pygame.display.flip()
2156 for event in pygame.event.get():
2157 self.last_event = time.time()
2158 if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_q):
2159 if isinstance(game, GameThread):
2161 game.final_result = ""
2162 if game.state["turn"] != None:
2163 game.final_result = game.state["turn"].colour + " "
2164 game.final_result += "terminated"
2168 elif event.type == pygame.MOUSEBUTTONDOWN:
2169 self.mouse_down(event)
2171 elif event.type == pygame.MOUSEBUTTONUP:
2172 self.mouse_up(event)
2181 self.message("Game ends, result \""+str(game.final_result) + "\"")
2184 # Wake up anyone who is sleeping
2189 pygame.quit() # Time to say goodbye
2191 # Mouse release event handler
2192 def mouse_up(self, event):
2193 if event.button == 3:
2195 self.state["overlay"] = None
2196 elif event.button == 2:
2198 self.state["coverage"] = None
2200 # Mouse click event handler
2201 def mouse_down(self, event):
2202 if event.button == 1:
2203 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
2204 if isinstance(game, GameThread):
2206 p = game.state["turn"]
2211 if isinstance(p, HumanPlayer):
2213 s = self.board.grid[m[0]][m[1]]
2214 select = self.state["select"]
2216 if s != None and s.colour != p.colour:
2217 self.message("Wrong colour") # Look at all this user friendliness!
2220 # Notify human player of move
2223 self.state["select"] = s
2224 self.state["dest"] = None
2233 if self.state["moves"] == None:
2236 if not m in self.state["moves"]:
2237 self.message("Illegal Move") # I still think last year's mouse interface was adequate
2242 if self.state["dest"] == None:
2244 self.state["dest"] = m
2245 self.state["select"] = None
2246 self.state["moves"] = None
2249 elif event.button == 3:
2250 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2251 if isinstance(game, GameThread):
2253 p = game.state["turn"]
2258 if isinstance(p, HumanPlayer):
2260 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
2262 elif event.button == 2:
2263 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2264 if isinstance(game, GameThread):
2266 p = game.state["turn"]
2271 if isinstance(p, HumanPlayer):
2273 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
2278 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
2279 # Draw square over the selected piece
2281 select = self.state["select"]
2283 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
2284 square_img.fill(pygame.Color(0,255,0,64))
2285 self.window.blit(square_img, mp)
2286 # If a piece is selected, draw all reachable squares
2287 # (This quality user interface has been patented)
2289 m = self.state["moves"]
2291 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
2293 mp = [self.grid_sz[i] * move[i] for i in range(2)]
2294 self.window.blit(square_img, mp)
2295 # If a piece is overlayed, show all squares that it has a probability to reach
2297 m = self.state["overlay"]
2302 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
2303 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
2304 self.window.blit(square_img, mp)
2305 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2306 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
2307 self.window.blit(text, mp)
2309 # If a square is selected, highlight all pieces that have a probability to reach it
2311 m = self.state["coverage"]
2314 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
2315 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
2316 self.window.blit(square_img, mp)
2317 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2318 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
2319 self.window.blit(text, mp)
2320 # Draw a square where the mouse is
2321 # This also serves to indicate who's turn it is
2323 if isinstance(game, GameThread):
2325 turn = game.state["turn"]
2329 if isinstance(turn, HumanPlayer):
2330 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
2331 square_img.fill(pygame.Color(0,0,255,128))
2332 if turn.colour == "white":
2333 c = pygame.Color(255,255,255)
2335 c = pygame.Color(0,0,0)
2336 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
2337 self.window.blit(square_img, mp)
2339 # Message in a bottle
2340 def message(self, string, pos = None, colour = None, font_size = 20):
2341 #print "Drawing message..."
2342 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2344 colour = pygame.Color(0,0,0)
2346 text = font.render(string, 1, colour)
2349 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
2350 s.fill(pygame.Color(128,128,128))
2352 tmp = self.window.get_size()
2355 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
2357 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
2360 rect = (pos[0], pos[1], text.get_width(), text.get_height())
2362 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
2363 self.window.blit(s, pos)
2364 self.window.blit(text, pos)
2366 pygame.display.flip()
2368 def getstr(self, prompt = None):
2369 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
2370 s.blit(self.window, (0,0))
2376 self.message(prompt)
2377 self.message(result, pos = (0, 1))
2380 for event in pygame.event.get():
2381 if event.type == pygame.QUIT:
2383 if event.type == pygame.KEYDOWN:
2384 if event.key == pygame.K_BACKSPACE:
2385 result = result[0:len(result)-1]
2386 self.window.blit(s, (0,0)) # Revert the display
2391 if event.unicode == '\r':
2394 result += str(event.unicode)
2399 # Function to pick a button
2400 def SelectButton(self, choices, prompt = None, font_size=20):
2402 #print "Select button called!"
2403 self.board.display_grid(self.window, self.grid_sz)
2405 self.message(prompt)
2406 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2408 sz = self.window.get_size()
2411 for i in range(len(choices)):
2414 text = font.render(c, 1, pygame.Color(0,0,0))
2415 p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
2416 targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
2419 mp =pygame.mouse.get_pos()
2420 for i in range(len(choices)):
2422 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
2423 font_colour = pygame.Color(255,0,0)
2424 box_colour = pygame.Color(0,0,255,128)
2426 font_colour = pygame.Color(0,0,0)
2427 box_colour = pygame.Color(128,128,128)
2429 text = font.render(c, 1, font_colour)
2430 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
2432 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
2433 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
2434 self.window.blit(s, targets[i][0:2])
2437 pygame.display.flip()
2439 for event in pygame.event.get():
2440 if event.type == pygame.QUIT:
2442 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
2443 for i in range(len(targets)):
2445 if event.pos[0] > t[0] and event.pos[0] < t[2]:
2446 if event.pos[1] > t[1] and event.pos[1] < t[3]:
2448 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
2451 # Function to choose between dedicated server or normal play
2452 def SelectServer(self):
2454 choice = self.SelectButton(["Normal", "Join Eigenserver"],prompt="Game type?")
2457 choice = self.SelectButton(["progcomp.ucc", "other"], prompt="Address?")
2459 return "progcomp.ucc.asn.au"
2461 return self.getstr(prompt = "Enter address:")
2463 # Function to pick players in a nice GUI way
2464 def SelectPlayers(self, players = []):
2467 #print "SelectPlayers called"
2469 missing = ["white", "black"]
2471 missing.remove(p.colour)
2473 for colour in missing:
2476 choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
2478 players.append(HumanPlayer("human", colour))
2481 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2482 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2483 internal_agents.remove(('InternalAgent', InternalAgent))
2484 if len(internal_agents) > 0:
2485 choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
2490 agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
2491 players.append(agent[1](agent[0], colour))
2495 from tkFileDialog import askopenfilename
2496 root = Tkinter.Tk() # Need a root to make Tkinter behave
2497 root.withdraw() # Some sort of magic incantation
2498 path = askopenfilename(parent=root, initialdir="../agents",title=
2501 return self.SelectPlayers()
2502 players.append(make_player(path, colour))
2507 self.board.display_grid(self.window, self.grid_sz)
2508 pygame.display.flip()
2509 path = self.getstr(prompt = "Enter path:")
2514 return self.SelectPlayers()
2517 p = make_player(path, colour)
2519 self.board.display_grid(self.window, self.grid_sz)
2520 pygame.display.flip()
2521 self.message("Invalid path!")
2527 while address == "":
2528 self.board.display_grid(self.window, self.grid_sz)
2530 address = self.getstr(prompt = "Address? (leave blank for server)")
2537 map(int, address.split("."))
2539 self.board.display_grid(self.window, self.grid_sz)
2540 self.message("Invalid IPv4 address!")
2543 players.append(NetworkReceiver(colour, address))
2546 #print str(self) + ".SelectPlayers returns " + str(players)
2551 # --- graphics.py --- #
2552 def dedicated_server():
2561 log("Getting clients...")
2563 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2564 s.bind(("0.0.0.0", 4562))
2568 log("Got white player")
2570 args = ["python", "qchess.py", "--no-graphics", "@network::"+str(4600+2*len(games)), "@network::"+str(4600+2*len(games))]
2571 if len(log_files) != 0:
2574 args.append("--log")
2576 args.append("--log="+str(l.name)+"_"+str(gameID))
2578 g = subprocess.Popen(args, stdout=subprocess.PIPE)
2582 ss[0].send("white " + str(4600 + 2*(len(games)-1)))
2583 ss[0].shutdown(socket.SHUT_RD)
2589 log("Got black player")
2592 ss[0].send("black " + str(4600 + 2*(len(games)-1)))
2593 ss[0].shutdown(socket.SHUT_RD)
2596 s.shutdown(socket.SHUT_RDWR)
2600 while len(games) > max_games:
2601 #log("Too many games; waiting for game to finish...")
2602 ready = select.select(map(lambda e : e.stdout, games),[], [])
2604 s = r.readline().strip(" \r\n").split(" ")
2605 if s[0] == "white" or s[0] == "black":
2608 log("Game " + str(g) + " has finished")
2613 def client(addr, player="@human"):
2616 debug("Client " + player + " starts")
2618 s.connect((addr, 4562))
2620 [colour,port] = s.recv(1024).strip(" \r\n").split(" ")
2622 debug("Colour: " + colour + ", port: " + port)
2624 s.shutdown(socket.SHUT_RDWR)
2627 if colour == "white":
2628 p = subprocess.Popen(["python", "qchess.py", player, "@network:"+addr+":"+port])
2630 p = subprocess.Popen(["python", "qchess.py", "@network:"+addr+":"+port, player])
2633 # --- server.py --- #
2634 #!/usr/bin/python -u
2636 # Do you know what the -u does? It unbuffers stdin and stdout
2637 # I can't remember why, but last year things broke without that
2640 UCC::Progcomp 2013 Quantum Chess game
2641 @author Sam Moore [SZM] "matches"
2642 @copyright The University Computer Club, Incorporated
2643 (ie: You can copy it for not for profit purposes)
2646 # system python modules or whatever they are called
2652 sleep_timeout = None
2653 [game, graphics] = [None, None]
2655 def make_player(name, colour):
2658 if name[1:] == "human":
2659 return HumanPlayer(name, colour)
2660 s = name[1:].split(":")
2661 if s[0] == "network":
2672 if colour == "black":
2674 elif colour == "white":
2677 return NetworkPlayer(colour, Network((ip, port)), None)
2678 if s[0] == "internal":
2681 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2682 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2683 internal_agents.remove(('InternalAgent', InternalAgent))
2686 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
2687 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2690 for a in internal_agents:
2692 return a[1](name, colour)
2694 sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
2695 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2699 return FifoPlayer(s[1], colour)
2701 return FifoPlayer(str(os.getpid())+"."+colour, colour)
2704 return ExternalAgent(name, colour)
2708 # The main function! It does the main stuff!
2711 # Apparently python will silently treat things as local unless you do this
2712 # Anyone who says "You should never use a global variable" can die in a fire
2717 global agent_timeout
2720 global graphics_enabled
2721 global always_reveal_states
2722 global sleep_timeout
2725 retry_illegal = False
2734 # Get the important warnings out of the way
2735 if platform.system() == "Windows":
2736 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
2737 if platform.release() == "Vista":
2738 sys.stderr.write(sys.argv[0] + " : God help you.\n")
2743 while i < len(argv)-1:
2750 # Option parsing goes here
2751 if arg[1] == '-' and arg[2:] == "classical":
2753 elif arg[1] == '-' and arg[2:] == "quantum":
2755 elif arg[1] == '-' and arg[2:] == "reveal":
2756 always_reveal_states = True
2757 elif (arg[1] == '-' and arg[2:] == "graphics"):
2758 graphics_enabled = True
2759 elif (arg[1] == '-' and arg[2:] == "no-graphics"):
2760 graphics_enabled = False
2761 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
2762 # Load game from file
2763 if len(arg[2:].split("=")) == 1:
2764 src_file = sys.stdin
2766 f = arg[2:].split("=")[1]
2767 if f[0:7] == "http://":
2768 src_file = HttpReplay(f)
2770 src_file = FileReplay(f.split(":")[0])
2772 if len(f.split(":")) == 2:
2773 max_moves = int(f.split(":")[1])
2775 elif (arg[1] == '-' and arg[2:].split("=")[0] == "server"):
2776 #debug("Server: " + str(arg[2:]))
2777 if len(arg[2:].split("=")) <= 1:
2780 server_addr = arg[2:].split("=")[1]
2782 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
2784 if len(arg[2:].split("=")) == 1:
2785 log_files.append(LogFile(sys.stdout,""))
2787 f = arg[2:].split("=")[1]
2789 log_files.append(LogFile(sys.stdout, ""))
2791 log_files.append(ShortLog(f[1:]))
2793 log_files.append(LogFile(open(f, "w", 0), f))
2794 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
2796 if len(arg[2:].split("=")) == 1:
2799 turn_delay = float(arg[2:].split("=")[1])
2801 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
2803 if len(arg[2:].split("=")) == 1:
2806 agent_timeout = float(arg[2:].split("=")[1])
2807 elif (arg[1] == '-' and arg[2:].split("=")[0] == "blackout"):
2808 # Screen saver delay
2809 if len(arg[2:].split("=")) == 1:
2812 sleep_timeout = float(arg[2:].split("=")[1])
2813 elif (arg[1] == '-' and arg[2:] == "retry-illegal"):
2814 retry_illegal = not retry_illegal
2815 elif (arg[1] == '-' and arg[2:] == "help"):
2817 os.system("less data/help.txt") # The best help function
2822 #debug("server_addr = " + str(server_addr))
2824 if server_addr != None:
2825 if server_addr == True:
2826 return dedicated_server()
2828 if len(players) > 1:
2829 sys.stderr.write("Only a single player may be provided when --server is used\n")
2831 if len(players) == 1:
2832 return client(server_addr, players[0])
2834 return client(server_addr)
2836 for i in xrange(len(players)):
2837 p = make_player(players[i], colour)
2838 if not isinstance(p, Player):
2839 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
2842 if colour == "white":
2844 elif colour == "black":
2847 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
2851 # Construct a GameThread! Make it global! Damn the consequences!
2853 if src_file != None:
2854 # Hack to stop ReplayThread from exiting
2855 #if len(players) == 0:
2856 # players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
2858 # Normally the ReplayThread exits if there are no players
2859 # TODO: Decide which behaviour to use, and fix it
2860 end = (len(players) == 0)
2862 players = [Player("dummy", "white"), Player("dummy", "black")]
2863 elif len(players) != 2:
2864 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2865 if graphics_enabled:
2866 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
2868 game = ReplayThread(players, src_file, end=end, max_moves=max_moves)
2870 board = Board(style)
2871 board.max_moves = max_moves
2872 game = GameThread(board, players)
2873 game.retry_illegal = retry_illegal
2879 if graphics_enabled == True:
2881 graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
2883 graphics.sleep_timeout = sleep_timeout
2887 sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
2888 graphics_enabled = False
2890 # If there are no players listed, display a nice pretty menu
2891 if len(players) != 2:
2892 if graphics != None:
2894 server_addr = graphics.SelectServer()
2895 if server_addr != None:
2896 pygame.quit() # Time to say goodbye
2897 if server_addr == True:
2898 return dedicated_server()
2900 return client(server_addr)
2902 players = graphics.SelectPlayers(players)
2904 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2907 # If there are still no players, quit
2908 if players == None or len(players) != 2:
2909 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
2914 if isinstance(p, NetworkPlayer):
2915 for i in range(len(old)):
2916 if old[i] == p or isinstance(old[i], NetworkPlayer):
2918 players[i] = NetworkPlayer(old[i].colour, p.network, old[i])
2922 if isinstance(p, NetworkPlayer):
2923 p.board = game.board
2924 if not p.network.connected:
2925 if not p.network.server:
2930 # If using windows, select won't work; use horrible TimeoutPlayer hack
2931 if agent_timeout > 0:
2932 if platform.system() == "Windows":
2933 for i in range(len(players)):
2934 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
2935 players[i] = TimeoutPlayer(players[i], agent_timeout)
2939 # InternalAgents get wrapped to an ExternalAgent when there is a timeout
2940 # This is not confusing at all.
2941 for i in range(len(players)):
2942 if isinstance(players[i], InternalAgent):
2943 players[i] = ExternalWrapper(players[i])
2951 log_init(game.board, players)
2954 if graphics != None:
2955 game.start() # This runs in a new thread
2961 error = game.error + graphics.error
2970 if src_file != None and src_file != sys.stdin:
2973 sys.stdout.write(game.final_result + "\n")
2984 # This is how python does a main() function...
2985 if __name__ == "__main__":
2988 retcode = main(sys.argv)
2989 except KeyboardInterrupt:
2990 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
2991 if isinstance(graphics, StoppableThread):
2993 graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
2995 if isinstance(game, StoppableThread):
3000 #except Exception, e:
3001 # sys.stderr.write(sys.argv[0] + " : " + e.message + "\n")
3016 # EOF - created from make on Monday 24 June 23:55:46 WST 2013