1 graphics_enabled = True
5 graphics_enabled = False
11 # A thread to make things pretty
12 class GraphicsThread(StoppableThread):
13 def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
14 StoppableThread.__init__(self)
18 self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
19 pygame.display.set_caption(title)
21 #print "Initialised properly"
23 self.grid_sz = grid_sz[:]
24 self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
26 self.lock = threading.RLock()
27 self.cond = threading.Condition()
28 self.sleep_timeout = None
29 self.last_event = time.time()
32 pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
35 create_images(grid_sz)
38 for c in images.keys():
39 for p in images[c].keys():
40 images[c][p] = images[c][p].convert(self.window)
41 small_images[c][p] = small_images[c][p].convert(self.window)
48 # On the run from the world
51 while not self.stopped():
53 if self.sleep_timeout == None or (time.time() - self.last_event) < self.sleep_timeout:
56 self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
58 #print "Display overlay"
61 #print "Display pieces"
62 self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board
65 self.window.fill((0,0,0))
69 for event in pygame.event.get():
70 self.last_event = time.time()
71 if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_q):
72 if isinstance(game, GameThread):
74 game.final_result = ""
75 if game.state["turn"] != None:
76 game.final_result = game.state["turn"].colour + " "
77 game.final_result += "terminated"
81 elif event.type == pygame.MOUSEBUTTONDOWN:
82 self.mouse_down(event)
84 elif event.type == pygame.MOUSEBUTTONUP:
94 self.message("Game ends, result \""+str(game.final_result) + "\"")
97 # Wake up anyone who is sleeping
102 pygame.quit() # Time to say goodbye
104 # Mouse release event handler
105 def mouse_up(self, event):
106 if event.button == 3:
108 self.state["overlay"] = None
109 elif event.button == 2:
111 self.state["coverage"] = None
113 # Mouse click event handler
114 def mouse_down(self, event):
115 if event.button == 1:
116 m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
117 if isinstance(game, GameThread):
119 p = game.state["turn"]
124 if isinstance(p, HumanPlayer):
126 s = self.board.grid[m[0]][m[1]]
127 select = self.state["select"]
129 if s != None and s.colour != p.colour:
130 self.message("Wrong colour") # Look at all this user friendliness!
133 # Notify human player of move
136 self.state["select"] = s
137 self.state["dest"] = None
146 if self.state["moves"] == None:
149 if not m in self.state["moves"]:
150 self.message("Illegal Move") # I still think last year's mouse interface was adequate
155 if self.state["dest"] == None:
157 self.state["dest"] = m
158 self.state["select"] = None
159 self.state["moves"] = None
162 elif event.button == 3:
163 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
164 if isinstance(game, GameThread):
166 p = game.state["turn"]
171 if isinstance(p, HumanPlayer):
173 self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])
175 elif event.button == 2:
176 m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
177 if isinstance(game, GameThread):
179 p = game.state["turn"]
184 if isinstance(p, HumanPlayer):
186 self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
191 square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
192 # Draw square over the selected piece
194 select = self.state["select"]
196 mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
197 square_img.fill(pygame.Color(0,255,0,64))
198 self.window.blit(square_img, mp)
199 # If a piece is selected, draw all reachable squares
200 # (This quality user interface has been patented)
202 m = self.state["moves"]
204 square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
206 mp = [self.grid_sz[i] * move[i] for i in range(2)]
207 self.window.blit(square_img, mp)
208 # If a piece is overlayed, show all squares that it has a probability to reach
210 m = self.state["overlay"]
215 mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
216 square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
217 self.window.blit(square_img, mp)
218 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
219 text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
220 self.window.blit(text, mp)
222 # If a square is selected, highlight all pieces that have a probability to reach it
224 m = self.state["coverage"]
227 mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
228 square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
229 self.window.blit(square_img, mp)
230 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
231 text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
232 self.window.blit(text, mp)
233 # Draw a square where the mouse is
234 # This also serves to indicate who's turn it is
236 if isinstance(game, GameThread):
238 turn = game.state["turn"]
242 if isinstance(turn, HumanPlayer):
243 mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
244 square_img.fill(pygame.Color(0,0,255,128))
245 if turn.colour == "white":
246 c = pygame.Color(255,255,255)
248 c = pygame.Color(0,0,0)
249 pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
250 self.window.blit(square_img, mp)
252 # Message in a bottle
253 def message(self, string, pos = None, colour = None, font_size = 20):
254 #print "Drawing message..."
255 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
257 colour = pygame.Color(0,0,0)
259 text = font.render(string, 1, colour)
262 s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
263 s.fill(pygame.Color(128,128,128))
265 tmp = self.window.get_size()
268 pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
270 pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
273 rect = (pos[0], pos[1], text.get_width(), text.get_height())
275 pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
276 self.window.blit(s, pos)
277 self.window.blit(text, pos)
279 pygame.display.flip()
281 def getstr(self, prompt = None):
282 s = pygame.Surface((self.window.get_width(), self.window.get_height()))
283 s.blit(self.window, (0,0))
290 self.message(result, pos = (0, 1))
293 for event in pygame.event.get():
294 if event.type == pygame.QUIT:
296 if event.type == pygame.KEYDOWN:
297 if event.key == pygame.K_BACKSPACE:
298 result = result[0:len(result)-1]
299 self.window.blit(s, (0,0)) # Revert the display
304 if event.unicode == '\r':
307 result += str(event.unicode)
312 # Function to pick a button
313 def SelectButton(self, choices, prompt = None, font_size=20):
315 #print "Select button called!"
316 self.board.display_grid(self.window, self.grid_sz)
319 font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
321 sz = self.window.get_size()
324 for i in range(len(choices)):
327 text = font.render(c, 1, pygame.Color(0,0,0))
328 p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
329 targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))
332 mp =pygame.mouse.get_pos()
333 for i in range(len(choices)):
335 if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
336 font_colour = pygame.Color(255,0,0)
337 box_colour = pygame.Color(0,0,255,128)
339 font_colour = pygame.Color(0,0,0)
340 box_colour = pygame.Color(128,128,128)
342 text = font.render(c, 1, font_colour)
343 s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
345 pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
346 s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
347 self.window.blit(s, targets[i][0:2])
350 pygame.display.flip()
352 for event in pygame.event.get():
353 if event.type == pygame.QUIT:
355 elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
356 for i in range(len(targets)):
358 if event.pos[0] > t[0] and event.pos[0] < t[2]:
359 if event.pos[1] > t[1] and event.pos[1] < t[3]:
361 #print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
364 # Function to pick players in a nice GUI way
365 def SelectPlayers(self, players = []):
368 #print "SelectPlayers called"
370 missing = ["white", "black"]
372 missing.remove(p.colour)
374 for colour in missing:
377 choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
379 players.append(HumanPlayer("human", colour))
382 internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
383 internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
384 internal_agents.remove(('InternalAgent', InternalAgent))
385 if len(internal_agents) > 0:
386 choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
391 agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
392 players.append(agent[1](agent[0], colour))
396 from tkFileDialog import askopenfilename
397 root = Tkinter.Tk() # Need a root to make Tkinter behave
398 root.withdraw() # Some sort of magic incantation
399 path = askopenfilename(parent=root, initialdir="../agents",title=
402 return self.SelectPlayers()
403 players.append(make_player(path, colour))
408 self.board.display_grid(self.window, self.grid_sz)
409 pygame.display.flip()
410 path = self.getstr(prompt = "Enter path:")
415 return self.SelectPlayers()
418 p = make_player(path, colour)
420 self.board.display_grid(self.window, self.grid_sz)
421 pygame.display.flip()
422 self.message("Invalid path!")
429 self.board.display_grid(self.window, self.grid_sz)
431 address = self.getstr(prompt = "Address? (leave blank for server)")
438 map(int, address.split("."))
440 self.board.display_grid(self.window, self.grid_sz)
441 self.message("Invalid IPv4 address!")
444 players.append(NetworkReceiver(colour, address))
447 #print str(self) + ".SelectPlayers returns " + str(players)