Make sure the board reflects the state BEFORE the move is made
[progcomp2013.git] / qchess / src / main.py
1 #!/usr/bin/python -u
2
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
5
6 """
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)
11 """
12
13 # system python modules or whatever they are called
14 import sys
15 import os
16 import time
17
18 turn_delay = 0.5
19 [game, graphics] = [None, None]
20
21 def make_player(name, colour):
22         if name[0] == '@':
23                 if name[1:] == "human":
24                         return HumanPlayer(name, colour)
25                 s = name[1:].split(":")
26                 if s[0] == "network":
27                         address = None
28                         if len(s) > 1:
29                                 address = s[1]
30                         return NetworkReceiver(colour, address)
31                 if s[0] == "internal":
32
33                         import inspect
34                         internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
35                         internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
36                         internal_agents.remove(('InternalAgent', InternalAgent)) 
37                         
38                         if len(s) != 2:
39                                 sys.stderr.write(sys.argv[0] + " : '@internal' should be followed by ':' and an agent name\n")
40                                 sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
41                                 return None
42
43                         for a in internal_agents:
44                                 if s[1] == a[0]:
45                                         return a[1](name, colour)
46                         
47                         sys.stderr.write(sys.argv[0] + " : Can't find an internal agent matching \"" + s[1] + "\"\n")
48                         sys.stderr.write(sys.argv[0] + " : Choices are: " + str(map(lambda e : e[0], internal_agents)) + "\n")
49                         return None
50                         
51
52         else:
53                 return ExternalAgent(name, colour)
54                         
55
56
57 # The main function! It does the main stuff!
58 def main(argv):
59
60         # Apparently python will silently treat things as local unless you do this
61         # Anyone who says "You should never use a global variable" can die in a fire
62         global game
63         global graphics
64         
65         global turn_delay
66         global agent_timeout
67         global log_file
68         global src_file
69         global graphics_enabled
70         global always_reveal_states
71
72         max_lines = None
73         src_file = None
74         
75         style = "quantum"
76         colour = "white"
77
78         # Get the important warnings out of the way
79         if platform.system() == "Windows":
80                 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
81                 if platform.release() == "Vista":
82                         sys.stderr.write(sys.argv[0] + " : God help you.\n")
83         
84
85         players = []
86         i = 0
87         while i < len(argv)-1:
88                 i += 1
89                 arg = argv[i]
90                 if arg[0] != '-':
91                         p = make_player(arg, colour)
92                         if not isinstance(p, Player):
93                                 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
94                                 return 100
95                         players.append(p)
96                         if colour == "white":
97                                 colour = "black"
98                         elif colour == "black":
99                                 pass
100                         else:
101                                 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
102                         continue
103
104                 # Option parsing goes here
105                 if arg[1] == '-' and arg[2:] == "classical":
106                         style = "classical"
107                 elif arg[1] == '-' and arg[2:] == "quantum":
108                         style = "quantum"
109                 elif arg[1] == '-' and arg[2:] == "reveal":
110                         always_reveal_states = True
111                 elif (arg[1] == '-' and arg[2:] == "graphics"):
112                         graphics_enabled = not graphics_enabled
113                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
114                         # Load game from file
115                         if len(arg[2:].split("=")) == 1:
116                                 src_file = sys.stdin
117                         else:
118                                 f = arg[2:].split("=")[1]
119                                 if f[0] == '@':
120                                         src_file = HttpReplay("http://" + f.split(":")[0][1:])
121                                 else:
122                                         src_file = open(f.split(":")[0], "r", 0)
123
124                                 if len(f.split(":")) == 2:
125                                         max_lines = int(f.split(":")[1])
126
127                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
128                         # Log file
129                         if len(arg[2:].split("=")) == 1:
130                                 log_file = sys.stdout
131                         else:
132                                 f = arg[2:].split("=")[1]
133                                 if f[0] == '@':
134                                         log_file = HttpLog(f[1:])
135                                 else:
136                                         log_file = LogFile(f)
137                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
138                         # Delay
139                         if len(arg[2:].split("=")) == 1:
140                                 turn_delay = 0
141                         else:
142                                 turn_delay = float(arg[2:].split("=")[1])
143
144                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
145                         # Timeout
146                         if len(arg[2:].split("=")) == 1:
147                                 agent_timeout = -1
148                         else:
149                                 agent_timeout = float(arg[2:].split("=")[1])
150                                 
151                 elif (arg[1] == '-' and arg[2:] == "help"):
152                         # Help
153                         os.system("less data/help.txt") # The best help function
154                         return 0
155
156
157         # Create the board
158         
159         # Construct a GameThread! Make it global! Damn the consequences!
160                         
161         if src_file != None:
162                 # Hack to stop ReplayThread from exiting
163                 #if len(players) == 0:
164                 #       players = [HumanPlayer("dummy", "white"), HumanPlayer("dummy", "black")]
165
166                 # Normally the ReplayThread exits if there are no players
167                 # TODO: Decide which behaviour to use, and fix it
168                 end = (len(players) == 0)
169                 if end:
170                         players = [Player("dummy", "white"), Player("dummy", "black")]
171                 elif len(players) != 2:
172                         sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
173                         if graphics_enabled:
174                                 sys.stderr.write(sys.argv[0] + " : (You won't get a GUI, because --file was used, and the author is lazy)\n")
175                         return 44
176                 game = ReplayThread(players, src_file, end=end, max_lines=max_lines)
177         else:
178                 board = Board(style)
179                 game = GameThread(board, players) 
180
181
182
183         # Initialise GUI
184         if graphics_enabled == True:
185                 try:
186                         graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
187
188                 except Exception,e:
189                         graphics = None
190                         sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
191                         graphics_enabled = False
192
193         # If there are no players listed, display a nice pretty menu
194         if len(players) != 2:
195                 if graphics != None:
196                         players = graphics.SelectPlayers(players)
197                 else:
198                         sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
199                         return 44
200
201         # If there are still no players, quit
202         if players == None or len(players) != 2:
203                 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
204                 return 45
205
206
207         # Wrap NetworkSender players around original players if necessary
208         for i in range(len(players)):
209                 if isinstance(players[i], NetworkReceiver):
210                         players[i].board = board # Network players need direct access to the board
211                         for j in range(len(players)):
212                                 if j == i:
213                                         continue
214                                 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
215                                         continue
216                                 players[j] = NetworkSender(players[j], players[i].address)
217                                 players[j].board = board
218
219         # Connect the networked players
220         for p in players:
221                 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
222                         if graphics != None:
223                                 graphics.board.display_grid(graphics.window, graphics.grid_sz)
224                                 graphics.message("Connecting to " + p.colour + " player...")
225                         p.connect()
226
227         
228         # If using windows, select won't work; use horrible TimeoutPlayer hack
229         if agent_timeout > 0:
230                 if platform.system() == "Windows":
231                         for i in range(len(players)):
232                                 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
233                                         players[i] = TimeoutPlayer(players[i], agent_timeout)
234
235                 else:
236                         warned = False
237                         # InternalAgents get wrapped to an ExternalAgent when there is a timeout
238                         # This is not confusing at all.
239                         for i in range(len(players)):
240                                 if isinstance(players[i], InternalAgent):
241                                                 players[i] = ExternalWrapper(players[i])
242
243
244                 
245
246
247
248
249         log_init(game.board, players)
250         
251         
252         if graphics != None:
253                 game.start() # This runs in a new thread
254                 graphics.run()
255                 if game.is_alive():
256                         game.join()
257         
258
259                 error = game.error + graphics.error
260         else:
261                 game.run()
262                 error = game.error
263         
264
265         if log_file != None and log_file != sys.stdout:
266                 log_file.write("# EOF\n")
267                 log_file.close()
268
269         if src_file != None and src_file != sys.stdin:
270                 src_file.close()
271
272         return error
273
274 # This is how python does a main() function...
275 if __name__ == "__main__":
276         try:
277                 sys.exit(main(sys.argv))
278         except KeyboardInterrupt:
279                 sys.stderr.write(sys.argv[0] + " : Got KeyboardInterrupt. Stopping everything\n")
280                 if isinstance(graphics, StoppableThread):
281                         graphics.stop()
282                         graphics.run() # Will clean up graphics because it is stopped, not run it (a bit dodgy)
283
284                 if isinstance(game, StoppableThread):
285                         game.stop()
286                         if game.is_alive():
287                                 game.join()
288
289                 sys.exit(102)
290

UCC git Repository :: git.ucc.asn.au