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):
655 # Player that runs through a fifo
656 class FifoPlayer(Player):
657 def __init__(self, name, colour):
658 Player.__init__(self, name, colour)
659 os.mkfifo(self.name+".in")
660 os.mkfifo(self.name+".out")
666 def update(self, result):
667 sys.stderr.write("update fifo called\n")
668 self.fifo_out = open(self.name+".out", "w")
669 self.fifo_out.write(result +"\n")
670 self.fifo_out.close()
674 sys.stderr.write("select fifo called\n")
675 self.fifo_out = open(self.name+".out", "w")
676 self.fifo_out.write("SELECT?\n")
677 self.fifo_out.close()
678 self.fifo_in = open(self.name+".in", "r")
679 s = map(int, self.fifo_in.readline().strip(" \r\n").split(" "))
684 sys.stderr.write("get_move fifo called\n")
685 self.fifo_out = open(self.name+".out", "w")
686 self.fifo_out.write("MOVE?\n")
687 self.fifo_out.close()
688 self.fifo_in = open(self.name+".in", "r")
689 s = map(int, self.fifo_in.readline().strip(" \r\n").split(" "))
693 def quit(self, result):
694 self.fifo_out = open(self.name+".out", "w")
695 self.fifo_out.write(result + "\n")
696 self.fifo_out.close()
697 os.remove(self.name+".in")
698 os.remove(self.name+".out")
700 # Player that runs from another process
701 class ExternalAgent(Player):
704 def __init__(self, name, colour):
705 Player.__init__(self, name, colour)
706 self.p = subprocess.Popen(name,bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,universal_newlines=True)
708 self.send_message(colour)
710 def send_message(self, s):
711 if agent_timeout > 0.0:
712 ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
714 ready = [self.p.stdin]
715 if self.p.stdin in ready:
716 #sys.stderr.write("Writing \'" + s + "\' to " + str(self.p) + "\n")
718 self.p.stdin.write(s + "\n")
720 raise Exception("UNRESPONSIVE")
722 raise Exception("TIMEOUT")
724 def get_response(self):
725 if agent_timeout > 0.0:
726 ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
728 ready = [self.p.stdout]
729 if self.p.stdout in ready:
730 #sys.stderr.write("Reading from " + str(self.p) + " 's stdout...\n")
732 result = self.p.stdout.readline().strip(" \t\r\n")
733 #sys.stderr.write("Read \'" + result + "\' from " + str(self.p) + "\n")
735 except: # Exception, e:
736 raise Exception("UNRESPONSIVE")
738 raise Exception("TIMEOUT")
742 self.send_message("SELECTION?")
743 line = self.get_response()
746 m = re.match("\s*(\d+)\s+(\d+)\s*", line)
747 result = map(int, [m.group(1), m.group(2)])
749 raise Exception("GIBBERISH \"" + str(line) + "\"")
752 def update(self, result):
753 #print "Update " + str(result) + " called for AgentPlayer"
754 self.send_message(result)
759 self.send_message("MOVE?")
760 line = self.get_response()
763 m = re.match("\s*(\d+)\s+(\d+)\s*", line)
764 result = map(int, [m.group(1), m.group(2)])
767 raise Exception("GIBBERISH \"" + str(line) + "\"")
770 def reset_board(self, s):
771 self.send_message("BOARD")
772 for line in s.split("\n"):
773 self.send_message(line.strip(" \r\n"))
774 self.send_message("END BOARD")
776 def quit(self, final_result):
778 self.send_message("QUIT " + final_result)
782 # So you want to be a player here?
783 class HumanPlayer(Player):
784 def __init__(self, name, colour):
785 Player.__init__(self, name, colour)
787 # Select your preferred account
789 if isinstance(graphics, GraphicsThread):
790 # Basically, we let the graphics thread do some shit and then return that information to the game thread
791 graphics.cond.acquire()
792 # We wait for the graphics thread to select a piece
793 while graphics.stopped() == False and graphics.state["select"] == None:
794 graphics.cond.wait() # The difference between humans and machines is that humans sleep
795 select = graphics.state["select"]
798 graphics.cond.release()
799 if graphics.stopped():
801 return [select.x, select.y]
803 # Since I don't display the board in this case, I'm not sure why I filled it in...
805 sys.stdout.write("SELECTION?\n")
807 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
809 sys.stderr.write("ILLEGAL GIBBERISH\n")
811 # It's your move captain
813 if isinstance(graphics, GraphicsThread):
814 graphics.cond.acquire()
815 while graphics.stopped() == False and graphics.state["dest"] == None:
817 graphics.cond.release()
819 return graphics.state["dest"]
823 sys.stdout.write("MOVE?\n")
825 p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
827 sys.stderr.write("ILLEGAL GIBBERISH\n")
830 # Are you sure you want to quit?
831 def quit(self, final_result):
833 sys.stdout.write("QUIT " + final_result + "\n")
835 # Completely useless function
836 def update(self, result):
837 if isinstance(graphics, GraphicsThread):
840 sys.stdout.write(result + "\n")
844 # Default internal player (makes random moves)
845 class InternalAgent(Player):
846 def __init__(self, name, colour):
847 Player.__init__(self, name, colour)
850 self.board = Board(style = "agent")
854 def update(self, result):
856 self.board.update(result)
860 def reset_board(self, s):
861 self.board.reset_board(s)
863 def quit(self, final_result):
866 class AgentRandom(InternalAgent):
867 def __init__(self, name, colour):
868 InternalAgent.__init__(self, name, colour)
872 self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
874 # Check that the piece has some possibility to move
875 tmp = self.choice.current_type
876 if tmp == "unknown": # For unknown pieces, try both types
877 for t in self.choice.types:
880 self.choice.current_type = t
881 all_moves += self.board.possible_moves(self.choice)
883 all_moves = self.board.possible_moves(self.choice)
884 self.choice.current_type = tmp
885 if len(all_moves) > 0:
887 return [self.choice.x, self.choice.y]
890 moves = self.board.possible_moves(self.choice)
891 move = moves[random.randint(0, len(moves)-1)]
895 # Terrible, terrible hacks
897 def run_agent(agent):
898 #sys.stderr.write(sys.argv[0] + " : Running agent " + str(agent) + "\n")
900 line = sys.stdin.readline().strip(" \r\n")
901 if line == "SELECTION?":
902 #sys.stderr.write(sys.argv[0] + " : Make selection\n")
903 [x,y] = agent.select() # Gets your agent's selection
904 #sys.stderr.write(sys.argv[0] + " : Selection was " + str(agent.choice) + "\n")
905 sys.stdout.write(str(x) + " " + str(y) + "\n")
906 elif line == "MOVE?":
907 #sys.stderr.write(sys.argv[0] + " : Make move\n")
908 [x,y] = agent.get_move() # Gets your agent's move
909 sys.stdout.write(str(x) + " " + str(y) + "\n")
910 elif line.split(" ")[0] == "QUIT":
911 #sys.stderr.write(sys.argv[0] + " : Quitting\n")
912 agent.quit(" ".join(line.split(" ")[1:])) # Quits the game
914 elif line.split(" ")[0] == "BOARD":
916 line = sys.stdin.readline().strip(" \r\n")
917 while line != "END BOARD":
919 line = sys.stdin.readline().strip(" \r\n")
920 agent.board.reset_board(s)
923 agent.update(line) # Updates agent.board
929 class ExternalWrapper(ExternalAgent):
930 def __init__(self, agent):
931 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))\""
933 ExternalAgent.__init__(self, run, agent.colour)
937 # --- player.py --- #
941 class AgentBishop(AgentRandom): # Inherits from AgentRandom (in qchess)
942 def __init__(self, name, colour,value={"pawn" : 1, "bishop" : 3, "knight" : 3, "rook" : 5, "queen" : 9, "king" : 100, "unknown" : 2}):
943 InternalAgent.__init__(self, name, colour)
945 self.aggression = 2.0 # Multiplier for scoring due to aggressive actions
946 self.defence = 1.0 # Multiplier for scoring due to defensive actions
948 self.depth = 0 # Current depth
949 self.max_depth = 2 # Recurse this many times (for some reason, makes more mistakes when this is increased???)
950 self.recurse_for = -1 # Recurse for the best few moves each times (less than 0 = all moves)
952 for p in self.board.pieces["white"] + self.board.pieces["black"]:
954 p.selected_moves = None
958 def get_value(self, piece):
961 return float(self.value[piece.types[0]] + self.value[piece.types[1]]) / 2.0
963 # Score possible moves for the piece
965 def prioritise_moves(self, piece):
967 #sys.stderr.write(sys.argv[0] + " : " + str(self) + " prioritise called for " + str(piece) + "\n")
971 grid = self.board.probability_grid(piece)
972 #sys.stderr.write("\t Probability grid " + str(grid) + "\n")
976 if grid[x][y] < 0.3: # Throw out moves with < 30% probability
977 #sys.stderr.write("\tReject " + str(x) + "," + str(y) + " (" + str(grid[x][y]) + ")\n")
980 target = self.board.grid[x][y]
985 # Get total probability that the move is protected
986 self.board.push_move(piece, x, y)
990 defenders = self.board.coverage(x, y, piece.colour, reject_allied = False)
992 for d in defenders.keys():
993 d_prob += defenders[d]
994 if len(defenders.keys()) > 0:
995 d_prob /= float(len(defenders.keys()))
1000 # Get total probability that the move is threatened
1001 attackers = self.board.coverage(x, y, opponent(piece.colour), reject_allied = False)
1003 for a in attackers.keys():
1004 a_prob += attackers[a]
1005 if len(attackers.keys()) > 0:
1006 a_prob /= float(len(attackers.keys()))
1011 self.board.pop_move()
1016 value = self.aggression * (1.0 + d_prob) * self.get_value(target) - self.defence * (1.0 - d_prob) * a_prob * self.get_value(piece)
1018 # Adjust score based on movement of piece out of danger
1019 attackers = self.board.coverage(piece.x, piece.y, opponent(piece.colour))
1021 for a in attackers.keys():
1022 s_prob += attackers[a]
1023 if len(attackers.keys()) > 0:
1024 s_prob /= float(len(attackers.keys()))
1028 value += self.defence * s_prob * self.get_value(piece)
1030 # Adjust score based on probability that the move is actually possible
1031 moves.append([[x, y], grid[x][y] * value])
1033 moves.sort(key = lambda e : e[1], reverse = True)
1034 #sys.stderr.write(sys.argv[0] + ": Moves for " + str(piece) + " are " + str(moves) + "\n")
1036 piece.last_moves = moves
1037 piece.selected_moves = None
1044 def select_best(self, colour):
1048 for p in self.board.pieces[colour]:
1049 self.choice = p # Temporarily pick that piece
1050 m = self.prioritise_moves(p)
1052 all_moves.update({p : m[0]})
1054 if len(all_moves.items()) <= 0:
1058 opts = all_moves.items()
1059 opts.sort(key = lambda e : e[1][1], reverse = True)
1061 if self.depth >= self.max_depth:
1063 return list(opts[0])
1065 if self.recurse_for >= 0:
1066 opts = opts[0:self.recurse_for]
1067 #sys.stderr.write(sys.argv[0] + " : Before recurse, options are " + str(opts) + "\n")
1069 # Take the best few moves, and recurse
1070 for choice in opts[0:self.recurse_for]:
1071 [xx,yy] = [choice[0].x, choice[0].y] # Remember position
1072 [nx,ny] = choice[1][0] # Target
1073 [choice[0].x, choice[0].y] = [nx, ny] # Set position
1074 target = self.board.grid[nx][ny] # Remember piece in spot
1075 self.board.grid[xx][yy] = None # Remove piece
1076 self.board.grid[nx][ny] = choice[0] # Replace with moving piece
1079 best_enemy_move = self.select_best(opponent(choice[0].colour))
1080 choice[1][1] -= best_enemy_move[1][1] / float(self.depth + 1.0)
1082 [choice[0].x, choice[0].y] = [xx, yy] # Restore position
1083 self.board.grid[nx][ny] = target # Restore taken piece
1084 self.board.grid[xx][yy] = choice[0] # Restore moved piece
1088 opts.sort(key = lambda e : e[1][1], reverse = True)
1089 #sys.stderr.write(sys.argv[0] + " : After recurse, options are " + str(opts) + "\n")
1092 return list(opts[0])
1096 # Returns [x,y] of selected piece
1098 #sys.stderr.write("Getting choice...")
1099 self.choice = self.select_best(self.colour)[0]
1101 #sys.stderr.write(" Done " + str(self.choice)+"\n")
1102 return [self.choice.x, self.choice.y]
1104 # Returns [x,y] of square to move selected piece into
1106 #sys.stderr.write("Choice is " + str(self.choice) + "\n")
1107 self.choice.selected_moves = self.choice.last_moves
1108 moves = self.prioritise_moves(self.choice)
1112 return AgentRandom.get_move(self)
1114 # --- agent_bishop.py --- #
1115 import multiprocessing
1117 # Hacky alternative to using select for timing out players
1119 # WARNING: Do not wrap around HumanPlayer or things breakify
1120 # WARNING: Do not use in general or things breakify
1122 class Sleeper(multiprocessing.Process):
1123 def __init__(self, timeout):
1124 multiprocessing.Process.__init__(self)
1125 self.timeout = timeout
1128 time.sleep(self.timeout)
1131 class Worker(multiprocessing.Process):
1132 def __init__(self, function, args, q):
1133 multiprocessing.Process.__init__(self)
1134 self.function = function
1139 #print str(self) + " runs " + str(self.function) + " with args " + str(self.args)
1140 self.q.put(self.function(*self.args))
1144 def TimeoutFunction(function, args, timeout):
1145 q = multiprocessing.Queue()
1146 w = Worker(function, args, q)
1147 s = Sleeper(timeout)
1150 while True: # Busy loop of crappyness
1151 if not w.is_alive():
1155 #print "TimeoutFunction gets " + str(result)
1157 elif not s.is_alive():
1160 raise Exception("TIMEOUT")
1165 # A player that wraps another player and times out its moves
1167 # A (crappy) alternative to the use of select()
1168 class TimeoutPlayer(Player):
1169 def __init__(self, base_player, timeout):
1170 Player.__init__(self, base_player.name, base_player.colour)
1171 self.base_player = base_player
1172 self.timeout = timeout
1175 return TimeoutFunction(self.base_player.select, [], self.timeout)
1179 return TimeoutFunction(self.base_player.get_move, [], self.timeout)
1181 def update(self, result):
1182 return TimeoutFunction(self.base_player.update, [result], self.timeout)
1184 def quit(self, final_result):
1185 return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
1186 # --- timeout_player.py --- #
1190 network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
1191 network_timeout_delay = 1.0 # Maximum time between two characters being received
1193 class NetworkPlayer(Player):
1194 def __init__(self, colour, network, player):
1195 Player.__init__(self, "@network:"+str(network.address), colour)
1196 self.player = player
1197 self.network = network
1200 return "NetworkPlayer<"+str(self.colour)+","+str(self.player)+">"
1203 #debug(str(self) + " select called")
1204 if self.player != None:
1205 s = self.player.select()
1206 self.send_message(str(s[0]) + " " + str(s[1]))
1208 s = map(int, self.get_response().split(" "))
1209 for p in game.players:
1210 if p != self and isinstance(p, NetworkPlayer) and p.player == None:
1211 p.network.send_message(str(s[0]) + " " + str(s[1]))
1213 game.final_result = "network terminate"
1217 def send_message(self, message):
1218 #debug(str(self) + " send_message(\""+str(message)+"\") called")
1219 self.network.send_message(message)
1221 def get_response(self):
1222 #debug(str(self) + " get_response() called")
1223 s = self.network.get_response()
1224 #debug(str(self) + " get_response() returns \""+str(s)+"\"")
1229 #debug(str(self) + " get_move called")
1230 if self.player != None:
1231 s = self.player.get_move()
1232 self.send_message(str(s[0]) + " " + str(s[1]))
1234 s = map(int, self.get_response().split(" "))
1235 for p in game.players:
1236 if p != self and isinstance(p, NetworkPlayer) and p.player == None:
1237 p.network.send_message(str(s[0]) + " " + str(s[1]))
1240 game.final_result = "network terminate"
1244 def update(self, result):
1245 #debug(str(self) + " update(\""+str(result)+"\") called")
1246 if self.network.server == True:
1247 if self.player == None:
1248 self.send_message(result)
1249 elif self.player != None:
1250 result = self.get_response()
1251 if result == "-1 -1":
1252 game.final_result = "network terminate"
1255 self.board.update(result, deselect=False)
1259 if self.player != None:
1260 result = self.player.update(result)
1266 def base_player(self):
1267 if self.player == None:
1270 return self.player.base_player()
1272 def quit(self, result):
1274 self.send_message("-1 -1")
1279 def __init__(self, address = (None,4562)):
1280 self.socket = socket.socket()
1281 self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
1282 #self.socket.setblocking(0)
1283 self.address = address
1284 self.server = (address[0] == None)
1287 self.connected = False
1290 #debug(str(self) + "Tries to connect")
1291 self.connected = True
1292 if self.address[0] == None:
1293 self.host = "0.0.0.0" #socket.gethostname() # Breaks things???
1294 self.socket.bind((self.host, self.address[1]))
1295 self.socket.listen(5)
1297 self.src, self.actual_address = self.socket.accept()
1299 self.src.send("ok\n")
1300 s = self.get_response()
1306 self.__init__(colour, (self.address[0], int(s)), baseplayer)
1311 self.socket.connect(self.address)
1312 self.src = self.socket
1313 self.src.send("ok\n")
1314 s = self.get_response()
1320 self.__init__(colour, (self.address[0], int(s)), baseplayer)
1326 return "@network:"+str(self.address)
1328 def get_response(self):
1330 # Timeout the start of the message (first character)
1331 if network_timeout_start > 0.0:
1332 ready = select.select([self.src], [], [], network_timeout_start)[0]
1335 if self.src in ready:
1336 s = self.src.recv(1)
1338 raise Exception("UNRESPONSIVE")
1341 while s[len(s)-1] != '\n':
1342 # Timeout on each character in the message
1343 if network_timeout_delay > 0.0:
1344 ready = select.select([self.src], [], [], network_timeout_delay)[0]
1347 if self.src in ready:
1348 s += self.src.recv(1)
1350 raise Exception("UNRESPONSIVE")
1353 return s.strip(" \r\n")
1355 def send_message(self,s):
1356 if network_timeout_start > 0.0:
1357 ready = select.select([], [self.src], [], network_timeout_start)[1]
1361 if self.src in ready:
1362 self.src.send(s + "\n")
1364 raise Exception("UNRESPONSIVE")
1371 # --- network.py --- #
1374 # A thread that can be stopped!
1375 # Except it can only be stopped if it checks self.stopped() periodically
1376 # So it can sort of be stopped
1377 class StoppableThread(threading.Thread):
1379 threading.Thread.__init__(self)
1380 self._stop = threading.Event()
1386 return self._stop.isSet()
1387 # --- thread_util.py --- #
1393 def __init__(self, log, name):
1397 self.log.write("# Log starts " + str(datetime.datetime.now()) + "\n")
1400 now = datetime.datetime.now()
1401 self.log.write(str(now) + " : " + s + "\n")
1402 self.logged.append((now, s))
1404 def setup(self, board, players):
1407 self.log.write("# " + str(p.colour) + " : " + str(p.name) + "\n")
1409 self.log.write("# Initial board\n")
1410 for x in range(0, w):
1411 for y in range(0, h):
1412 if board.grid[x][y] != None:
1413 self.log.write(str(board.grid[x][y]) + "\n")
1415 self.log.write("# Start game\n")
1418 self.log.write("# EOF\n")
1419 if self.log != sys.stdout:
1422 class ShortLog(LogFile):
1423 def __init__(self, file_name):
1425 self.log = sys.stdout
1427 self.log = open(file_name, "w", 0)
1428 LogFile.__init__(self, self.log, "@"+file_name)
1429 self.file_name = file_name
1433 now = datetime.datetime.now()
1434 self.logged.append((now, s))
1437 if self.log != sys.stdout:
1439 self.log = open(self.file_name, "w", 0)
1440 self.log.write("# Short log updated " + str(datetime.datetime.now()) + "\n")
1441 LogFile.setup(self, game.board, game.players)
1443 elif self.phase == 1:
1444 for message in self.logged[len(self.logged)-2:]:
1445 self.log.write(str(message[0]) + " : " + message[1] + "\n")
1447 self.phase = (self.phase + 1) % 2
1451 ending = self.logged[len(self.logged)-1]
1452 self.log.write(str(ending[0]) + " : " + ending[1] + "\n")
1453 self.log.write("# EOF\n")
1454 if self.log != sys.stdout:
1458 class HeadRequest(urllib2.Request):
1459 def get_method(self):
1462 class HttpGetter(StoppableThread):
1463 def __init__(self, address):
1464 StoppableThread.__init__(self)
1465 self.address = address
1466 self.log = urllib2.urlopen(address)
1468 self.lock = threading.RLock() #lock for access of self.state
1469 self.cond = threading.Condition() # conditional
1472 while not self.stopped():
1473 line = self.log.readline()
1475 date_mod = datetime.datetime.strptime(self.log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1478 next_log = urllib2.urlopen(HeadRequest(self.address))
1479 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1480 while date_new <= date_mod and not self.stopped():
1481 next_log = urllib2.urlopen(HeadRequest(self.address))
1482 date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
1486 self.log = urllib2.urlopen(self.address)
1487 line = self.log.readline()
1490 self.lines.append(line)
1491 self.cond.notifyAll()
1494 #sys.stderr.write(" HttpGetter got \'" + str(line) + "\'\n")
1503 def __init__(self, address):
1504 self.getter = HttpGetter(address)
1508 self.getter.cond.acquire()
1509 while len(self.getter.lines) == 0:
1510 self.getter.cond.wait()
1512 result = self.getter.lines[0]
1513 self.getter.lines = self.getter.lines[1:]
1514 self.getter.cond.release()
1523 def __init__(self, filename):
1524 self.f = open(filename, "r", 0)
1525 self.filename = filename
1526 self.mod = os.path.getmtime(filename)
1530 line = self.f.readline()
1533 mod2 = os.path.getmtime(self.filename)
1535 #sys.stderr.write("File changed!\n")
1538 self.f = open(self.filename, "r", 0)
1540 new_line = self.f.readline()
1542 if " ".join(new_line.split(" ")[0:3]) != "# Short log":
1543 for i in range(self.count):
1544 new_line = self.f.readline()
1545 #sys.stderr.write("Read back " + str(i) + ": " + str(new_line) + "\n")
1546 new_line = self.f.readline()
1564 sys.stderr.write("# DEBUG: " + s + "\n")
1567 def log_init(board, players):
1569 l.setup(board, players)
1577 # A thread that runs the game
1578 class GameThread(StoppableThread):
1579 def __init__(self, board, players, server = True):
1580 StoppableThread.__init__(self)
1582 self.players = players
1583 self.state = {"turn" : None} # The game state
1584 self.error = 0 # Whether the thread exits with an error
1585 self.lock = threading.RLock() #lock for access of self.state
1586 self.cond = threading.Condition() # conditional for some reason, I forgot
1587 self.final_result = ""
1588 self.server = server
1595 # Run the game (run in new thread with start(), run in current thread with run())
1598 while not self.stopped():
1600 for p in self.players:
1602 self.state["turn"] = p.base_player()
1605 [x,y] = p.select() # Player selects a square
1607 #debug("Quitting in select")
1610 if isinstance(p, NetworkPlayer):
1611 if p.network.server == True:
1612 result = self.board.select(x, y, colour = p.colour)
1617 result = self.board.select(x, y, colour = p.colour)
1619 result = p.update(result)
1622 for p2 in self.players:
1625 p2.update(result) # Inform players of what happened
1635 target = self.board.grid[x][y]
1636 if isinstance(graphics, GraphicsThread):
1638 graphics.state["moves"] = self.board.possible_moves(target)
1639 graphics.state["select"] = target
1641 time.sleep(turn_delay)
1644 if len(self.board.possible_moves(target)) == 0:
1645 #print "Piece cannot move"
1647 if isinstance(graphics, GraphicsThread):
1649 graphics.state["moves"] = None
1650 graphics.state["select"] = None
1651 graphics.state["dest"] = None
1655 [x2,y2] = p.get_move() # Player selects a destination
1660 #debug("Quitting in get_move")
1663 if isinstance(p, NetworkPlayer):
1664 if p.network.server == True:
1665 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1666 self.board.update_move(x, y, x2, y2)
1671 result = str(x) + " " + str(y) + " -> " + str(x2) + " " + str(y2)
1672 self.board.update_move(x, y, x2, y2)
1674 result = p.update(result)
1677 for p2 in self.players:
1680 p2.update(result) # Inform players of what happened
1694 if isinstance(graphics, GraphicsThread):
1696 graphics.state["moves"] = [[x2,y2]]
1698 time.sleep(turn_delay)
1700 if isinstance(graphics, GraphicsThread):
1702 graphics.state["select"] = None
1703 graphics.state["dest"] = None
1704 graphics.state["moves"] = None
1706 # Commented out exception stuff for now, because it makes it impossible to tell if I made an IndentationError somewhere
1707 # except Exception,e:
1708 # result = e.message
1709 # #sys.stderr.write(result + "\n")
1713 # self.final_result = self.state["turn"].colour + " " + e.message
1715 end = self.board.end_condition()
1719 self.final_result = self.state["turn"].colour + " " + end
1721 self.final_result = end
1728 for p2 in self.players:
1729 p2.quit(self.final_result)
1731 log(self.final_result)
1733 if isinstance(graphics, GraphicsThread):
1737 # A thread that replays a log file
1738 class ReplayThread(GameThread):
1739 def __init__(self, players, src, end=False,max_moves=None):
1740 self.board = Board(style="empty")
1741 self.board.max_moves = max_moves
1742 GameThread.__init__(self, self.board, players)
1746 self.reset_board(self.src.readline())
1748 def reset_board(self, line):
1751 while line != "# Start game" and line != "# EOF":
1754 line = self.src.readline().strip(" \r\n")
1758 line = self.src.readline().strip(" \r\n")
1761 self_str += line + "\n"
1763 if self.players[0].name == "dummy" and self.players[1].name == "dummy":
1764 line = self.src.readline().strip(" \r\n")
1767 tokens = line.split(" ")
1768 types = map(lambda e : e.strip("[] ,'"), tokens[2:4])
1769 for i in range(len(types)):
1770 if types[i][0] == "?":
1771 types[i] = "unknown"
1773 agent_str += tokens[0] + " " + tokens[1] + " " + str(types) + " ".join(tokens[4:]) + "\n"
1774 line = self.src.readline().strip(" \r\n")
1776 for p in self.players:
1777 p.reset_board(agent_str)
1780 self.board.reset_board(self_str)
1786 line = self.src.readline().strip(" \r\n")
1787 while line != "# EOF":
1799 line = self.src.readline().strip(" \r\n")
1802 tokens = line.split(" ")
1803 if tokens[0] == "white" or tokens[0] == "black":
1804 self.reset_board(line)
1806 line = self.src.readline().strip(" \r\n")
1809 move = line.split(":")
1810 move = move[len(move)-1].strip(" \r\n")
1811 tokens = move.split(" ")
1815 [x,y] = map(int, tokens[0:2])
1823 target = self.board.grid[x][y]
1825 if target.colour == "white":
1826 self.state["turn"] = self.players[0]
1828 self.state["turn"] = self.players[1]
1830 move_piece = (tokens[2] == "->")
1832 [x2,y2] = map(int, tokens[len(tokens)-2:])
1834 if isinstance(graphics, GraphicsThread):
1836 graphics.state["select"] = target
1839 self.board.update_select(x, y, int(tokens[2]), tokens[len(tokens)-1])
1840 if isinstance(graphics, GraphicsThread):
1842 if target.current_type != "unknown":
1843 graphics.state["moves"] = self.board.possible_moves(target)
1845 graphics.state["moves"] = None
1846 time.sleep(turn_delay)
1848 self.board.update_move(x, y, x2, y2)
1849 if isinstance(graphics, GraphicsThread):
1851 graphics.state["moves"] = [[x2,y2]]
1852 time.sleep(turn_delay)
1854 graphics.state["select"] = None
1855 graphics.state["moves"] = None
1856 graphics.state["dest"] = None
1862 for p in self.players:
1866 line = self.src.readline().strip(" \r\n")
1869 end = self.board.end_condition()
1871 self.final_result = end
1889 if self.end and isinstance(graphics, GraphicsThread):
1891 pass # Let the user stop the display
1892 elif not self.end and self.board.end_condition() == None:
1894 # Work out the last move
1896 t = last_line.split(" ")
1897 if t[len(t)-2] == "black":
1898 self.players.reverse()
1899 elif t[len(t)-2] == "white":
1901 elif self.state["turn"] != None and self.state["turn"].colour == "white":
1902 self.players.reverse()
1905 game = GameThread(self.board, self.players)
1912 def opponent(colour):
1913 if colour == "white":
1924 # Dictionary that stores the unicode character representations of the different pieces
1925 # Chess was clearly the reason why unicode was invented
1926 # For some reason none of the pygame chess implementations I found used them!
1927 piece_char = {"white" : {"king" : u'\u2654',
1928 "queen" : u'\u2655',
1930 "bishop" : u'\u2657',
1931 "knight" : u'\u2658',
1934 "black" : {"king" : u'\u265A',
1935 "queen" : u'\u265B',
1937 "bishop" : u'\u265D',
1938 "knight" : u'\u265E',
1942 images = {"white" : {}, "black" : {}}
1943 small_images = {"white" : {}, "black" : {}}
1945 def create_images(grid_sz, font_name=os.path.join(os.path.curdir, "data", "DejaVuSans.ttf")):
1947 # Get the font sizes
1948 l_size = 5*(grid_sz[0] / 8)
1949 s_size = 3*(grid_sz[0] / 8)
1951 for c in piece_char.keys():
1954 for p in piece_char[c].keys():
1955 images[c].update({p : pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0))})
1956 small_images[c].update({p : pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0))})
1958 for p in piece_char[c].keys():
1959 images[c].update({p : pygame.font.Font(font_name, l_size+1).render(piece_char["black"][p], True,(255,255,255))})
1960 images[c][p].blit(pygame.font.Font(font_name, l_size).render(piece_char[c][p], True,(0,0,0)),(0,0))
1961 small_images[c].update({p : pygame.font.Font(font_name, s_size+1).render(piece_char["black"][p],True,(255,255,255))})
1962 small_images[c][p].blit(pygame.font.Font(font_name, s_size).render(piece_char[c][p],True,(0,0,0)),(0,0))
1965 def load_images(image_dir=os.path.join(os.path.curdir, "data", "images")):
1966 if not os.path.exists(image_dir):
1967 raise Exception("Couldn't load images from " + image_dir + " (path doesn't exist)")
1968 for c in piece_char.keys():
1969 for p in piece_char[c].keys():
1970 images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + ".png"))})
1971 small_images[c].update({p : pygame.image.load(os.path.join(image_dir, c + "_" + p + "_small.png"))})
1972 # --- images.py --- #
1973 graphics_enabled = True
1977 os.environ["SDL_VIDEO_ALLOW_SCREENSAVER"] = "1"
1979 graphics_enabled = False
1985 # A thread to make things pretty
1986 class GraphicsThread(StoppableThread):
1987 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
1988 StoppableThread.__init__(self)
1992 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
1993 pygame.display.set_caption(title)
1995 #print "Initialised properly"
1997 self.grid_sz = grid_sz[:]
1998 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
2000 self.lock = threading.RLock()
2001 self.cond = threading.Condition()
2002 self.sleep_timeout = None
2003 self.last_event = time.time()
2004 self.blackout = False
2007 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
2010 create_images(grid_sz)
2013 for c in images.keys():
2014 for p in images[c].keys():
2015 images[c][p] = images[c][p].convert(self.window)
2016 small_images[c][p] = small_images[c][p].convert(self.window)
2023 # On the run from the world
2026 while not self.stopped():
2028 if self.sleep_timeout == None or (time.time() - self.last_event) < self.sleep_timeout:
2030 #print "Display grid"
2031 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
2033 #print "Display overlay"
2036 #print "Display pieces"
2037 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
2038 self.blackout = False
2040 elif pygame.mouse.get_focused() and not self.blackout:
2041 os.system("xset dpms force off")
2042 self.blackout = True
2043 self.window.fill((0,0,0))
2045 pygame.display.flip()
2047 for event in pygame.event.get():
2048 self.last_event = time.time()
2049 if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_q):
2050 if isinstance(game, GameThread):
2052 game.final_result = ""
2053 if game.state["turn"] != None:
2054 game.final_result = game.state["turn"].colour + " "
2055 game.final_result += "terminated"
2059 elif event.type == pygame.MOUSEBUTTONDOWN:
2060 self.mouse_down(event)
2062 elif event.type == pygame.MOUSEBUTTONUP:
2063 self.mouse_up(event)
2072 self.message("Game ends, result \""+str(game.final_result) + "\"")
2075 # Wake up anyone who is sleeping
2080 pygame.quit() # Time to say goodbye
2082 # Mouse release event handler
2083 def mouse_up(self, event):
2084 if event.button == 3:
2086 self.state["overlay"] = None
2087 elif event.button == 2:
2089 self.state["coverage"] = None
2091 # Mouse click event handler
2092 def mouse_down(self, event):
2093 if event.button == 1:
2094 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
2095 if isinstance(game, GameThread):
2097 p = game.state["turn"]
2102 if isinstance(p, HumanPlayer):
2104 s = self.board.grid[m[0]][m[1]]
2105 select = self.state["select"]
2107 if s != None and s.colour != p.colour:
2108 self.message("Wrong colour") # Look at all this user friendliness!
2111 # Notify human player of move
2114 self.state["select"] = s
2115 self.state["dest"] = None
2124 if self.state["moves"] == None:
2127 if not m in self.state["moves"]:
2128 self.message("Illegal Move") # I still think last year's mouse interface was adequate
2133 if self.state["dest"] == None:
2135 self.state["dest"] = m
2136 self.state["select"] = None
2137 self.state["moves"] = None
2140 elif event.button == 3:
2141 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2142 if isinstance(game, GameThread):
2144 p = game.state["turn"]
2149 if isinstance(p, HumanPlayer):
2151 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
2153 elif event.button == 2:
2154 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
2155 if isinstance(game, GameThread):
2157 p = game.state["turn"]
2162 if isinstance(p, HumanPlayer):
2164 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
2169 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
2170 # Draw square over the selected piece
2172 select = self.state["select"]
2174 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
2175 square_img.fill(pygame.Color(0,255,0,64))
2176 self.window.blit(square_img, mp)
2177 # If a piece is selected, draw all reachable squares
2178 # (This quality user interface has been patented)
2180 m = self.state["moves"]
2182 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
2184 mp = [self.grid_sz[i] * move[i] for i in range(2)]
2185 self.window.blit(square_img, mp)
2186 # If a piece is overlayed, show all squares that it has a probability to reach
2188 m = self.state["overlay"]
2193 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
2194 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
2195 self.window.blit(square_img, mp)
2196 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2197 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
2198 self.window.blit(text, mp)
2200 # If a square is selected, highlight all pieces that have a probability to reach it
2202 m = self.state["coverage"]
2205 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
2206 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
2207 self.window.blit(square_img, mp)
2208 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
2209 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
2210 self.window.blit(text, mp)
2211 # Draw a square where the mouse is
2212 # This also serves to indicate who's turn it is
2214 if isinstance(game, GameThread):
2216 turn = game.state["turn"]
2220 if isinstance(turn, HumanPlayer):
2221 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
2222 square_img.fill(pygame.Color(0,0,255,128))
2223 if turn.colour == "white":
2224 c = pygame.Color(255,255,255)
2226 c = pygame.Color(0,0,0)
2227 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
2228 self.window.blit(square_img, mp)
2230 # Message in a bottle
2231 def message(self, string, pos = None, colour = None, font_size = 20):
2232 #print "Drawing message..."
2233 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2235 colour = pygame.Color(0,0,0)
2237 text = font.render(string, 1, colour)
2240 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
2241 s.fill(pygame.Color(128,128,128))
2243 tmp = self.window.get_size()
2246 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
2248 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
2251 rect = (pos[0], pos[1], text.get_width(), text.get_height())
2253 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
2254 self.window.blit(s, pos)
2255 self.window.blit(text, pos)
2257 pygame.display.flip()
2259 def getstr(self, prompt = None):
2260 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
2261 s.blit(self.window, (0,0))
2267 self.message(prompt)
2268 self.message(result, pos = (0, 1))
2271 for event in pygame.event.get():
2272 if event.type == pygame.QUIT:
2274 if event.type == pygame.KEYDOWN:
2275 if event.key == pygame.K_BACKSPACE:
2276 result = result[0:len(result)-1]
2277 self.window.blit(s, (0,0)) # Revert the display
2282 if event.unicode == '\r':
2285 result += str(event.unicode)
2290 # Function to pick a button
2291 def SelectButton(self, choices, prompt = None, font_size=20):
2293 #print "Select button called!"
2294 self.board.display_grid(self.window, self.grid_sz)
2296 self.message(prompt)
2297 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
2299 sz = self.window.get_size()
2302 for i in range(len(choices)):
2305 text = font.render(c, 1, pygame.Color(0,0,0))
2306 p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
2307 targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
2310 mp =pygame.mouse.get_pos()
2311 for i in range(len(choices)):
2313 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
2314 font_colour = pygame.Color(255,0,0)
2315 box_colour = pygame.Color(0,0,255,128)
2317 font_colour = pygame.Color(0,0,0)
2318 box_colour = pygame.Color(128,128,128)
2320 text = font.render(c, 1, font_colour)
2321 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
2323 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
2324 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
2325 self.window.blit(s, targets[i][0:2])
2328 pygame.display.flip()
2330 for event in pygame.event.get():
2331 if event.type == pygame.QUIT:
2333 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
2334 for i in range(len(targets)):
2336 if event.pos[0] > t[0] and event.pos[0] < t[2]:
2337 if event.pos[1] > t[1] and event.pos[1] < t[3]:
2339 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
2342 # Function to choose between dedicated server or normal play
2343 def SelectServer(self):
2345 choice = self.SelectButton(["Normal", "Join Eigenserver"],prompt="Game type?")
2348 choice = self.SelectButton(["progcomp.ucc", "other"], prompt="Address?")
2350 return "progcomp.ucc.asn.au"
2352 return self.getstr(prompt = "Enter address:")
2354 # Function to pick players in a nice GUI way
2355 def SelectPlayers(self, players = []):
2358 #print "SelectPlayers called"
2360 missing = ["white", "black"]
2362 missing.remove(p.colour)
2364 for colour in missing:
2367 choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
2369 players.append(HumanPlayer("human", colour))
2372 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2373 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2374 internal_agents.remove(('InternalAgent', InternalAgent))
2375 if len(internal_agents) > 0:
2376 choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
2381 agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
2382 players.append(agent[1](agent[0], colour))
2386 from tkFileDialog import askopenfilename
2387 root = Tkinter.Tk() # Need a root to make Tkinter behave
2388 root.withdraw() # Some sort of magic incantation
2389 path = askopenfilename(parent=root, initialdir="../agents",title=
2392 return self.SelectPlayers()
2393 players.append(make_player(path, colour))
2398 self.board.display_grid(self.window, self.grid_sz)
2399 pygame.display.flip()
2400 path = self.getstr(prompt = "Enter path:")
2405 return self.SelectPlayers()
2408 p = make_player(path, colour)
2410 self.board.display_grid(self.window, self.grid_sz)
2411 pygame.display.flip()
2412 self.message("Invalid path!")
2418 while address == "":
2419 self.board.display_grid(self.window, self.grid_sz)
2421 address = self.getstr(prompt = "Address? (leave blank for server)")
2428 map(int, address.split("."))
2430 self.board.display_grid(self.window, self.grid_sz)
2431 self.message("Invalid IPv4 address!")
2434 players.append(NetworkReceiver(colour, address))
2437 #print str(self) + ".SelectPlayers returns " + str(players)
2442 # --- graphics.py --- #
2443 def dedicated_server():
2452 log("Getting clients...")
2454 s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
2455 s.bind(("0.0.0.0", 4562))
2459 log("Got white player")
2461 args = ["python", "qchess.py", "--no-graphics", "@network::"+str(4600+2*len(games)), "@network::"+str(4600+2*len(games))]
2462 if len(log_files) != 0:
2465 args.append("--log")
2467 args.append("--log="+str(l.name)+"_"+str(gameID))
2469 g = subprocess.Popen(args, stdout=subprocess.PIPE)
2473 ss[0].send("white " + str(4600 + 2*(len(games)-1)))
2474 ss[0].shutdown(socket.SHUT_RD)
2480 log("Got black player")
2483 ss[0].send("black " + str(4600 + 2*(len(games)-1)))
2484 ss[0].shutdown(socket.SHUT_RD)
2487 s.shutdown(socket.SHUT_RDWR)
2491 while len(games) > max_games:
2492 #log("Too many games; waiting for game to finish...")
2493 ready = select.select(map(lambda e : e.stdout, games),[], [])
2495 s = r.readline().strip(" \r\n").split(" ")
2496 if s[0] == "white" or s[0] == "black":
2499 log("Game " + str(g) + " has finished")
2509 s.connect((addr, 4562))
2511 [colour,port] = s.recv(1024).strip(" \r\n").split(" ")
2513 #debug("Colour: " + colour + ", port: " + port)
2515 s.shutdown(socket.SHUT_RDWR)
2518 if colour == "white":
2519 p = subprocess.Popen(["python", "qchess.py", "@human", "@network:"+addr+":"+port])
2521 p = subprocess.Popen(["python", "qchess.py", "@network:"+addr+":"+port, "@human"])
2523 return 0# --- server.py --- #
2524 #!/usr/bin/python -u
2526 # Do you know what the -u does? It unbuffers stdin and stdout
2527 # I can't remember why, but last year things broke without that
2530 UCC::Progcomp 2013 Quantum Chess game
2531 @author Sam Moore [SZM] "matches"
2532 @copyright The University Computer Club, Incorporated
2533 (ie: You can copy it for not for profit purposes)
2536 # system python modules or whatever they are called
2542 sleep_timeout = None
2543 [game, graphics] = [None, None]
2545 def make_player(name, colour):
2547 if name[1:] == "human":
2548 return HumanPlayer(name, colour)
2549 s = name[1:].split(":")
2550 if s[0] == "network":
2561 if colour == "black":
2563 elif colour == "white":
2566 return NetworkPlayer(colour, Network((ip, port)), None)
2567 if s[0] == "internal":
2570 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
2571 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
2572 internal_agents.remove(('InternalAgent', InternalAgent))
2575 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
2576 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2579 for a in internal_agents:
2581 return a[1](name, colour)
2583 sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
2584 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
2588 return FifoPlayer(s[1], colour)
2590 return FifoPlayer(str(os.getpid())+"."+colour, colour)
2593 return ExternalAgent(name, colour)
2597 # The main function! It does the main stuff!
2600 # Apparently python will silently treat things as local unless you do this
2601 # Anyone who says "You should never use a global variable" can die in a fire
2606 global agent_timeout
2609 global graphics_enabled
2610 global always_reveal_states
2611 global sleep_timeout
2622 # Get the important warnings out of the way
2623 if platform.system() == "Windows":
2624 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
2625 if platform.release() == "Vista":
2626 sys.stderr.write(sys.argv[0] + " : God help you.\n")
2631 while i < len(argv)-1:
2635 p = make_player(arg, colour)
2636 if not isinstance(p, Player):
2637 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
2640 if colour == "white":
2642 elif colour == "black":
2645 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
2648 # Option parsing goes here
2649 if arg[1] == '-' and arg[2:] == "classical":
2651 elif arg[1] == '-' and arg[2:] == "quantum":
2653 elif arg[1] == '-' and arg[2:] == "reveal":
2654 always_reveal_states = True
2655 elif (arg[1] == '-' and arg[2:] == "graphics"):
2656 graphics_enabled = True
2657 elif (arg[1] == '-' and arg[2:] == "no-graphics"):
2658 graphics_enabled = False
2659 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
2660 # Load game from file
2661 if len(arg[2:].split("=")) == 1:
2662 src_file = sys.stdin
2664 f = arg[2:].split("=")[1]
2665 if f[0:7] == "http://":
2666 src_file = HttpReplay(f)
2668 src_file = FileReplay(f.split(":")[0])
2670 if len(f.split(":")) == 2:
2671 max_moves = int(f.split(":")[1])
2673 elif (arg[1] == '-' and arg[2:].split("=")[0] == "server"):
2674 #debug("Server: " + str(arg[2:]))
2675 if len(arg[2:].split("=")) <= 1:
2678 server_addr = arg[2:].split("=")[1]
2680 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
2682 if len(arg[2:].split("=")) == 1:
2683 log_files.append(LogFile(sys.stdout,""))
2685 f = arg[2:].split("=")[1]
2687 log_files.append(LogFile(sys.stdout, ""))
2689 log_files.append(ShortLog(f[1:]))
2691 log_files.append(LogFile(open(f, "w", 0), f))
2692 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
2694 if len(arg[2:].split("=")) == 1:
2697 turn_delay = float(arg[2:].split("=")[1])
2699 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
2701 if len(arg[2:].split("=")) == 1:
2704 agent_timeout = float(arg[2:].split("=")[1])
2705 elif (arg[1] == '-' and arg[2:].split("=")[0] == "blackout"):
2706 # Screen saver delay
2707 if len(arg[2:].split("=")) == 1:
2710 sleep_timeout = float(arg[2:].split("=")[1])
2712 elif (arg[1] == '-' and arg[2:] == "help"):
2714 os.system("less data/help.txt") # The best help function
2719 #debug("server_addr = " + str(server_addr))
2721 if server_addr != None:
2722 if server_addr == True:
2723 return dedicated_server()
2725 return client(server_addr)
2730 # Construct a GameThread! Make it global! Damn the consequences!
2732 if src_file != None:
2733 # Hack to stop ReplayThread from exiting
2734 #if len(players) == 0:
2735 # players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
2737 # Normally the ReplayThread exits if there are no players
2738 # TODO: Decide which behaviour to use, and fix it
2739 end = (len(players) == 0)
2741 players = [Player("dummy", "white"), Player("dummy", "black")]
2742 elif len(players) != 2:
2743 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2744 if graphics_enabled:
2745 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
2747 game = ReplayThread(players, src_file, end=end, max_moves=max_moves)
2749 board = Board(style)
2750 board.max_moves = max_moves
2751 game = GameThread(board, players)
2757 if graphics_enabled == True:
2759 graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
2761 graphics.sleep_timeout = sleep_timeout
2765 sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
2766 graphics_enabled = False
2768 # If there are no players listed, display a nice pretty menu
2769 if len(players) != 2:
2770 if graphics != None:
2772 server_addr = graphics.SelectServer()
2773 if server_addr != None:
2774 pygame.quit() # Time to say goodbye
2775 if server_addr == True:
2776 return dedicated_server()
2778 return client(server_addr)
2780 players = graphics.SelectPlayers(players)
2782 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
2785 # If there are still no players, quit
2786 if players == None or len(players) != 2:
2787 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
2792 if isinstance(p, NetworkPlayer):
2793 for i in range(len(old)):
2794 if old[i] == p or isinstance(old[i], NetworkPlayer):
2796 players[i] = NetworkPlayer(old[i].colour, p.network, old[i])
2800 if isinstance(p, NetworkPlayer):
2801 p.board = game.board
2802 if not p.network.connected:
2803 if not p.network.server:
2808 # If using windows, select won't work; use horrible TimeoutPlayer hack
2809 if agent_timeout > 0:
2810 if platform.system() == "Windows":
2811 for i in range(len(players)):
2812 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
2813 players[i] = TimeoutPlayer(players[i], agent_timeout)
2817 # InternalAgents get wrapped to an ExternalAgent when there is a timeout
2818 # This is not confusing at all.
2819 for i in range(len(players)):
2820 if isinstance(players[i], InternalAgent):
2821 players[i] = ExternalWrapper(players[i])
2829 log_init(game.board, players)
2832 if graphics != None:
2833 game.start() # This runs in a new thread
2839 error = game.error + graphics.error
2848 if src_file != None and src_file != sys.stdin:
2851 sys.stdout.write(game.final_result + "\n")
2862 # This is how python does a main() function...
2863 if __name__ == "__main__":
2866 retcode = main(sys.argv)
2867 except KeyboardInterrupt:
2868 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
2869 if isinstance(graphics, StoppableThread):
2871 graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
2873 if isinstance(game, StoppableThread):
2878 #except Exception, e:
2879 # sys.stderr.write(sys.argv[0] + " : " + e.message + "\n")
2894 # EOF - created from make on Thu May 16 23:54:28 WST 2013