graphics.py 13.2 KB
Newer Older
Sam Moore's avatar
Sam Moore committed
1
graphics_enabled = True
Sam Moore's avatar
Sam Moore committed
2

Sam Moore's avatar
Sam Moore committed
3
4
try:
	import pygame
Sam Moore's avatar
Sam Moore committed
5
	os.environ["SDL_VIDEO_ALLOW_SCREENSAVER"] = "1"
Sam Moore's avatar
Sam Moore committed
6
7
8
except:
	graphics_enabled = False
	
Sam Moore's avatar
Sam Moore committed
9
import time
10
11


Sam Moore's avatar
Sam Moore committed
12
13
14
15
16
17
18
19
20
21

# A thread to make things pretty
class GraphicsThread(StoppableThread):
	def __init__(self, board, title = "UCC::Progcomp 2013 - QChess", grid_sz = [80,80]):
		StoppableThread.__init__(self)
		
		self.board = board
		pygame.init()
		self.window = pygame.display.set_mode((grid_sz[0] * w, grid_sz[1] * h))
		pygame.display.set_caption(title)
22
23
24

		#print "Initialised properly"
		
Sam Moore's avatar
Sam Moore committed
25
26
27
28
29
		self.grid_sz = grid_sz[:]
		self.state = {"select" : None, "dest" : None, "moves" : None, "overlay" : None, "coverage" : None}
		self.error = 0
		self.lock = threading.RLock()
		self.cond = threading.Condition()
Sam Moore's avatar
Sam Moore committed
30
31
		self.sleep_timeout = None
		self.last_event = time.time()
32
		self.blackout = False
Sam Moore's avatar
Sam Moore committed
33

34
35
		#print "Test font"
		pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 32).render("Hello", True,(0,0,0))
Sam Moore's avatar
Sam Moore committed
36

37
38
39
40
41
42
43
44
45
		#load_images()
		create_images(grid_sz)

		"""
		for c in images.keys():
			for p in images[c].keys():
				images[c][p] = images[c][p].convert(self.window)
				small_images[c][p] = small_images[c][p].convert(self.window)
		"""
Sam Moore's avatar
Sam Moore committed
46
47
48
49
50
51
52
53
54
55

		
	


	# On the run from the world
	def run(self):
		
		while not self.stopped():
			
Sam Moore's avatar
Sam Moore committed
56
57
58
59
			if self.sleep_timeout == None or (time.time() - self.last_event) < self.sleep_timeout:
			
				#print "Display grid"
				self.board.display_grid(window = self.window, grid_sz = self.grid_sz) # Draw the board
Sam Moore's avatar
Sam Moore committed
60

Sam Moore's avatar
Sam Moore committed
61
62
				#print "Display overlay"
				self.overlay()
Sam Moore's avatar
Sam Moore committed
63

Sam Moore's avatar
Sam Moore committed
64
65
				#print "Display pieces"
				self.board.display_pieces(window = self.window, grid_sz = self.grid_sz) # Draw the board		
66
				self.blackout = False
Sam Moore's avatar
Sam Moore committed
67
				
68
69
70
			elif pygame.mouse.get_focused() and not self.blackout:
				os.system("xset dpms force off")
				self.blackout = True
Sam Moore's avatar
Sam Moore committed
71
				self.window.fill((0,0,0))
Sam Moore's avatar
Sam Moore committed
72
73
74
75

			pygame.display.flip()

			for event in pygame.event.get():
Sam Moore's avatar
Sam Moore committed
76
				self.last_event = time.time()
77
				if event.type == pygame.QUIT or (event.type == pygame.KEYDOWN and event.key == pygame.K_q):
Sam Moore's avatar
Sam Moore committed
78
79
					if isinstance(game, GameThread):
						with game.lock:
Sam Moore's avatar
Sam Moore committed
80
81
82
83
							game.final_result = ""
							if game.state["turn"] != None:
								game.final_result = game.state["turn"].colour + " "
							game.final_result += "terminated"
Sam Moore's avatar
Sam Moore committed
84
85
86
87
88
						game.stop()
					self.stop()
					break
				elif event.type == pygame.MOUSEBUTTONDOWN:
					self.mouse_down(event)
Sam Moore's avatar
Sam Moore committed
89
					
Sam Moore's avatar
Sam Moore committed
90
				elif event.type == pygame.MOUSEBUTTONUP:
Sam Moore's avatar
Sam Moore committed
91
92
93
					self.mouse_up(event)			
				
				
Sam Moore's avatar
Sam Moore committed
94
					
95
  
Sam Moore's avatar
Sam Moore committed
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
				
								
						
						
		self.message("Game ends, result \""+str(game.final_result) + "\"")
		time.sleep(1)

		# Wake up anyone who is sleeping
		self.cond.acquire()
		self.cond.notify()
		self.cond.release()

		pygame.quit() # Time to say goodbye

	# Mouse release event handler
	def mouse_up(self, event):
		if event.button == 3:
			with self.lock:
				self.state["overlay"] = None
		elif event.button == 2:
			with self.lock:
				self.state["coverage"] = None	

	# Mouse click event handler
	def mouse_down(self, event):
		if event.button == 1:
			m = [event.pos[i] / self.grid_sz[i] for i in range(2)]
			if isinstance(game, GameThread):
				with game.lock:
					p = game.state["turn"]
			else:
					p = None
					
					
			if isinstance(p, HumanPlayer):
				with self.lock:
					s = self.board.grid[m[0]][m[1]]
					select = self.state["select"]
				if select == None:
					if s != None and s.colour != p.colour:
						self.message("Wrong colour") # Look at all this user friendliness!
						time.sleep(1)
						return
					# Notify human player of move
					self.cond.acquire()
					with self.lock:
						self.state["select"] = s
						self.state["dest"] = None
					self.cond.notify()
					self.cond.release()
					return

				if select == None:
					return
						
					
				if self.state["moves"] == None:
					return

				if not m in self.state["moves"]:
					self.message("Illegal Move") # I still think last year's mouse interface was adequate
					time.sleep(2)
					return
						
				with self.lock:
					if self.state["dest"] == None:
						self.cond.acquire()
						self.state["dest"] = m
						self.state["select"] = None
						self.state["moves"] = None
						self.cond.notify()
						self.cond.release()
		elif event.button == 3:
			m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
			if isinstance(game, GameThread):
				with game.lock:
					p = game.state["turn"]
			else:
				p = None
					
					
			if isinstance(p, HumanPlayer):
				with self.lock:
					self.state["overlay"] = self.board.probability_grid(self.board.grid[m[0]][m[1]])

		elif event.button == 2:
			m = [event.pos[i] / self.grid_sz[i] for i in range(len(event.pos))]
			if isinstance(game, GameThread):
				with game.lock:
					p = game.state["turn"]
			else:
				p = None
			
			
			if isinstance(p, HumanPlayer):
				with self.lock:
					self.state["coverage"] = self.board.coverage(m[0], m[1], None, self.state["select"])
				
	# Draw the overlay
	def overlay(self):

		square_img = pygame.Surface((self.grid_sz[0], self.grid_sz[1]),pygame.SRCALPHA) # A square image
		# Draw square over the selected piece
		with self.lock:
			select = self.state["select"]
		if select != None:
			mp = [self.grid_sz[i] * [select.x, select.y][i] for i in range(len(self.grid_sz))]
			square_img.fill(pygame.Color(0,255,0,64))
			self.window.blit(square_img, mp)
		# If a piece is selected, draw all reachable squares
		# (This quality user interface has been patented)
		with self.lock:
			m = self.state["moves"]
		if m != None:
			square_img.fill(pygame.Color(255,0,0,128)) # Draw them in blood red
			for move in m:
				mp = [self.grid_sz[i] * move[i] for i in range(2)]
				self.window.blit(square_img, mp)
		# If a piece is overlayed, show all squares that it has a probability to reach
		with self.lock:
			m = self.state["overlay"]
		if m != None:
			for x in range(w):
				for y in range(h):
					if m[x][y] > 0.0:
						mp = [self.grid_sz[i] * [x,y][i] for i in range(2)]
						square_img.fill(pygame.Color(255,0,255,int(m[x][y] * 128))) # Draw in purple
						self.window.blit(square_img, mp)
224
						font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
Sam Moore's avatar
Sam Moore committed
225
226
227
228
229
230
231
232
233
234
235
						text = font.render("{0:.2f}".format(round(m[x][y],2)), 1, pygame.Color(0,0,0))
						self.window.blit(text, mp)
				
		# If a square is selected, highlight all pieces that have a probability to reach it
		with self.lock:				
			m = self.state["coverage"]
		if m != None:
			for p in m:
				mp = [self.grid_sz[i] * [p.x,p.y][i] for i in range(2)]
				square_img.fill(pygame.Color(0,255,255, int(m[p] * 196))) # Draw in pale blue
				self.window.blit(square_img, mp)
236
				font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), 14)
Sam Moore's avatar
Sam Moore committed
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
				text = font.render("{0:.2f}".format(round(m[p],2)), 1, pygame.Color(0,0,0))
				self.window.blit(text, mp)
			# Draw a square where the mouse is
		# This also serves to indicate who's turn it is
		
		if isinstance(game, GameThread):
			with game.lock:
				turn = game.state["turn"]
		else:
			turn = None

		if isinstance(turn, HumanPlayer):
			mp = [self.grid_sz[i] * int(pygame.mouse.get_pos()[i] / self.grid_sz[i]) for i in range(2)]
			square_img.fill(pygame.Color(0,0,255,128))
			if turn.colour == "white":
				c = pygame.Color(255,255,255)
			else:
				c = pygame.Color(0,0,0)
			pygame.draw.rect(square_img, c, (0,0,self.grid_sz[0], self.grid_sz[1]), self.grid_sz[0]/10)
			self.window.blit(square_img, mp)

	# Message in a bottle
259
260
261
	def message(self, string, pos = None, colour = None, font_size = 20):
		#print "Drawing message..."
		font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
Sam Moore's avatar
Sam Moore committed
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
		if colour == None:
			colour = pygame.Color(0,0,0)
		
		text = font.render(string, 1, colour)
	

		s = pygame.Surface((text.get_width(), text.get_height()), pygame.SRCALPHA)
		s.fill(pygame.Color(128,128,128))

		tmp = self.window.get_size()

		if pos == None:
			pos = (tmp[0] / 2 - text.get_width() / 2, tmp[1] / 3 - text.get_height())
		else:
			pos = (pos[0]*text.get_width() + tmp[0] / 2 - text.get_width() / 2, pos[1]*text.get_height() + tmp[1] / 3 - text.get_height())
		

		rect = (pos[0], pos[1], text.get_width(), text.get_height())
	
		pygame.draw.rect(self.window, pygame.Color(0,0,0), pygame.Rect(rect), 1)
		self.window.blit(s, pos)
		self.window.blit(text, pos)

		pygame.display.flip()

	def getstr(self, prompt = None):
Sam Moore's avatar
Sam Moore committed
288
289
		s = pygame.Surface((self.window.get_width(), self.window.get_height()))
		s.blit(self.window, (0,0))
Sam Moore's avatar
Sam Moore committed
290
		result = ""
Sam Moore's avatar
Sam Moore committed
291

Sam Moore's avatar
Sam Moore committed
292
293
294
295
296
297
		while True:
			#print "LOOP"
			if prompt != None:
				self.message(prompt)
				self.message(result, pos = (0, 1))
	
Sam Moore's avatar
Sam Moore committed
298
			pygame.event.pump()
Sam Moore's avatar
Sam Moore committed
299
			for event in pygame.event.get():
Sam Moore's avatar
Sam Moore committed
300
301
				if event.type == pygame.QUIT:
					return None
Sam Moore's avatar
Sam Moore committed
302
				if event.type == pygame.KEYDOWN:
Sam Moore's avatar
Sam Moore committed
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
					if event.key == pygame.K_BACKSPACE:
						result = result[0:len(result)-1]
						self.window.blit(s, (0,0)) # Revert the display
						continue
				
						
					try:
						if event.unicode == '\r':
							return result
					
						result += str(event.unicode)
					except:
						continue


	# Function to pick a button
319
320
321
	def SelectButton(self, choices, prompt = None, font_size=20):

		#print "Select button called!"
Sam Moore's avatar
Sam Moore committed
322
323
324
		self.board.display_grid(self.window, self.grid_sz)
		if prompt != None:
			self.message(prompt)
325
		font = pygame.font.Font(os.path.join(os.path.curdir, "data", "DejaVuSans.ttf"), font_size)
Sam Moore's avatar
Sam Moore committed
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
		targets = []
		sz = self.window.get_size()

		
		for i in range(len(choices)):
			c = choices[i]
			
			text = font.render(c, 1, pygame.Color(0,0,0))
			p = (sz[0] / 2 - (1.5*text.get_width())/2, sz[1] / 2 +(i-1)*text.get_height()+(i*2))
			targets.append((p[0], p[1], p[0] + 1.5*text.get_width(), p[1] + text.get_height()))

		while True:
			mp =pygame.mouse.get_pos()
			for i in range(len(choices)):
				c = choices[i]
				if mp[0] > targets[i][0] and mp[0] < targets[i][2] and mp[1] > targets[i][1] and mp[1] < targets[i][3]:
					font_colour = pygame.Color(255,0,0)
					box_colour = pygame.Color(0,0,255,128)
				else:
					font_colour = pygame.Color(0,0,0)
					box_colour = pygame.Color(128,128,128)
				
				text = font.render(c, 1, font_colour)
				s = pygame.Surface((text.get_width()*1.5, text.get_height()), pygame.SRCALPHA)
				s.fill(box_colour)
				pygame.draw.rect(s, (0,0,0), (0,0,1.5*text.get_width(), text.get_height()), self.grid_sz[0]/10)
				s.blit(text, ((text.get_width()*1.5)/2 - text.get_width()/2 ,0))
				self.window.blit(s, targets[i][0:2])
				
	
			pygame.display.flip()

			for event in pygame.event.get():
				if event.type == pygame.QUIT:
					return None
				elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
					for i in range(len(targets)):
						t = targets[i]
						if event.pos[0] > t[0] and event.pos[0] < t[2]:
							if event.pos[1] > t[1] and event.pos[1] < t[3]:
								return i
						#print "Reject " + str(i) + str(event.pos) + " vs " + str(t)
		

370

Sam Moore's avatar
Sam Moore committed
371
372
373
374
	# Function to pick players in a nice GUI way
	def SelectPlayers(self, players = []):


375
		#print "SelectPlayers called"
Sam Moore's avatar
Sam Moore committed
376
377
378
379
380
381
382
383
		
		missing = ["white", "black"]
		for p in players:
			missing.remove(p.colour)

		for colour in missing:
			
			
384
			choice = self.SelectButton(["human", "agent", "network"],prompt = "Choose " + str(colour) + " player")
Sam Moore's avatar
Sam Moore committed
385
386
387
			if choice == 0:
				players.append(HumanPlayer("human", colour))
			elif choice == 1:
Sam Moore's avatar
Sam Moore committed
388
389
390
391
392
393
				import inspect
				internal_agents = inspect.getmembers(sys.modules[__name__], inspect.isclass)
				internal_agents = [x for x in internal_agents if issubclass(x[1], InternalAgent)]
				internal_agents.remove(('InternalAgent', InternalAgent)) 
				if len(internal_agents) > 0:
					choice2 = self.SelectButton(["internal", "external"], prompt="Type of agent")
394
				else:
Sam Moore's avatar
Sam Moore committed
395
					choice2 = 1
Sam Moore's avatar
Sam Moore committed
396

Sam Moore's avatar
Sam Moore committed
397
398
399
400
401
402
403
404
405
406
407
				if choice2 == 0:
					agent = internal_agents[self.SelectButton(map(lambda e : e[0], internal_agents), prompt="Choose internal agent")]
					players.append(agent[1](agent[0], colour))					
				elif choice2 == 1:
					try:
						import Tkinter
						from tkFileDialog import askopenfilename
						root = Tkinter.Tk() # Need a root to make Tkinter behave
						root.withdraw() # Some sort of magic incantation
						path = askopenfilename(parent=root, initialdir="../agents",title=
'Choose an agent.')
Sam Moore's avatar
Sam Moore committed
408
409
						if path == "":
							return self.SelectPlayers()
Sam Moore's avatar
Sam Moore committed
410
411
412
413
414
						players.append(make_player(path, colour))	
					except:
						
						p = None
						while p == None:
Sam Moore's avatar
Sam Moore committed
415
416
							self.board.display_grid(self.window, self.grid_sz)
							pygame.display.flip()
Sam Moore's avatar
Sam Moore committed
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
							path = self.getstr(prompt = "Enter path:")
							if path == None:
								return None
	
							if path == "":
								return self.SelectPlayers()
	
							try:
								p = make_player(path, colour)
							except:
								self.board.display_grid(self.window, self.grid_sz)
								pygame.display.flip()
								self.message("Invalid path!")
								time.sleep(1)
								p = None
						players.append(p)
433
			elif choice == 1:
Sam Moore's avatar
Sam Moore committed
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
				address = ""
				while address == "":
					self.board.display_grid(self.window, self.grid_sz)
					
					address = self.getstr(prompt = "Address? (leave blank for server)")
					if address == None:
						return None
					if address == "":
						address = None
						continue
					try:
						map(int, address.split("."))
					except:
						self.board.display_grid(self.window, self.grid_sz)
						self.message("Invalid IPv4 address!")
						address = ""

				players.append(NetworkReceiver(colour, address))
			else:
				return None
		#print str(self) + ".SelectPlayers returns " + str(players)
		return players