3 # Do you know what the -u does? It unbuffers stdin and stdout
4 # I can't remember why, but last year things broke without that
7 UCC::Progcomp 2013 Quantum Chess game
8 @author Sam Moore [SZM] "matches"
9 @copyright The University Computer Club, Incorporated
10 (ie: You can copy it for not for profit purposes)
13 # system python modules or whatever they are called
20 [game, graphics] = [None, None]
22 def make_player(name, colour):
24 if name[1:] == "human":
25 return HumanPlayer(name, colour)
26 s = name[1:].split(":")
40 elif colour == "white":
43 return NetworkPlayer(colour, Network((ip, port)), None)
44 if s[0] == "internal":
47 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
48 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
49 internal_agents.remove(('InternalAgent', InternalAgent))
52 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
53 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
56 for a in internal_agents:
58 return a[1](name, colour)
60 sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
61 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
65 return FifoPlayer(s[1], colour)
67 return FifoPlayer(str(os.getpid())+"."+colour, colour)
70 return ExternalAgent(name, colour)
74 # The main function! It does the main stuff!
77 # Apparently python will silently treat things as local unless you do this
78 # Anyone who says "You should never use a global variable" can die in a fire
86 global graphics_enabled
87 global always_reveal_states
100 # Get the important warnings out of the way
101 if platform.system() == "Windows":
102 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
103 if platform.release() == "Vista":
104 sys.stderr.write(sys.argv[0] + " : God help you.\n")
109 while i < len(argv)-1:
113 p = make_player(arg, colour)
114 if not isinstance(p, Player):
115 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
118 if colour == "white":
120 elif colour == "black":
123 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
126 # Option parsing goes here
127 if arg[1] == '-' and arg[2:] == "classical":
129 elif arg[1] == '-' and arg[2:] == "quantum":
131 elif arg[1] == '-' and arg[2:] == "reveal":
132 always_reveal_states = True
133 elif (arg[1] == '-' and arg[2:] == "graphics"):
134 graphics_enabled = True
135 elif (arg[1] == '-' and arg[2:] == "no-graphics"):
136 graphics_enabled = False
137 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
138 # Load game from file
139 if len(arg[2:].split("=")) == 1:
142 f = arg[2:].split("=")[1]
143 if f[0:7] == "http://":
144 src_file = HttpReplay(f)
146 src_file = FileReplay(f.split(":")[0])
148 if len(f.split(":")) == 2:
149 max_moves = int(f.split(":")[1])
151 elif (arg[1] == '-' and arg[2:].split("=")[0] == "server"):
152 #debug("Server: " + str(arg[2:]))
153 if len(arg[2:].split("=")) <= 1:
156 server_addr = arg[2:].split("=")[1]
158 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
160 if len(arg[2:].split("=")) == 1:
161 log_files.append(LogFile(sys.stdout,""))
163 f = arg[2:].split("=")[1]
165 log_files.append(LogFile(sys.stdout, ""))
167 log_files.append(ShortLog(f[1:]))
169 log_files.append(LogFile(open(f, "w", 0), f))
170 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
172 if len(arg[2:].split("=")) == 1:
175 turn_delay = float(arg[2:].split("=")[1])
177 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
179 if len(arg[2:].split("=")) == 1:
182 agent_timeout = float(arg[2:].split("=")[1])
183 elif (arg[1] == '-' and arg[2:].split("=")[0] == "blackout"):
185 if len(arg[2:].split("=")) == 1:
188 sleep_timeout = float(arg[2:].split("=")[1])
189 elif (arg[1] == '-' and arg[2:] == "retry-illegal"):
190 retry_illegal = not retry_illegal
191 elif (arg[1] == '-' and arg[2:] == "help"):
193 os.system("less data/help.txt") # The best help function
198 #debug("server_addr = " + str(server_addr))
200 if server_addr != None:
201 if server_addr == True:
202 return dedicated_server()
205 sys.stderr.write("Only a single player may be provided when --server is used\n")
207 if len(players) == 1:
208 return client(server_addr, players[0].name)
210 return client(server_addr)
215 # Construct a GameThread! Make it global! Damn the consequences!
218 # Hack to stop ReplayThread from exiting
219 #if len(players) == 0:
220 # players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
222 # Normally the ReplayThread exits if there are no players
223 # TODO: Decide which behaviour to use, and fix it
224 end = (len(players) == 0)
226 players = [Player("dummy", "white"), Player("dummy", "black")]
227 elif len(players) != 2:
228 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
230 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
232 game = ReplayThread(players, src_file, end=end, max_moves=max_moves)
235 board.max_moves = max_moves
236 game = GameThread(board, players)
237 game.retry_illegal = retry_illegal
243 if graphics_enabled == True:
245 graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
247 graphics.sleep_timeout = sleep_timeout
251 sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
252 graphics_enabled = False
254 # If there are no players listed, display a nice pretty menu
255 if len(players) != 2:
258 server_addr = graphics.SelectServer()
259 if server_addr != None:
260 pygame.quit() # Time to say goodbye
261 if server_addr == True:
262 return dedicated_server()
264 return client(server_addr)
266 players = graphics.SelectPlayers(players)
268 sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
271 # If there are still no players, quit
272 if players == None or len(players) != 2:
273 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
278 if isinstance(p, NetworkPlayer):
279 for i in range(len(old)):
280 if old[i] == p or isinstance(old[i], NetworkPlayer):
282 players[i] = NetworkPlayer(old[i].colour, p.network, old[i])
286 if isinstance(p, NetworkPlayer):
288 if not p.network.connected:
289 if not p.network.server:
294 # If using windows, select won't work; use horrible TimeoutPlayer hack
295 if agent_timeout > 0:
296 if platform.system() == "Windows":
297 for i in range(len(players)):
298 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
299 players[i] = TimeoutPlayer(players[i], agent_timeout)
303 # InternalAgents get wrapped to an ExternalAgent when there is a timeout
304 # This is not confusing at all.
305 for i in range(len(players)):
306 if isinstance(players[i], InternalAgent):
307 players[i] = ExternalWrapper(players[i])
315 log_init(game.board, players)
319 game.start() # This runs in a new thread
325 error = game.error + graphics.error
334 if src_file != None and src_file != sys.stdin:
337 sys.stdout.write(game.final_result + "\n")
348 # This is how python does a main() function...
349 if __name__ == "__main__":
352 retcode = main(sys.argv)
353 except KeyboardInterrupt:
354 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
355 if isinstance(graphics, StoppableThread):
357 graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
359 if isinstance(game, StoppableThread):
364 #except Exception, e:
365 # sys.stderr.write(sys.argv[0] + " : " + e.message + "\n")