qchess.py 73.3 KB
Newer Older
Sam Moore's avatar
Sam Moore committed
1
#!/usr/bin/python -u
Sam Moore's avatar
Sam Moore committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import random

# I know using non-abreviated strings is inefficient, but this is python, who cares?
# Oh, yeah, this stores the number of pieces of each type in a normal chess game
piece_types = {"pawn" : 8, "bishop" : 2, "knight" : 2, "rook" : 2, "queen" : 1, "king" : 1, "unknown" : 0}

# Class to represent a quantum chess piece
class Piece():
	def __init__(self, colour, x, y, types):
		self.colour = colour # Colour (string) either "white" or "black"
		self.x = x # x coordinate (0 - 8), none of this fancy 'a', 'b' shit here
		self.y = y # y coordinate (0 - 8)
		self.types = types # List of possible types the piece can be (should just be two)
		self.current_type = "unknown" # Current type
		self.choice = -1 # Index of the current type in self.types (-1 = unknown type)
		
Sam Moore's avatar
Sam Moore committed
18
		
Sam Moore's avatar
Sam Moore committed
19
		self.last_state = None
Sam Moore's avatar
Sam Moore committed
20
		
Sam Moore's avatar
Sam Moore committed
21
		self.move_pattern = None
Sam Moore's avatar
Sam Moore committed
22
		self.coverage = None
Sam Moore's avatar
Sam Moore committed
23
		self.possible_moves = None
Sam Moore's avatar
Sam Moore committed
24
25
26
27
28
29
30
31
32
		

	def init_from_copy(self, c):
		self.colour = c.colour
		self.x = c.x
		self.y = c.y
		self.types = c.types[:]
		self.current_type = c.current_type
		self.choice = c.choice
Sam Moore's avatar
Sam Moore committed
33
		
Sam Moore's avatar
Sam Moore committed
34
35
36
37
38
39
40
		self.last_state = None
		self.move_pattern = None

	

	# Make a string for the piece (used for debug)
	def __str__(self):
41
		return str(self.colour) + " " + str(self.current_type) + " " + str(self.types) + " at " + str(self.x) + ","+str(self.y)  
Sam Moore's avatar
Sam Moore committed
42
43

	# Draw the piece in a pygame surface
Sam Moore's avatar
Sam Moore committed
44
	def draw(self, window, grid_sz = [80,80], style="quantum"):
Sam Moore's avatar
Sam Moore committed
45
46
47
48

		# First draw the image corresponding to self.current_type
		img = images[self.colour][self.current_type]
		rect = img.get_rect()
Sam Moore's avatar
Sam Moore committed
49
50
51
52
		if style == "classical":
			offset = [-rect.width/2, -rect.height/2]
		else:
			offset = [-rect.width/2,-3*rect.height/4] 
Sam Moore's avatar
Sam Moore committed
53
54
55
		window.blit(img, (self.x * grid_sz[0] + grid_sz[0]/2 + offset[0], self.y * grid_sz[1] + grid_sz[1]/2 + offset[1]))
		
		
Sam Moore's avatar
Sam Moore committed
56
57
58
		if style == "classical":
			return

Sam Moore's avatar
Sam Moore committed
59
60
		# Draw the two possible types underneath the current_type image
		for i in range(len(self.types)):
Sam Moore's avatar
Sam Moore committed
61
			if always_reveal_states == True or self.types[i][0] != '?':
Sam Moore's avatar
Sam Moore committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
				img = small_images[self.colour][self.types[i]]
			else:
				img = small_images[self.colour]["unknown"] # If the type hasn't been revealed, show a placeholder

			
			rect = img.get_rect()
			offset = [-rect.width/2,-rect.height/2] 
			
			if i == 0:
				target = (self.x * grid_sz[0] + grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])				
			else:
				target = (self.x * grid_sz[0] + 4*grid_sz[0]/5 + offset[0], self.y * grid_sz[1] + 3*grid_sz[1]/4 + offset[1])				
				
			window.blit(img, target) # Blit shit
	
	# Collapses the wave function!		
	def select(self):
Sam Moore's avatar
Sam Moore committed
79
		if self.current_type == "unknown" or not self.choice in [0,1]:
Sam Moore's avatar
Sam Moore committed
80
			self.choice = random.randint(0,1)
Sam Moore's avatar
Sam Moore committed
81
82
			if self.types[self.choice][0] == '?':
				self.types[self.choice] = self.types[self.choice][1:]
Sam Moore's avatar
Sam Moore committed
83
84
85
86
87
88
89
			self.current_type = self.types[self.choice]
		return self.choice

	# Uncollapses (?) the wave function!
	def deselect(self):
		#print "Deselect called"
		if (self.x + self.y) % 2 != 0:
Sam Moore's avatar
Sam Moore committed
90
			if (self.types[0] != self.types[1]) or (self.types[0][0] == '?' or self.types[1][0] == '?'):
Sam Moore's avatar
Sam Moore committed
91
92
93
94
95
96
97
				self.current_type = "unknown"
				self.choice = -1
			else:
				self.choice = 0 # Both the two types are the same

	# The sad moment when you realise that you do not understand anything about a subject you studied for 4 years...
# --- piece.py --- #
Sam Moore's avatar
Sam Moore committed
98
99
[w,h] = [8,8] # Width and height of board(s)

100
101
always_reveal_states = False

Sam Moore's avatar
Sam Moore committed
102
103
104
105
106
107
108
109
110
111
112
# Class to represent a quantum chess board
class Board():
	# Initialise; if master=True then the secondary piece types are assigned
	#	Otherwise, they are left as unknown
	#	So you can use this class in Agent programs, and fill in the types as they are revealed
	def __init__(self, style="agent"):
		self.style = style
		self.pieces = {"white" : [], "black" : []}
		self.grid = [[None] * w for _ in range(h)] # 2D List (you can get arrays in python, somehow, but they scare me)
		self.unrevealed_types = {"white" : piece_types.copy(), "black" : piece_types.copy()}
		self.king = {"white" : None, "black" : None} # We need to keep track of the king, because he is important
Sam Moore's avatar
Sam Moore committed
113
114
		self.max_moves = None
		self.moves = 0
Sam Moore's avatar
Sam Moore committed
115
		self.move_stack = []
Sam Moore's avatar
Sam Moore committed
116
117
118
		for c in ["black", "white"]:
			del self.unrevealed_types[c]["unknown"]

119
120
121
		if style == "empty":
			return

Sam Moore's avatar
Sam Moore committed
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
		# Add all the pieces with known primary types
		for i in range(0, 2):
			
			s = ["black", "white"][i]
			c = self.pieces[s]
			y = [0, h-1][i]

			c.append(Piece(s, 0, y, ["rook"]))
			c.append(Piece(s, 1, y, ["knight"]))
			c.append(Piece(s, 2, y, ["bishop"]))
			k = Piece(s, 3, y, ["king", "king"]) # There can only be one ruler!
			k.current_type = "king"
			self.king[s] = k
			c.append(k)
			c.append(Piece(s, 4, y, ["queen"])) # Apparently he may have multiple wives though.
			c.append(Piece(s, 5, y, ["bishop"]))
			c.append(Piece(s, 6, y, ["knight"]))
			c.append(Piece(s, 7, y, ["rook"]))
			
			if y == 0: 
				y += 1 
			else: 
				y -= 1
			
			# Lots of pawn
			for x in range(0, w):
				c.append(Piece(s, x, y, ["pawn"]))

			types_left = {}
			types_left.update(piece_types)
			del types_left["king"] # We don't want one of these randomly appearing (although it might make things interesting...)
			del types_left["unknown"] # We certainly don't want these!
			for piece in c:
				# Add to grid
				self.grid[piece.x][piece.y] = piece 

				if len(piece.types) > 1:
					continue				
				if style == "agent": # Assign placeholder "unknown" secondary type
					piece.types.append("unknown")
					continue

				elif style == "quantum":
					# The master allocates the secondary types
					choice = types_left.keys()[random.randint(0, len(types_left.keys())-1)]
					types_left[choice] -= 1
					if types_left[choice] <= 0:
						del types_left[choice]
Sam Moore's avatar
Sam Moore committed
170
					piece.types.append('?' + choice)
Sam Moore's avatar
Sam Moore committed
171
172
173
174
175
176
177
178
179
180
181
182
				elif style == "classical":
					piece.types.append(piece.types[0])
					piece.current_type = piece.types[0]
					piece.choice = 0

	def clone(self):
		newboard = Board(master = False)
		newpieces = newboard.pieces["white"] + newboard.pieces["black"]
		mypieces = self.pieces["white"] + self.pieces["black"]

		for i in range(len(mypieces)):
			newpieces[i].init_from_copy(mypieces[i])
Sam Moore's avatar
Sam Moore committed
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
	
	# Reset the board from a string
	def reset_board(self, s):
		self.pieces = {"white" : [], "black" : []}
		self.king = {"white" : None, "black" : None}
		self.grid = [[None] * w for _ in range(h)]
		for x in range(w):
			for y in range(h):
				self.grid[x][y] = None

		for line in s.split("\n"):
			if line == "":
				continue
			if line[0] == "#":
				continue

			tokens = line.split(" ")
			[x, y] = map(int, tokens[len(tokens)-1].split(","))
			current_type = tokens[1]
			types = map(lambda e : e.strip(" '[],"), line.split('[')[1].split(']')[0].split(','))
			
			target = Piece(tokens[0], x, y, types)
			target.current_type = current_type
			
			try:
				target.choice = types.index(current_type)
			except:
				target.choice = -1

			self.pieces[tokens[0]].append(target)
			if target.current_type == "king":
				self.king[tokens[0]] = target

			self.grid[x][y] = target
Sam Moore's avatar
Sam Moore committed
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
			

	def display_grid(self, window = None, grid_sz = [80,80]):
		if window == None:
			return # I was considering implementing a text only display, then I thought "Fuck that"

		# The indentation is getting seriously out of hand...
		for x in range(0, w):
			for y in range(0, h):
				if (x + y) % 2 == 0:
					c = pygame.Color(200,200,200)
				else:
					c = pygame.Color(64,64,64)
				pygame.draw.rect(window, c, (x*grid_sz[0], y*grid_sz[1], (x+1)*grid_sz[0], (y+1)*grid_sz[1]))

	def display_pieces(self, window = None, grid_sz = [80,80]):
		if window == None:
			return
		for p in self.pieces["white"] + self.pieces["black"]:
Sam Moore's avatar
Sam Moore committed
236
			p.draw(window, grid_sz, self.style)
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
259
260
261
262
263

	# Draw the board in a pygame window
	def display(self, window = None):
		self.display_grid(window)
		self.display_pieces(window)
		

		

	def verify(self):
		for x in range(w):
			for y in range(h):
				if self.grid[x][y] == None:
					continue
				if (self.grid[x][y].x != x or self.grid[x][y].y != y):
					raise Exception(sys.argv[0] + ": MISMATCH " + str(self.grid[x][y]) + " should be at " + str(x) + "," + str(y))

	# Select a piece on the board (colour is the colour of whoever is doing the selecting)
	def select(self, x,y, colour=None):
		if not self.on_board(x, y): # Get on board everyone!
			raise Exception("BOUNDS")

		piece = self.grid[x][y]
		if piece == None:
			raise Exception("EMPTY")

		if colour != None and piece.colour != colour:
Sam Moore's avatar
Sam Moore committed
264
			raise Exception("COLOUR " + str(piece.colour) + " not " + str(colour))
Sam Moore's avatar
Sam Moore committed
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285

		# I'm not quite sure why I made this return a string, but screw logical design
		return str(x) + " " + str(y) + " " + str(piece.select()) + " " + str(piece.current_type)


	# Update the board when a piece has been selected
	# "type" is apparently reserved, so I'll use "state"
	def update_select(self, x, y, type_index, state):
		piece = self.grid[x][y]
		if piece.types[type_index] == "unknown":
			if not state in self.unrevealed_types[piece.colour].keys():
				raise Exception("SANITY: Too many " + piece.colour + " " + state + "s")
			self.unrevealed_types[piece.colour][state] -= 1
			if self.unrevealed_types[piece.colour][state] <= 0:
				del self.unrevealed_types[piece.colour][state]

		piece.types[type_index] = state
		piece.current_type = state

		if len(self.possible_moves(piece)) <= 0:
			piece.deselect() # Piece can't move; deselect it
Sam Moore's avatar
Sam Moore committed
286
287
288
			
		# Piece needs to recalculate moves
		piece.possible_moves = None
Sam Moore's avatar
Sam Moore committed
289
290
291
		
	# Update the board when a piece has been moved
	def update_move(self, x, y, x2, y2):
Sam Moore's avatar
Sam Moore committed
292
				
Sam Moore's avatar
Sam Moore committed
293
		piece = self.grid[x][y]
Sam Moore's avatar
Sam Moore committed
294
295
296
		#print "Moving " + str(x) + "," + str(y) + " to " + str(x2) + "," + str(y2) + "; possible_moves are " + str(self.possible_moves(piece))
		
		if not [x2,y2] in self.possible_moves(piece):
297
			raise Exception("ILLEGAL move " + str(x2)+","+str(y2))
Sam Moore's avatar
Sam Moore committed
298
		
Sam Moore's avatar
Sam Moore committed
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
		self.grid[x][y] = None
		taken = self.grid[x2][y2]
		if taken != None:
			if taken.current_type == "king":
				self.king[taken.colour] = None
			self.pieces[taken.colour].remove(taken)
		self.grid[x2][y2] = piece
		piece.x = x2
		piece.y = y2

		# If the piece is a pawn, and it reaches the final row, it becomes a queen
		# I know you are supposed to get a choice
		# But that would be effort
		if piece.current_type == "pawn" and ((piece.colour == "white" and piece.y == 0) or (piece.colour == "black" and piece.y == h-1)):
			if self.style == "classical":
				piece.types[0] = "queen"
				piece.types[1] = "queen"
			else:
				piece.types[piece.choice] = "queen"
			piece.current_type = "queen"

		piece.deselect() # Uncollapse (?) the wavefunction!
Sam Moore's avatar
Sam Moore committed
321
		self.moves += 1
Sam Moore's avatar
Sam Moore committed
322
323
324
325
326
		
		# All other pieces need to recalculate moves
		for p in self.pieces["white"] + self.pieces["black"]:
			p.possible_moves = None
		
Sam Moore's avatar
Sam Moore committed
327
		#self.verify()	
Sam Moore's avatar
Sam Moore committed
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383

	# Update the board from a string
	# Guesses what to do based on the format of the string
	def update(self, result):
		#print "Update called with \"" + str(result) + "\""
		# String always starts with 'x y'
		try:
			s = result.split(" ")
			[x,y] = map(int, s[0:2])	
		except:
			raise Exception("GIBBERISH \""+ str(result) + "\"") # Raise expectations

		piece = self.grid[x][y]
		if piece == None:
			raise Exception("EMPTY")

		# If a piece is being moved, the third token is '->'
		# We could get away with just using four integers, but that wouldn't look as cool
		if "->" in s:
			# Last two tokens are the destination
			try:
				[x2,y2] = map(int, s[3:])
			except:
				raise Exception("GIBBERISH \"" + str(result) + "\"") # Raise the alarm

			# Move the piece (take opponent if possible)
			self.update_move(x, y, x2, y2)
			
		else:
			# Otherwise we will just assume a piece has been selected
			try:
				type_index = int(s[2]) # We need to know which of the two types the piece is in; that's the third token
				state = s[3] # The last token is a string identifying the type
			except:
				raise Exception("GIBBERISH \"" + result + "\"") # Throw a hissy fit

			# Select the piece
			self.update_select(x, y, type_index, state)

		return result

	# Gets each piece that could reach the given square and the probability that it could reach that square	
	# Will include allied pieces that defend the attacker
	def coverage(self, x, y, colour = None, reject_allied = True):
		result = {}
		
		if colour == None:
			pieces = self.pieces["white"] + self.pieces["black"]
		else:
			pieces = self.pieces[colour]

		for p in pieces:
			prob = self.probability_grid(p, reject_allied)[x][y]
			if prob > 0:
				result.update({p : prob})
		
Sam Moore's avatar
Sam Moore committed
384
		#self.verify()
Sam Moore's avatar
Sam Moore committed
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
		return result


		


	# Associates each square with a probability that the piece could move into it
	# Look, I'm doing all the hard work for you here...
	def probability_grid(self, p, reject_allied = True):
		
		result = [[0.0] * w for _ in range(h)]
		if not isinstance(p, Piece):
			return result

		if p.current_type != "unknown":
			#sys.stderr.write(sys.argv[0] + ": " + str(p) + " moves " + str(self.possible_moves(p, reject_allied)) + "\n")
			for point in self.possible_moves(p, reject_allied):
				result[point[0]][point[1]] = 1.0
			return result
		
		
		for i in range(len(p.types)):
			t = p.types[i]
			prob = 0.5
Sam Moore's avatar
Sam Moore committed
409
			if t == "unknown" or p.types[i][0] == '?':
Sam Moore's avatar
Sam Moore committed
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
				total_types = 0
				for t2 in self.unrevealed_types[p.colour].keys():
					total_types += self.unrevealed_types[p.colour][t2]
				
				for t2 in self.unrevealed_types[p.colour].keys():
					prob2 = float(self.unrevealed_types[p.colour][t2]) / float(total_types)
					p.current_type = t2
					for point in self.possible_moves(p, reject_allied):
						result[point[0]][point[1]] += prob2 * prob
				
			else:
				p.current_type = t
				for point in self.possible_moves(p, reject_allied):
					result[point[0]][point[1]] += prob
		
Sam Moore's avatar
Sam Moore committed
425
		#self.verify()
Sam Moore's avatar
Sam Moore committed
426
427
428
429
430
431
432
433
434
435
436
		p.current_type = "unknown"
		return result

	def prob_is_type(self, p, state):
		prob = 0.5
		result = 0
		for i in range(len(p.types)):
			t = p.types[i]
			if t == state:
				result += prob
				continue	
Sam Moore's avatar
Sam Moore committed
437
			if t == "unknown" or p.types[i][0] == '?':
Sam Moore's avatar
Sam Moore committed
438
439
440
441
442
443
444
445
446
447
448
449
450
				total_prob = 0
				for t2 in self.unrevealed_types[p.colour].keys():
					total_prob += self.unrevealed_types[p.colour][t2]
				for t2 in self.unrevealed_types[p.colour].keys():
					if t2 == state:
						result += prob * float(self.unrevealed_types[p.colour][t2]) / float(total_prob)
				


	# Get all squares that the piece could move into
	# This is probably inefficient, but I looked at some sample chess games and they seem to actually do things this way
	# reject_allied indicates whether squares occupied by allied pieces will be removed
	# (set to false to check for defense)
Sam Moore's avatar
Sam Moore committed
451
	def possible_moves(self, p, reject_allied = True, state=None):
Sam Moore's avatar
Sam Moore committed
452
		if p == None:
Sam Moore's avatar
Sam Moore committed
453
454
455
456
457
458
459
460
461
			raise Exception("SANITY: No piece")
		
		
		
		if state != None and state != p.current_type:
			old_type = p.current_type
			p.current_type = state
			result = self.possible_moves(p, reject_allied, state=None)
			p.current_type = old_type
Sam Moore's avatar
Sam Moore committed
462
			return result
Sam Moore's avatar
Sam Moore committed
463
464
465
466
467
468
469
		
		if p.possible_moves != None:
			return p.possible_moves
		
		
		result = []
		
Sam Moore's avatar
Sam Moore committed
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540

		
		if p.current_type == "unknown":
			raise Exception("SANITY: Piece state unknown")
			# The below commented out code causes things to break badly
			#for t in p.types:
			#	if t == "unknown":
			#		continue
			#	p.current_type = t
			#	result += self.possible_moves(p)						
			#p.current_type = "unknown"
			#return result

		if p.current_type == "king":
			result = [[p.x-1,p.y],[p.x+1,p.y],[p.x,p.y-1],[p.x,p.y+1], [p.x-1,p.y-1],[p.x-1,p.y+1],[p.x+1,p.y-1],[p.x+1,p.y+1]]
		elif p.current_type == "queen":
			for d in [[-1,0],[1,0],[0,-1],[0,1],[-1,-1],[-1,1],[1,-1],[1,1]]:
				result += self.scan(p.x, p.y, d[0], d[1])
		elif p.current_type == "bishop":
			for d in [[-1,-1],[-1,1],[1,-1],[1,1]]: # There's a reason why bishops move diagonally
				result += self.scan(p.x, p.y, d[0], d[1])
		elif p.current_type == "rook":
			for d in [[-1,0],[1,0],[0,-1],[0,1]]:
				result += self.scan(p.x, p.y, d[0], d[1])
		elif p.current_type == "knight":
			# I would use two lines, but I'm not sure how python likes that
			result = [[p.x-2, p.y-1], [p.x-2, p.y+1], [p.x+2, p.y-1], [p.x+2,p.y+1], [p.x-1,p.y-2], [p.x-1, p.y+2],[p.x+1,p.y-2],[p.x+1,p.y+2]]
		elif p.current_type == "pawn":
			if p.colour == "white":
				
				# Pawn can't move forward into occupied square
				if self.on_board(p.x, p.y-1) and self.grid[p.x][p.y-1] == None:
					result = [[p.x,p.y-1]]
				for f in [[p.x-1,p.y-1],[p.x+1,p.y-1]]:
					if not self.on_board(f[0], f[1]):
						continue
					if self.grid[f[0]][f[1]] != None:  # Pawn can take diagonally
						result.append(f)
				if p.y == h-2:
					# Slightly embarrassing if the pawn jumps over someone on its first move...
					if self.grid[p.x][p.y-1] == None and self.grid[p.x][p.y-2] == None:
						result.append([p.x, p.y-2])
			else:
				# Vice versa for the black pawn
				if self.on_board(p.x, p.y+1) and self.grid[p.x][p.y+1] == None:
					result = [[p.x,p.y+1]]

				for f in [[p.x-1,p.y+1],[p.x+1,p.y+1]]:
					if not self.on_board(f[0], f[1]):
						continue
					if self.grid[f[0]][f[1]] != None:
						#sys.stderr.write(sys.argv[0] + " : "+str(p) + " can take " + str(self.grid[f[0]][f[1]]) + "\n")
						result.append(f)
				if p.y == 1:
					if self.grid[p.x][p.y+1] == None and self.grid[p.x][p.y+2] == None:
						result.append([p.x, p.y+2])

			#sys.stderr.write(sys.argv[0] + " : possible_moves for " + str(p) + " " + str(result) + "\n")

		# Remove illegal moves
		# Note: The result[:] creates a copy of result, so that the result.remove calls don't fuck things up
		for point in result[:]: 

			if (point[0] < 0 or point[0] >= w) or (point[1] < 0 or point[1] >= h):
				result.remove(point) # Remove locations outside the board
				continue
			g = self.grid[point[0]][point[1]]
			
			if g != None and (g.colour == p.colour and reject_allied == True):
				result.remove(point) # Remove allied pieces
		
Sam Moore's avatar
Sam Moore committed
541
542
543
		#self.verify()
		
		p.possible_moves = result
Sam Moore's avatar
Sam Moore committed
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
		return result


	# Scans in a direction until it hits a piece, returns all squares in the line
	# (includes the final square (which contains a piece), but not the original square)
	def scan(self, x, y, vx, vy):
		p = []
			
		xx = x
		yy = y
		while True:
			xx += vx
			yy += vy
			if not self.on_board(xx, yy):
				break
			if not [xx,yy] in p:
				p.append([xx, yy])
			g = self.grid[xx][yy]
			if g != None:
				return p	
					
		return p

Sam Moore's avatar
Sam Moore committed
567
568
569
570
571
572
573
574
575
576
577
578
579
	# Returns "white", "black" or "DRAW" if the game should end
	def end_condition(self):
		if self.king["white"] == None:
			if self.king["black"] == None:
				return "DRAW" # This shouldn't happen
			return "black"
		elif self.king["black"] == None:
			return "white"
		elif len(self.pieces["white"]) == 1 and len(self.pieces["black"]) == 1:
			return "DRAW"
		elif self.max_moves != None and self.moves > self.max_moves:
			return "DRAW"
		return None
Sam Moore's avatar
Sam Moore committed
580
581
582
583
584


	# I typed the full statement about 30 times before writing this function...
	def on_board(self, x, y):
		return (x >= 0 and x < w) and (y >= 0 and y < h)
Sam Moore's avatar
Sam Moore committed
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
	
	# Pushes a move temporarily
	def push_move(self, piece, x, y):
		target = self.grid[x][y]
		self.move_stack.append([piece, target, piece.x, piece.y, x, y])
		[piece.x, piece.y] = [x, y]
		self.grid[x][y] = piece
		self.grid[piece.x][piece.y] = None
		
		for p in self.pieces["white"] + self.pieces["black"]:
			p.possible_moves = None
		
	# Restore move
	def pop_move(self):
		#print str(self.move_stack)
		[piece, target, x1, y1, x2, y2] = self.move_stack[len(self.move_stack)-1]
		self.move_stack = self.move_stack[:-1]
		piece.x = x1
		piece.y = y1
		self.grid[x1][y1] = piece
		if target != None:
			target.x = x2
			target.y = y2
		self.grid[x2][y2] = target
		
		for p in self.pieces["white"] + self.pieces["black"]:
				p.possible_moves = None
		
Sam Moore's avatar
Sam Moore committed
613
# --- board.py --- #
Sam Moore's avatar
Sam Moore committed
614
import subprocess
Sam Moore's avatar
Sam Moore committed
615
616
import select
import platform
617
import re
618

Sam Moore's avatar
Sam Moore committed
619
620
agent_timeout = -1.0 # Timeout in seconds for AI players to make moves
			# WARNING: Won't work for windows based operating systems
Sam Moore's avatar
Sam Moore committed
621

Sam Moore's avatar
Sam Moore committed
622
623
if platform.system() == "Windows":
	agent_timeout = -1 # Hence this
Sam Moore's avatar
Sam Moore committed
624

Sam Moore's avatar
Sam Moore committed
625
626
627
628
629
# A player who can't play
class Player():
	def __init__(self, name, colour):
		self.name = name
		self.colour = colour
Sam Moore's avatar
Sam Moore committed
630

Sam Moore's avatar
Sam Moore committed
631
632
633
	def update(self, result):
		pass

Sam Moore's avatar
Sam Moore committed
634
635
636
	def reset_board(self, s):
		pass

Sam Moore's avatar
Sam Moore committed
637
# Player that runs from another process
Sam Moore's avatar
Sam Moore committed
638
class ExternalAgent(Player):
Sam Moore's avatar
Sam Moore committed
639
640


Sam Moore's avatar
Sam Moore committed
641
642
	def __init__(self, name, colour):
		Player.__init__(self, name, colour)
Sam Moore's avatar
Sam Moore committed
643
		self.p = subprocess.Popen(name,bufsize=0,stdin=subprocess.PIPE, stdout=subprocess.PIPE, shell=True,universal_newlines=True)
Sam Moore's avatar
Sam Moore committed
644
645
646
647
648
649
650
651
652
		
		self.send_message(colour)

	def send_message(self, s):
		if agent_timeout > 0.0:
			ready = select.select([], [self.p.stdin], [], agent_timeout)[1]
		else:
			ready = [self.p.stdin]
		if self.p.stdin in ready:
Sam Moore's avatar
Sam Moore committed
653
			#sys.stderr.write("Writing \'" + s + "\' to " + str(self.p) + "\n")
Sam Moore's avatar
Sam Moore committed
654
655
656
657
658
			try:
				self.p.stdin.write(s + "\n")
			except:
				raise Exception("UNRESPONSIVE")
		else:
Sam Moore's avatar
Sam Moore committed
659
			raise Exception("TIMEOUT")
Sam Moore's avatar
Sam Moore committed
660
661
662
663
664
665
666

	def get_response(self):
		if agent_timeout > 0.0:
			ready = select.select([self.p.stdout], [], [], agent_timeout)[0]
		else:
			ready = [self.p.stdout]
		if self.p.stdout in ready:
Sam Moore's avatar
Sam Moore committed
667
			#sys.stderr.write("Reading from " + str(self.p) + " 's stdout...\n")
Sam Moore's avatar
Sam Moore committed
668
			try:
669
				result = self.p.stdout.readline().strip(" \t\r\n")
Sam Moore's avatar
Sam Moore committed
670
671
				#sys.stderr.write("Read \'" + result + "\' from " + str(self.p) + "\n")
				return result
Sam Moore's avatar
Sam Moore committed
672
673
674
			except: # Exception, e:
				raise Exception("UNRESPONSIVE")
		else:
Sam Moore's avatar
Sam Moore committed
675
			raise Exception("TIMEOUT")
Sam Moore's avatar
Sam Moore committed
676

Sam Moore's avatar
Sam Moore committed
677
	def select(self):
Sam Moore's avatar
Sam Moore committed
678
679
680

		self.send_message("SELECTION?")
		line = self.get_response()
Sam Moore's avatar
Sam Moore committed
681
682
		
		try:
683
684
			m = re.match("\s*(\d+)\s+(\d+)\s*", line)
			result = map(int, [m.group(1), m.group(2)])
Sam Moore's avatar
Sam Moore committed
685
686
687
		except:
			raise Exception("GIBBERISH \"" + str(line) + "\"")
		return result
Sam Moore's avatar
Sam Moore committed
688

Sam Moore's avatar
Sam Moore committed
689
690
	def update(self, result):
		#print "Update " + str(result) + " called for AgentPlayer"
Sam Moore's avatar
Sam Moore committed
691
692
		self.send_message(result)

Sam Moore's avatar
Sam Moore committed
693

Sam Moore's avatar
Sam Moore committed
694
695
	def get_move(self):
		
Sam Moore's avatar
Sam Moore committed
696
697
698
		self.send_message("MOVE?")
		line = self.get_response()
		
Sam Moore's avatar
Sam Moore committed
699
		try:
700
701
702
			m = re.match("\s*(\d+)\s+(\d+)\s*", line)
			result = map(int, [m.group(1), m.group(2)])

Sam Moore's avatar
Sam Moore committed
703
704
705
		except:
			raise Exception("GIBBERISH \"" + str(line) + "\"")
		return result
Sam Moore's avatar
Sam Moore committed
706

Sam Moore's avatar
Sam Moore committed
707
708
709
710
711
712
	def reset_board(self, s):
		self.send_message("BOARD")
		for line in s.split("\n"):
			self.send_message(line.strip(" \r\n"))
		self.send_message("END BOARD")

Sam Moore's avatar
Sam Moore committed
713
714
	def quit(self, final_result):
		try:
Sam Moore's avatar
Sam Moore committed
715
			self.send_message("QUIT " + final_result)
Sam Moore's avatar
Sam Moore committed
716
717
		except:
			self.p.kill()
Sam Moore's avatar
Sam Moore committed
718

Sam Moore's avatar
Sam Moore committed
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
# So you want to be a player here?
class HumanPlayer(Player):
	def __init__(self, name, colour):
		Player.__init__(self, name, colour)
		
	# Select your preferred account
	def select(self):
		if isinstance(graphics, GraphicsThread):
			# Basically, we let the graphics thread do some shit and then return that information to the game thread
			graphics.cond.acquire()
			# We wait for the graphics thread to select a piece
			while graphics.stopped() == False and graphics.state["select"] == None:
				graphics.cond.wait() # The difference between humans and machines is that humans sleep
			select = graphics.state["select"]
			
			
			graphics.cond.release()
			if graphics.stopped():
				return [-1,-1]
			return [select.x, select.y]
		else:
			# Since I don't display the board in this case, I'm not sure why I filled it in...
			while True:
				sys.stdout.write("SELECTION?\n")
				try:
					p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
				except:
					sys.stderr.write("ILLEGAL GIBBERISH\n")
					continue
	# It's your move captain
	def get_move(self):
		if isinstance(graphics, GraphicsThread):
			graphics.cond.acquire()
			while graphics.stopped() == False and graphics.state["dest"] == None:
				graphics.cond.wait()
			graphics.cond.release()
			
			return graphics.state["dest"]
		else:
Sam Moore's avatar
Sam Moore committed
758

Sam Moore's avatar
Sam Moore committed
759
760
761
762
763
764
765
			while True:
				sys.stdout.write("MOVE?\n")
				try:
					p = map(int, sys.stdin.readline().strip("\r\n ").split(" "))
				except:
					sys.stderr.write("ILLEGAL GIBBERISH\n")
					continue
Sam Moore's avatar
Sam Moore committed
766

Sam Moore's avatar
Sam Moore committed
767
768
	# Are you sure you want to quit?
	def quit(self, final_result):
Sam Moore's avatar
Sam Moore committed
769
770
		if graphics == None:		
			sys.stdout.write("QUIT " + final_result + "\n")
Sam Moore's avatar
Sam Moore committed
771

Sam Moore's avatar
Sam Moore committed
772
773
774
775
776
777
	# Completely useless function
	def update(self, result):
		if isinstance(graphics, GraphicsThread):
			pass
		else:
			sys.stdout.write(result + "\n")	
Sam Moore's avatar
Sam Moore committed
778
779


Sam Moore's avatar
Sam Moore committed
780
781
# Default internal player (makes random moves)
class InternalAgent(Player):
Sam Moore's avatar
Sam Moore committed
782
783
784
785
786
787
	def __init__(self, name, colour):
		Player.__init__(self, name, colour)
		self.choice = None

		self.board = Board(style = "agent")

Sam Moore's avatar
Sam Moore committed
788
789
790
791
792
793
794


	def update(self, result):
		
		self.board.update(result)
		self.board.verify()

Sam Moore's avatar
Sam Moore committed
795
796
797
	def reset_board(self, s):
		self.board.reset_board(s)

Sam Moore's avatar
Sam Moore committed
798
799
800
801
802
803
804
	def quit(self, final_result):
		pass

class AgentRandom(InternalAgent):
	def __init__(self, name, colour):
		InternalAgent.__init__(self, name, colour)

Sam Moore's avatar
Sam Moore committed
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
	def select(self):
		while True:
			self.choice = self.board.pieces[self.colour][random.randint(0, len(self.board.pieces[self.colour])-1)]
			all_moves = []
			# Check that the piece has some possibility to move
			tmp = self.choice.current_type
			if tmp == "unknown": # For unknown pieces, try both types
				for t in self.choice.types:
					if t == "unknown":
						continue
					self.choice.current_type = t
					all_moves += self.board.possible_moves(self.choice)
			else:
				all_moves = self.board.possible_moves(self.choice)
			self.choice.current_type = tmp
			if len(all_moves) > 0:
				break
		return [self.choice.x, self.choice.y]

	def get_move(self):
		moves = self.board.possible_moves(self.choice)
		move = moves[random.randint(0, len(moves)-1)]
		return move


Sam Moore's avatar
Sam Moore committed
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
# Terrible, terrible hacks

def run_agent(agent):
	#sys.stderr.write(sys.argv[0] + " : Running agent " + str(agent) + "\n")
	while True:
		line = sys.stdin.readline().strip(" \r\n")
		if line == "SELECTION?":
			#sys.stderr.write(sys.argv[0] + " : Make selection\n")
			[x,y] = agent.select() # Gets your agent's selection
			#sys.stderr.write(sys.argv[0] + " : Selection was " + str(agent.choice) + "\n")
			sys.stdout.write(str(x) + " " + str(y) + "\n")				
		elif line == "MOVE?":
			#sys.stderr.write(sys.argv[0] + " : Make move\n")
			[x,y] = agent.get_move() # Gets your agent's move
			sys.stdout.write(str(x) + " " + str(y) + "\n")
		elif line.split(" ")[0] == "QUIT":
			#sys.stderr.write(sys.argv[0] + " : Quitting\n")
			agent.quit(" ".join(line.split(" ")[1:])) # Quits the game
			break
Sam Moore's avatar
Sam Moore committed
849
850
851
852
853
854
855
856
		elif line.split(" ")[0] == "BOARD":
			s = ""
			line = sys.stdin.readline().strip(" \r\n")
			while line != "END BOARD":
				s += line + "\n"
				line = sys.stdin.readline().strip(" \r\n")
			agent.board.reset_board(s)
			
Sam Moore's avatar
Sam Moore committed
857
858
859
860
861
862
		else:
			agent.update(line) # Updates agent.board
	return 0


# Sort of works?
863

Sam Moore's avatar
Sam Moore committed
864
865
class ExternalWrapper(ExternalAgent):
	def __init__(self, agent):
866
		run = "python -u -c \"import sys;import os;from qchess import *;agent = " + agent.__class__.__name__ + "('" + agent.name + "','"+agent.colour+"');sys.stdin.readline();sys.exit(run_agent(agent))\""
Sam Moore's avatar
Sam Moore committed
867
868
869
870
		# str(run)
		ExternalAgent.__init__(self, run, agent.colour)

	
871

Sam Moore's avatar
Sam Moore committed
872
# --- player.py --- #
Sam Moore's avatar
Sam Moore committed
873
874
875
# A sample agent


Sam Moore's avatar
Sam Moore committed
876
class AgentBishop(AgentRandom): # Inherits from AgentRandom (in qchess)
Sam Moore's avatar
Sam Moore committed
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
	def __init__(self, name, colour):
		InternalAgent.__init__(self, name, colour)
		self.value = {"pawn" : 1, "bishop" : 3, "knight" : 3, "rook" : 5, "queen" : 9, "king" : 100, "unknown" : 4}

		self.aggression = 2.0 # Multiplier for scoring due to aggressive actions
		self.defence = 1.0 # Multiplier for scoring due to defensive actions
		
		self.depth = 0 # Current depth
		self.max_depth = 2 # Recurse this many times (for some reason, makes more mistakes when this is increased???)
		self.recurse_for = -1 # Recurse for the best few moves each times (less than 0 = all moves)

		for p in self.board.pieces["white"] + self.board.pieces["black"]:
			p.last_moves = None
			p.selected_moves = None

		

	def get_value(self, piece):
		if piece == None:
			return 0.0
		return float(self.value[piece.types[0]] + self.value[piece.types[1]]) / 2.0
		
	# Score possible moves for the piece
	
	def prioritise_moves(self, piece):

		#sys.stderr.write(sys.argv[0] + " : " + str(self) + " prioritise called for " + str(piece) + "\n")

		
		
		grid = self.board.probability_grid(piece)
		#sys.stderr.write("\t Probability grid " + str(grid) + "\n")
		moves = []
		for x in range(w):
			for y in range(h):
				if grid[x][y] < 0.3: # Throw out moves with < 30% probability
					#sys.stderr.write("\tReject " + str(x) + "," + str(y) + " (" + str(grid[x][y]) + ")\n")
					continue

				target = self.board.grid[x][y]
			
				
				
				
				# Get total probability that the move is protected
Sam Moore's avatar
Sam Moore committed
922
923
924
				self.board.push_move(piece, x, y)
				

Sam Moore's avatar
Sam Moore committed
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
				
				defenders = self.board.coverage(x, y, piece.colour, reject_allied = False)
				d_prob = 0.0
				for d in defenders.keys():
					d_prob += defenders[d]
				if len(defenders.keys()) > 0:
					d_prob /= float(len(defenders.keys()))

				if (d_prob > 1.0):
					d_prob = 1.0

				# Get total probability that the move is threatened
				attackers = self.board.coverage(x, y, opponent(piece.colour), reject_allied = False)
				a_prob = 0.0
				for a in attackers.keys():
					a_prob += attackers[a]
				if len(attackers.keys()) > 0:
					a_prob /= float(len(attackers.keys()))

				if (a_prob > 1.0):
					a_prob = 1.0

Sam Moore's avatar
Sam Moore committed
947
948
				self.board.pop_move()
				
Sam Moore's avatar
Sam Moore committed
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035

				
				# Score of the move
				value = self.aggression * (1.0 + d_prob) * self.get_value(target) - self.defence * (1.0 - d_prob) * a_prob * self.get_value(piece)

				# Adjust score based on movement of piece out of danger
				attackers = self.board.coverage(piece.x, piece.y, opponent(piece.colour))
				s_prob = 0.0
				for a in attackers.keys():
					s_prob += attackers[a]
				if len(attackers.keys()) > 0:
					s_prob /= float(len(attackers.keys()))

				if (s_prob > 1.0):
					s_prob = 1.0
				value += self.defence * s_prob * self.get_value(piece)
				
				# Adjust score based on probability that the move is actually possible
				moves.append([[x, y], grid[x][y] * value])

		moves.sort(key = lambda e : e[1], reverse = True)
		#sys.stderr.write(sys.argv[0] + ": Moves for " + str(piece) + " are " + str(moves) + "\n")

		piece.last_moves = moves
		piece.selected_moves = None

		

		
		return moves

	def select_best(self, colour):

		self.depth += 1
		all_moves = {}
		for p in self.board.pieces[colour]:
			self.choice = p # Temporarily pick that piece
			m = self.prioritise_moves(p)
			if len(m) > 0:
				all_moves.update({p : m[0]})

		if len(all_moves.items()) <= 0:
			return None
		
		
		opts = all_moves.items()
		opts.sort(key = lambda e : e[1][1], reverse = True)

		if self.depth >= self.max_depth:
			self.depth -= 1
			return list(opts[0])

		if self.recurse_for >= 0:
			opts = opts[0:self.recurse_for]
		#sys.stderr.write(sys.argv[0] + " : Before recurse, options are " + str(opts) + "\n")

		# Take the best few moves, and recurse
		for choice in opts[0:self.recurse_for]:
			[xx,yy] = [choice[0].x, choice[0].y] # Remember position
			[nx,ny] = choice[1][0] # Target
			[choice[0].x, choice[0].y] = [nx, ny] # Set position
			target = self.board.grid[nx][ny] # Remember piece in spot
			self.board.grid[xx][yy] = None # Remove piece
			self.board.grid[nx][ny] = choice[0] # Replace with moving piece
			
			# Recurse
			best_enemy_move = self.select_best(opponent(choice[0].colour))
			choice[1][1] -= best_enemy_move[1][1] / float(self.depth + 1.0)
			
			[choice[0].x, choice[0].y] = [xx, yy] # Restore position
			self.board.grid[nx][ny] = target # Restore taken piece
			self.board.grid[xx][yy] = choice[0] # Restore moved piece
			
		

		opts.sort(key = lambda e : e[1][1], reverse = True)
		#sys.stderr.write(sys.argv[0] + " : After recurse, options are " + str(opts) + "\n")

		self.depth -= 1
		return list(opts[0])

		

	# Returns [x,y] of selected piece
	def select(self):
		#sys.stderr.write("Getting choice...")
		self.choice = self.select_best(self.colour)[0]
Sam Moore's avatar
Sam Moore committed
1036
		
Sam Moore's avatar
Sam Moore committed
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
		#sys.stderr.write(" Done " + str(self.choice)+"\n")
		return [self.choice.x, self.choice.y]
	
	# Returns [x,y] of square to move selected piece into
	def get_move(self):
		#sys.stderr.write("Choice is " + str(self.choice) + "\n")
		self.choice.selected_moves = self.choice.last_moves
		moves = self.prioritise_moves(self.choice)
		if len(moves) > 0:
			return moves[0][0]
		else:
Sam Moore's avatar
Sam Moore committed
1048
			return AgentRandom.get_move(self)
Sam Moore's avatar
Sam Moore committed
1049
1050

# --- agent_bishop.py --- #
1051
1052
1053
1054
1055
import multiprocessing

# Hacky alternative to using select for timing out players

# WARNING: Do not wrap around HumanPlayer or things breakify
Sam Moore's avatar
Sam Moore committed
1056
# WARNING: Do not use in general or things breakify
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095

class Sleeper(multiprocessing.Process):
	def __init__(self, timeout):
		multiprocessing.Process.__init__(self)
		self.timeout = timeout

	def run(self):
		time.sleep(self.timeout)


class Worker(multiprocessing.Process):
	def __init__(self, function, args, q):
		multiprocessing.Process.__init__(self)
		self.function = function
		self.args = args
		self.q = q

	def run(self):
		#print str(self) + " runs " + str(self.function) + " with args " + str(self.args) 
		self.q.put(self.function(*self.args))
		
		

def TimeoutFunction(function, args, timeout):
	q = multiprocessing.Queue()
	w = Worker(function, args, q)
	s = Sleeper(timeout)
	w.start()
	s.start()
	while True: # Busy loop of crappyness
		if not w.is_alive():
			s.terminate()
			result = q.get()
			w.join()
			#print "TimeoutFunction gets " + str(result)
			return result
		elif not s.is_alive():
			w.terminate()
			s.join()
Sam Moore's avatar
Sam Moore committed
1096
			raise Exception("TIMEOUT")
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122

	
		

# A player that wraps another player and times out its moves
# Uses threads
# A (crappy) alternative to the use of select()
class TimeoutPlayer(Player):
	def __init__(self, base_player, timeout):
		Player.__init__(self, base_player.name, base_player.colour)
		self.base_player = base_player
		self.timeout = timeout
		
	def select(self):
		return TimeoutFunction(self.base_player.select, [], self.timeout)
		
	
	def get_move(self):
		return TimeoutFunction(self.base_player.get_move, [], self.timeout)

	def update(self, result):
		return TimeoutFunction(self.base_player.update, [result], self.timeout)

	def quit(self, final_result):
		return TimeoutFunction(self.base_player.quit, [final_result], self.timeout)
# --- timeout_player.py --- #
Sam Moore's avatar
Sam Moore committed
1123
import socket
Sam Moore's avatar
Sam Moore committed
1124
1125
1126
1127
import select

network_timeout_start = -1.0 # Timeout in seconds to wait for the start of a message
network_timeout_delay = 1.0 # Maximum time between two characters being received
Sam Moore's avatar
Sam Moore committed
1128
1129
1130
1131

class Network():
	def __init__(self, colour, address = None):
		self.socket = socket.socket()
Sam Moore's avatar
Sam Moore committed
1132
		#self.socket.setblocking(0)
Sam Moore's avatar
Sam Moore committed
1133
1134

		if colour == "white":
Sam Moore's avatar
Sam Moore committed
1135
			self.port = 4562
Sam Moore's avatar
Sam Moore committed
1136
		else:
Sam Moore's avatar
Sam Moore committed
1137
			self.port = 4563
Sam Moore's avatar
Sam Moore committed
1138
1139
1140

		self.src = None

Sam Moore's avatar
Sam Moore committed
1141
1142
	#	print str(self) + " listens on port " + str(self.port)

Sam Moore's avatar
Sam Moore committed
1143
		if address == None:
Sam Moore's avatar
Sam Moore committed
1144
			self.host = socket.gethostname()
Sam Moore's avatar
Sam Moore committed
1145
1146
1147
1148
			self.socket.bind((self.host, self.port))
			self.socket.listen(5)	

			self.src, self.address = self.socket.accept()
Sam Moore's avatar
Sam Moore committed
1149
1150
1151
			self.src.send("ok\n")
			if self.get_response() == "QUIT":
				self.src.close()
Sam Moore's avatar
Sam Moore committed
1152
1153
		else:
			self.host = address
Sam Moore's avatar
Sam Moore committed
1154
			self.socket.connect((address, self.port))
Sam Moore's avatar
Sam Moore committed
1155
			self.src = self.socket
Sam Moore's avatar
Sam Moore committed
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
			self.src.send("ok\n")
			if self.get_response() == "QUIT":
				self.src.close()

	def get_response(self):
		# Timeout the start of the message (first character)
		if network_timeout_start > 0.0:
			ready = select.select([self.src], [], [], network_timeout_start)[0]
		else:
			ready = [self.src]
		if self.src in ready:
			s = self.src.recv(1)
		else:
			raise Exception("UNRESPONSIVE")

Sam Moore's avatar
Sam Moore committed
1171
1172

		while s[len(s)-1] != '\n':
Sam Moore's avatar
Sam Moore committed
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
			# Timeout on each character in the message
			if network_timeout_delay > 0.0:
				ready = select.select([self.src], [], [], network_timeout_delay)[0]
			else:
				ready = [self.src]
			if self.src in ready:
				s += self.src.recv(1) 
			else:
				raise Exception("UNRESPONSIVE")

		return s.strip(" \r\n")

	def send_message(self,s):
		if network_timeout_start > 0.0:
			ready = select.select([], [self.src], [], network_timeout_start)[1]
		else:
			ready = [self.src]

		if self.src in ready:
			self.src.send(s + "\n")
		else:
			raise Exception("UNRESPONSIVE")

	def check_quit(self, s):
		s = s.split(" ")
		if s[0] == "QUIT":
			with game.lock:
				game.final_result = " ".join(s[1:]) + " " + str(opponent(self.colour))
			game.stop()
			return True
Sam Moore's avatar
Sam Moore committed
1203
1204
1205
1206

		

class NetworkSender(Player,Network):
Sam Moore's avatar
Sam Moore committed
1207
	def __init__(self, base_player, address = None):
Sam Moore's avatar
Sam Moore committed
1208
1209
1210
		self.base_player = base_player
		Player.__init__(self, base_player.name, base_player.colour)

Sam Moore's avatar
Sam Moore committed
1211
1212
1213
1214
1215
1216
		self.address = address

	def connect(self):
		Network.__init__(self, self.base_player.colour, self.address)


Sam Moore's avatar
Sam Moore committed
1217
1218
1219
1220
1221

	def select(self):
		[x,y] = self.base_player.select()
		choice = self.board.grid[x][y]
		s = str(x) + " " + str(y)
Sam Moore's avatar
Sam Moore committed
1222
1223
		#print str(self) + ".select sends " + s
		self.send_message(s)
Sam Moore's avatar
Sam Moore committed
1224
1225
1226
1227
1228
		return [x,y]

	def get_move(self):
		[x,y] = self.base_player.get_move()
		s = str(x) + " " + str(y)
Sam Moore's avatar
Sam Moore committed
1229
1230
		#print str(self) + ".get_move sends " + s
		self.send_message(s)
Sam Moore's avatar
Sam Moore committed
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
		return [x,y]

	def update(self, s):
		self.base_player.update(s)
		s = s.split(" ")
		[x,y] = map(int, s[0:2])
		selected = self.board.grid[x][y]
		if selected != None and selected.colour == self.colour and len(s) > 2 and not "->" in s:
			s = " ".join(s[0:3])
			for i in range(2):
				if selected.types_revealed[i] == True:
					s += " " + str(selected.types[i])
				else:
					s += " unknown"
Sam Moore's avatar
Sam Moore committed
1245
1246
			#print str(self) + ".update sends " + s
			self.send_message(s)
Sam Moore's avatar
Sam Moore committed
1247
1248
1249
1250
				

	def quit(self, final_result):
		self.base_player.quit(final_result)
Sam Moore's avatar
Sam Moore committed
1251
		#self.src.send("QUIT " + str(final_result) + "\n")
Sam Moore's avatar
Sam Moore committed
1252
1253
1254
		self.src.close()

class NetworkReceiver(Player,Network):
Sam Moore's avatar
Sam Moore committed
1255
	def __init__(self, colour, address=None):
Sam Moore's avatar
Sam Moore committed
1256
1257
1258
		
		Player.__init__(self, address, colour)

Sam Moore's avatar
Sam Moore committed
1259
		self.address = address
Sam Moore's avatar
Sam Moore committed
1260

Sam Moore's avatar
Sam Moore committed
1261
1262
1263
1264
		self.board = None

	def connect(self):
		Network.__init__(self, self.colour, self.address)
Sam Moore's avatar
Sam Moore committed
1265
1266
1267
			

	def select(self):
Sam Moore's avatar
Sam Moore committed
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
		
		s = self.get_response()
		#print str(self) + ".select gets " + s
		[x,y] = map(int,s.split(" "))
		if x == -1 and y == -1:
			#print str(self) + ".select quits the game"
			with game.lock:
				game.final_state = "network terminated " + self.colour
			game.stop()
		return [x,y]
Sam Moore's avatar
Sam Moore committed
1278
	def get_move(self):
Sam Moore's avatar
Sam Moore committed
1279
1280
1281
1282
1283
1284
1285
1286
1287
		s = self.get_response()
		#print str(self) + ".get_move gets " + s
		[x,y] = map(int,s.split(" "))
		if x == -1 and y == -1:
			#print str(self) + ".get_move quits the game"
			with game.lock:
				game.final_state = "network terminated " + self.colour
			game.stop()
		return [x,y]
Sam Moore's avatar
Sam Moore committed
1288
1289
1290
1291
1292
1293
1294

	def update(self, result):
		
		result = result.split(" ")
		[x,y] = map(int, result[0:2])
		selected = self.board.grid[x][y]
		if selected != None and selected.colour == self.colour and len(result) > 2 and not "->" in result:
Sam Moore's avatar
Sam Moore committed
1295
1296
			s = self.get_response()
			#print str(self) + ".update - receives " + str(s)
Sam Moore's avatar
Sam Moore committed
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
			s = s.split(" ")
			selected.choice = int(s[2])
			for i in range(2):
				selected.types[i] = str(s[3+i])
				if s[3+i] == "unknown":
					selected.types_revealed[i] = False
				else:
					selected.types_revealed[i] = True
			selected.current_type = selected.types[selected.choice]	
		else:
Sam Moore's avatar
Sam Moore committed
1307
1308
			pass
			#print str(self) + ".update - ignore result " + str(result)			
Sam Moore's avatar
Sam Moore committed
1309
1310
1311
1312
1313
1314
		

	def quit(self, final_result):
		self.src.close()
	
# --- network.py --- #
Sam Moore's avatar
Sam Moore committed
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
import threading

# A thread that can be stopped!
# Except it can only be stopped if it checks self.stopped() periodically
# So it can sort of be stopped
class StoppableThread(threading.Thread):
	def __init__(self):
		threading.Thread.__init__(self)
		self._stop = threading.Event()

	def stop(self):
		self._stop.set()

	def stopped(self):
		return self._stop.isSet()
# --- thread_util.py --- #
Sam Moore's avatar
Sam Moore committed
1331
log_files = []
Sam Moore's avatar
Sam Moore committed
1332
1333
import datetime
import urllib2
Sam Moore's avatar
Sam Moore committed
1334

Sam Moore's avatar
Sam Moore committed
1335
class LogFile():
1336
	def __init__(self, log):	
Sam Moore's avatar
Sam Moore committed
1337
		
1338
1339
		self.log = log
		self.logged = []
Sam Moore's avatar
Sam Moore committed
1340
		self.log.write("# Log starts " + str(datetime.datetime.now()) + "\n")
Sam Moore's avatar
Sam Moore committed
1341

Sam Moore's avatar
Sam Moore committed
1342
	def write(self, s):
1343
1344
1345
		now = datetime.datetime.now()
		self.log.write(str(now) + " : " + s + "\n")
		self.logged.append((now, s))
Sam Moore's avatar
Sam Moore committed
1346
1347

	def setup(self, board, players):
Sam Moore's avatar
Sam Moore committed
1348
		
1349
		for p in players:
Sam Moore's avatar
Sam Moore committed
1350
			self.log.write("# " + p.colour + " : " + p.name + "\n")
1351
		
Sam Moore's avatar
Sam Moore committed
1352
		self.log.write("# Initial board\n")
1353
1354
1355
		for x in range(0, w):
			for y in range(0, h):
				if board.grid[x][y] != None:
Sam Moore's avatar
Sam Moore committed
1356
1357
1358
1359
					self.log.write(str(board.grid[x][y]) + "\n")

		self.log.write("# Start game\n")

1360
1361
	def close(self):
		self.log.write("# EOF\n")
Sam Moore's avatar
Sam Moore committed
1362
1363
		if self.log != sys.stdout:
			self.log.close()
1364

Sam Moore's avatar
Sam Moore committed
1365
class ShortLog(LogFile):
Sam Moore's avatar
Sam Moore committed
1366
	def __init__(self, file_name):
Sam Moore's avatar
Sam Moore committed
1367
1368
1369
1370
1371
		if file_name == "":
			self.log = sys.stdout
		else:
			self.log = open(file_name, "w", 0)
		LogFile.__init__(self, self.log)
Sam Moore's avatar
Sam Moore committed
1372
		self.file_name = file_name
1373
		self.phase = 0
Sam Moore's avatar
Sam Moore committed
1374

1375
1376
1377
1378
1379
	def write(self, s):
		now = datetime.datetime.now()
		self.logged.append((now, s))
		
		if self.phase == 0:
Sam Moore's avatar
Sam Moore committed
1380
1381
1382
			if self.log != sys.stdout:
				self.log.close()
				self.log = open(self.file_name, "w", 0)
Sam Moore's avatar
Sam Moore committed
1383
			self.log.write("# Short log updated " + str(datetime.datetime.now()) + "\n")	
1384
			LogFile.setup(self, game.board, game.players)
Sam Moore's avatar
Sam Moore committed
1385

1386
1387
1388
1389
1390
1391
1392
		elif self.phase == 1:
			for message in self.logged[len(self.logged)-2:]:
				self.log.write(str(message[0]) + " : " + message[1] + "\n")

		self.phase = (self.phase + 1) % 2		
		
	def close(self):
Sam Moore's avatar
Sam Moore committed
1393
1394
1395
		if self.phase == 1:
			ending = self.logged[len(self.logged)-1]
			self.log.write(str(ending[0]) + " : " + ending[1] + "\n")
1396
		self.log.write("# EOF\n")
Sam Moore's avatar
Sam Moore committed
1397
1398
		if self.log != sys.stdout:
			self.log.close()
Sam Moore's avatar
Sam Moore committed
1399
1400
1401
1402
1403
		

class HeadRequest(urllib2.Request):
	def get_method(self):
		return "HEAD"
Sam Moore's avatar
Sam Moore committed
1404
1405

class HttpGetter(StoppableThread):
Sam Moore's avatar
Sam Moore committed
1406
	def __init__(self, address):
Sam Moore's avatar
Sam Moore committed
1407
		StoppableThread.__init__(self)
Sam Moore's avatar
Sam Moore committed
1408
		self.address = address
Sam Moore's avatar
Sam Moore committed
1409
1410
1411
1412
		self.log = urllib2.urlopen(address)
		self.lines = []
		self.lock = threading.RLock() #lock for access of self.state
		self.cond = threading.Condition() # conditional
Sam Moore's avatar
Sam Moore committed
1413

Sam Moore's avatar
Sam Moore committed
1414
1415
1416
1417
1418
1419
1420
	def run(self):
		while not self.stopped():
			line = self.log.readline()
			if line == "":
				date_mod = datetime.datetime.strptime(self.log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
				self.log.close()
	
Sam Moore's avatar
Sam Moore committed
1421
1422
				next_log = urllib2.urlopen(HeadRequest(self.address))
				date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
Sam Moore's avatar
Sam Moore committed
1423
1424
1425
1426
1427
				while date_new <= date_mod and not self.stopped():
					next_log = urllib2.urlopen(HeadRequest(self.address))
					date_new = datetime.datetime.strptime(next_log.headers['last-modified'], "%a, %d %b %Y %H:%M:%S GMT")
				if self.stopped():
					break
Sam Moore's avatar
Sam Moore committed
1428

Sam Moore's avatar
Sam Moore committed
1429
1430
				self.log = urllib2.urlopen(self.address)
				line = self.log.readline()
Sam Moore's avatar
Sam Moore committed
1431

Sam Moore's avatar
Sam Moore committed
1432
1433
1434
1435
			self.cond.acquire()
			self.lines.append(line)
			self.cond.notifyAll()
			self.cond.release()
Sam Moore's avatar
Sam Moore committed
1436

Sam Moore's avatar
Sam Moore committed
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
			#sys.stderr.write(" HttpGetter got \'" + str(line) + "\'\n")

		self.log.close()
				
				
	
		
		
class HttpReplay():
	def __init__(self, address):
		self.getter = HttpGetter(address)
		self.getter.start()
		
	def readline(self):
		self.getter.cond.acquire()
		while len(self.getter.lines) == 0:
			self.getter.cond.wait()
			
		result = self.getter.lines[0]
		self.getter.lines = self.getter.lines[1:]
		self.getter.cond.release()

		return result
			
Sam Moore's avatar
Sam Moore committed
1461
			
1462
	def close(self):
Sam Moore's avatar
Sam Moore committed
1463
		self.getter.stop()
Sam Moore's avatar
Sam Moore committed
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500

class FileReplay():
	def __init__(self, filename):
		self.f = open(filename, "r", 0)
		self.filename = filename
		self.mod = os.path.getmtime(filename)
		self.count = 0
	
	def readline(self):
		line = self.f.readline()
		
		while line == "":
			mod2 = os.path.getmtime(self.filename)
			if mod2 > self.mod:
				#sys.stderr.write("File changed!\n")
				self.mod = mod2
				self.f.close()
				self.f = open(self.filename, "r", 0)
				
				new_line = self.f.readline()
				
				if " ".join(new_line.split(" ")[0:3]) != "# Short log":
					for i in range(self.count):
						new_line = self.f.readline()
						#sys.stderr.write("Read back " + str(i) + ": " + str(new_line) + "\n")
					new_line = self.f.readline()
				else:
					self.count = 0
				
				line = new_line

		self.count += 1
		return line

	def close(self):
		self.f.close()
		
Sam Moore's avatar
Sam Moore committed
1501
1502
						
def log(s):
Sam Moore's avatar
Sam Moore committed
1503
1504
	for l in log_files:
		l.write(s)
Sam Moore's avatar
Sam Moore committed
1505
1506
1507
		

def log_init(board, players):
Sam Moore's avatar
Sam Moore committed