Progress?
[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
71
72         src_file = None
73         
74         style = "quantum"
75         colour = "white"
76
77         # Get the important warnings out of the way
78         if platform.system() == "Windows":
79                 sys.stderr.write(sys.argv[0] + " : Warning - You are using " + platform.system() + "\n")
80                 if platform.release() == "Vista":
81                         sys.stderr.write(sys.argv[0] + " : God help you.\n")
82         
83
84         players = []
85         i = 0
86         while i < len(argv)-1:
87                 i += 1
88                 arg = argv[i]
89                 if arg[0] != '-':
90                         p = make_player(arg, colour)
91                         if not isinstance(p, Player):
92                                 sys.stderr.write(sys.argv[0] + " : Fatal error creating " + colour + " player\n")
93                                 return 100
94                         players.append(p)
95                         if colour == "white":
96                                 colour = "black"
97                         elif colour == "black":
98                                 pass
99                         else:
100                                 sys.stderr.write(sys.argv[0] + " : Too many players (max 2)\n")
101                         continue
102
103                 # Option parsing goes here
104                 if arg[1] == '-' and arg[2:] == "classical":
105                         style = "classical"
106                 elif arg[1] == '-' and arg[2:] == "quantum":
107                         style = "quantum"
108                 elif (arg[1] == '-' and arg[2:] == "graphics"):
109                         graphics_enabled = not graphics_enabled
110                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "file"):
111                         # Load game from file
112                         if len(arg[2:].split("=")) == 1:
113                                 src_file = sys.stdin
114                         else:
115                                 src_file = open(arg[2:].split("=")[1])
116                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "log"):
117                         # Log file
118                         if len(arg[2:].split("=")) == 1:
119                                 log_file = sys.stdout
120                         else:
121                                 log_file = open(arg[2:].split("=")[1], "w")
122                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "delay"):
123                         # Delay
124                         if len(arg[2:].split("=")) == 1:
125                                 turn_delay = 0
126                         else:
127                                 turn_delay = float(arg[2:].split("=")[1])
128
129                 elif (arg[1] == '-' and arg[2:].split("=")[0] == "timeout"):
130                         # Timeout
131                         if len(arg[2:].split("=")) == 1:
132                                 agent_timeout = -1
133                         else:
134                                 agent_timeout = float(arg[2:].split("=")[1])
135                                 
136                 elif (arg[1] == '-' and arg[2:] == "help"):
137                         # Help
138                         os.system("less data/help.txt") # The best help function
139                         return 0
140
141
142         # Create the board
143         
144         # Construct a GameThread! Make it global! Damn the consequences!
145                         
146         if src_file != None:
147                 if len(players) == 0:
148                         players = [Player("dummy", "white"), Player("dummy", "black")]
149                 game = ReplayThread(players, src_file)
150         else:
151                 board = Board(style)
152                 game = GameThread(board, players) 
153
154
155
156         # Initialise GUI
157         if graphics_enabled == True:
158                 try:
159                         graphics = GraphicsThread(game.board, grid_sz = [64,64]) # Construct a GraphicsThread!
160
161                 except Exception,e:
162                         graphics = None
163                         sys.stderr.write(sys.argv[0] + " : Got exception trying to initialise graphics\n"+str(e.message)+"\nDisabled graphics\n")
164                         graphics_enabled = False
165
166         # If there are no players listed, display a nice pretty menu
167         if len(players) != 2:
168                 if graphics != None:
169                         players = graphics.SelectPlayers(players)
170                 else:
171                         sys.stderr.write(sys.argv[0] + " : Usage " + sys.argv[0] + " white black\n")
172                         return 44
173
174         # If there are still no players, quit
175         if players == None or len(players) != 2:
176                 sys.stderr.write(sys.argv[0] + " : Graphics window closed before players chosen\n")
177                 return 45
178
179
180         # Wrap NetworkSender players around original players if necessary
181         for i in range(len(players)):
182                 if isinstance(players[i], NetworkReceiver):
183                         players[i].board = board # Network players need direct access to the board
184                         for j in range(len(players)):
185                                 if j == i:
186                                         continue
187                                 if isinstance(players[j], NetworkSender) or isinstance(players[j], NetworkReceiver):
188                                         continue
189                                 players[j] = NetworkSender(players[j], players[i].address)
190                                 players[j].board = board
191
192         # Connect the networked players
193         for p in players:
194                 if isinstance(p, NetworkSender) or isinstance(p, NetworkReceiver):
195                         if graphics != None:
196                                 graphics.board.display_grid(graphics.window, graphics.grid_sz)
197                                 graphics.message("Connecting to " + p.colour + " player...")
198                         p.connect()
199
200         
201         # If using windows, select won't work; use horrible TimeoutPlayer hack
202         if agent_timeout > 0:
203                 if platform.system() == "Windows":
204                         for i in range(len(players)):
205                                 if isinstance(players[i], ExternalAgent) or isinstance(players[i], InternalAgent):
206                                         players[i] = TimeoutPlayer(players[i], agent_timeout)
207
208                 else:
209                         warned = False
210                         # InternalAgents get wrapped to an ExternalAgent when there is a timeout
211                         # This is not confusing at all.
212                         for i in range(len(players)):
213                                 if isinstance(players[i], InternalAgent):
214                                                 players[i] = ExternalWrapper(players[i])
215
216
217                 
218
219
220
221
222         
223         if graphics != None:
224                 game.start() # This runs in a new thread
225                 graphics.run()
226                 game.join()
227                 error = game.error + graphics.error
228         else:
229                 game.run()
230                 error = game.error
231
232         if log_file != None and log_file != sys.stdout:
233                 log_file.close()
234
235         if src_file != None and src_file != sys.stdin:
236                 src_file.close()
237
238         return error
239
240 # This is how python does a main() function...
241 if __name__ == "__main__":
242         sys.exit(main(sys.argv))

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