basic_python.py 9.9 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/python -u

#NOTE: The -u option is required for unbuffered stdin/stdout.
#	If stdin/stdout are buffered, the manager program will not recieve any messages and assume that the agent has timed out.

"""
 basic_python.py - A sample Stratego AI for the UCC Programming Competition 2012

 Written in python, the slithery language 
 Simply makes random moves, as long as possible

 author Sam Moore (matches) [SZM]
 website http://matches.ucc.asn.au/stratego
 email [email protected] or [email protected]
 git git.ucc.asn.au/progcomp2012.git
"""

import sys
import random

ranks = ['B','1','2','3','4','5','6','7','8','9','s','F', '?', '+']

Sam Moore's avatar
Sam Moore committed
23
24
25
26
27
28
29
30
31
def is_integer(s):
	""" Using exceptions for this feels... wrong..."""
	try:
		int(s)
		return True
	except ValueError:
		return False

def move(x, y, direction, multiplier):
32
33
	""" Moves point (x,y) in direction, returns a pair """
	if direction == "UP":
Sam Moore's avatar
Whoops    
Sam Moore committed
34
		return (x,y-multiplier)
35
	elif direction == "DOWN":
Sam Moore's avatar
Whoops    
Sam Moore committed
36
		return (x,y+multiplier)
37
	elif direction == "LEFT":
Sam Moore's avatar
Whoops    
Sam Moore committed
38
		return (x-multiplier, y)
39
	elif direction == "RIGHT":
Sam Moore's avatar
Whoops    
Sam Moore committed
40
		return (x+multiplier, y)
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
	return (x,y)



def oppositeColour(colour):
	""" Returns the opposite colour to that given """
	if colour == "RED":
		return "BLUE"
	elif colour == "BLUE":
		return "RED"
	else:
		return "NONE"

class Piece:
	""" Class representing a piece 
		Pieces have colour, rank and co-ordinates	
	"""
	def __init__(self, colour, rank, x, y):
		self.colour = colour
		self.rank = rank
		self.x = x
		self.y = y
		self.lastMoved = -1
64
		self.beenRevealed = False
65
66
67
68
69
70
71
72
73
74
75

	def mobile(self):
		return self.rank != 'F' and self.rank != 'B' and self.rank != '?' and self.rank != '+'

	def valuedRank(self):
		if ranks.count(self.rank) > 0:
			return len(ranks) - 2 - ranks.index(self.rank)
		else:
			return 0
	

Sam Moore's avatar
Sam Moore committed
76
77
78
79
80
81
def valuedRank(rank):
	if ranks.count(rank) > 0:
		return len(ranks) - 2 - ranks.index(rank)
	else:
		return 0

82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97


class BasicAI:
	"""
		BasicAI class to play a game of stratego
 		Implements the protocol correctly. Stores the state of the board in self.board
		Only makes random moves.
		Override method "MakeMove" for more complex moves
	"""
	def __init__(self):	
		""" Constructs the BasicAI agent, and starts it playing the game """
		#sys.stderr.write("BasicAI __init__ here...\n");
		self.turn = 0
		self.board = []
		self.units = []
		self.enemyUnits = []
Sam Moore's avatar
Sam Moore committed
98
99
100
101
102
103
104

		self.totalAllies = {'B':6,'1':1,'2':1,'3':2,'4':3,'5':4,'6':4,'7':4,'8':5,'9':8,'s':1,'F':1}
		self.totalEnemies = {'B':6,'1':1,'2':1,'3':2,'4':3,'5':4,'6':4,'7':4,'8':5,'9':8,'s':1,'F':1}
		self.hiddenEnemies = {'B':6,'1':1,'2':1,'3':2,'4':3,'5':4,'6':4,'7':4,'8':5,'9':8,'s':1,'F':1}
		self.hiddenAllies = {'B':6,'1':1,'2':1,'3':2,'4':3,'5':4,'6':4,'7':4,'8':5,'9':8,'s':1,'F':1}
		self.lastMoved = None

105
106
107
108
109
110
		

	def Setup(self):
		""" Implements Setup part of protocol. Always uses the same setup. Override to create custom setups """
		#sys.stderr.write("BasicAI Setup here...\n");
		setup = sys.stdin.readline().split(' ')
111
112
		if len(setup) != 4:
			sys.stderr.write("BasicAI setup fails, expected 4 tokens, got " + str(len(setup)) + " "+str(setup) + "\n")
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
		self.colour = setup[0]
		self.opponentName = setup[1]
		self.width = int(setup[2])
		self.height = int(setup[3])
		for x in range(0, self.width):
			self.board.append([])
			for y in range(0, self.height):		
				self.board[x].append(None)
		if self.colour == "RED":
			print "FB8sB479B8\nBB31555583\n6724898974\n967B669999"
		elif self.colour == "BLUE":
			print "967B669999\n6724898974\nBB31555583\nFB8sB479B8"
		return True

	def MoveCycle(self):
		#sys.stderr.write("BasicAI MakeMove here...\n");
		if self.InterpretResult() == False or self.ReadBoard() == False or self.MakeMove() == False:
			return False
		self.turn += 1
		return self.InterpretResult()

	def MakeMove(self):
		""" Randomly moves any moveable piece, or prints "NO_MOVE" if there are none """
		#TODO: Over-ride this function in base classes with more complex move behaviour

		#sys.stderr.write("BasicAI MakeMove here...\n")
		#self.debugPrintBoard()

		if len(self.units) <= 0:
			return False

		index = random.randint(0, len(self.units)-1)
		startIndex = index

		directions = ("UP", "DOWN", "LEFT", "RIGHT")
		while True:
			piece = self.units[index]
			if piece != None and piece.mobile():
				dirIndex = random.randint(0, len(directions)-1)
				startDirIndex = dirIndex
				
				while True:
					#sys.stderr.write("Trying index " + str(dirIndex) + "\n")
156
					p = move(piece.x, piece.y, directions[dirIndex],1)
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
224
225
226
					if p[0] >= 0 and p[0] < self.width and p[1] >= 0 and p[1] < self.height:
						target = self.board[p[0]][p[1]]
						if target == None or (target.colour != piece.colour and target.colour != "NONE" and target.colour != "BOTH"):	
							print str(piece.x) + " " + str(piece.y) + " "+directions[dirIndex]
							return True
					dirIndex = (dirIndex + 1) % len(directions)
					if startDirIndex == dirIndex:
						break

			index = (index + 1) % len(self.units)
			if startIndex == index:
				print "NO_MOVE"
				return True
							
			
	def ReadBoard(self):
		""" Reads in the board. 
			On the very first turn, sets up the self.board structure
			On subsequent turns, the board is simply read, but the self.board structure is not updated here.
		"""
		#sys.stderr.write("BasicAI ReadBoard here...\n");
		for y in range(0,self.height):
			row = sys.stdin.readline().strip()
			if len(row) < self.width:
				sys.stderr.write("Row has length " + str(len(row)) + " vs " + str(self.width) + "\n")
				return False
			for x in range(0,self.width):
				if self.turn == 0:
					if row[x] == '.':
						pass
					elif row[x] == '#':
						self.board[x][y] = Piece(oppositeColour(self.colour), '?',x,y)
						self.enemyUnits.append(self.board[x][y])
					elif row[x] == '+':
						self.board[x][y] = Piece("NONE", '+', x, y)
					else:
						self.board[x][y] = Piece(self.colour, row[x],x,y)
						self.units.append(self.board[x][y])
				else:
					pass
		return True
		

	def InterpretResult(self):
		""" Interprets the result of a move, and updates the board. 
			The very first move is ignored. 
			On subsequent moves, the self.board structure is updated
		"""
		#sys.stderr.write("BasicAI InterpretResult here...\n")
		result = sys.stdin.readline().split(' ')
		#sys.stderr.write("	Read status line \"" + str(result) + "\"\n")
		if self.turn == 0:
			return True

		if result[0].strip() == "QUIT": #Make sure we exit when the manager tells us to!
			return False

		if result[0].strip() == "NO_MOVE": #No move was made, don't need to update anything
			return True

		if len(result) < 4: #Should be at least 4 tokens (X Y DIRECTION OUTCOME) in any other case
			return False

		x = int(result[0].strip())
		y = int(result[1].strip())


		#sys.stderr.write("	Board position " + str(x) + " " + str(y) + " is OK!\n")		

		direction = result[2].strip()
Sam Moore's avatar
Sam Moore committed
227
228

		multiplier = 1
229
		outcome = result[3].strip()
Sam Moore's avatar
Sam Moore committed
230
231
232
233
234
		outIndex = 3
		if is_integer(outcome):
			multiplier = int(outcome)
			outcome = result[4].strip()
			outIndex = 4
235
		
Sam Moore's avatar
Sam Moore committed
236
		p = move(x,y,direction, multiplier)
237

238
239
240
		#Determine attacking piece
		attacker = self.board[x][y]
		self.board[x][y] = None
241

242
243
		if attacker == None:
			return False
Sam Moore's avatar
Sam Moore committed
244
245
246

		lastMoved = attacker

247
		defender = self.board[p[0]][p[1]]
248

249
250
251
		#Update attacker's position (Don't overwrite the board yet though)
		attacker.x = p[0]
		attacker.y = p[1]
252

253
254
255
256
257
258
		
		#Determine ranks of pieces if supplied
		if len(result) >= outIndex + 3:
			if defender == None:
				return False
			attacker.rank = result[outIndex+1].strip()
Sam Moore's avatar
Sam Moore committed
259
260
261
262
263
			if attacker.beenRevealed == False:
				if attacker.colour == self.colour:
					self.hiddenAllies[attacker.rank] -= 1
				elif attacker.colour == oppositeColour(self.colour):
					self.hiddenEnemies[attacker.rank] -= 1
264
265
			attacker.beenRevealed = True
			defender.rank = result[outIndex+2].strip()
Sam Moore's avatar
Sam Moore committed
266
267
268
269
270
271
			if defender.beenRevealed == False:
				if defender.colour == self.colour:
					self.hiddenAllies[defender.rank] -= 1
				elif defender.colour == oppositeColour(self.colour):
					self.hiddenEnemies[defender.rank] -= 1

272
			defender.beenRevealed = True
273
274

			
275
276
277
278
279
280
281
282
		
		if outcome == "OK":
			self.board[p[0]][p[1]] = attacker
			
		elif outcome == "KILLS":
			self.board[p[0]][p[1]] = attacker

			if defender.colour == self.colour:
Sam Moore's avatar
Sam Moore committed
283
				self.totalAllies[defender.rank] -= 1
284
285
				self.units.remove(defender)
			elif defender.colour == oppositeColour(self.colour):
Sam Moore's avatar
Sam Moore committed
286
				self.totalEnemies[defender.rank] -= 1
287
288
				self.enemyUnits.remove(defender)
	
289
		elif outcome == "DIES":
290
			if attacker.colour == self.colour:
Sam Moore's avatar
Sam Moore committed
291
				self.totalAllies[attacker.rank] -= 1
292
293
				self.units.remove(attacker)
			elif attacker.colour == oppositeColour(self.colour):
Sam Moore's avatar
Sam Moore committed
294
				self.totalEnemies[attacker.rank] -= 1
295
				self.enemyUnits.remove(attacker)
296
297

		elif outcome == "BOTHDIE":
298
			self.board[p[0]][p[1]] = None
299

300
			if defender.colour == self.colour:
Sam Moore's avatar
Sam Moore committed
301
				self.totalAllies[defender.rank] -= 1
302
303
				self.units.remove(defender)
			elif defender.colour == oppositeColour(self.colour):
Sam Moore's avatar
Sam Moore committed
304
				self.totalEnemies[defender.rank] -= 1
305
				self.enemyUnits.remove(defender)
306

307
			if attacker.colour == self.colour:
Sam Moore's avatar
Sam Moore committed
308
				self.totalAllies[attacker.rank] -= 1
309
310
				self.units.remove(attacker)
			elif attacker.colour == oppositeColour(self.colour):
Sam Moore's avatar
Sam Moore committed
311
				self.totalEnemies[attacker.rank] -= 1
312
				self.enemyUnits.remove(attacker)
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339

		elif outcome == "FLAG":
			#sys.stderr.write("	Game over!\n")
			return False
		elif outcome == "ILLEGAL":
			#sys.stderr.write("	Illegal move!\n")
			return False
		else:
			#sys.stderr.write("	Don't understand outcome \"" + outcome + "\"!\n");
			return False

		#sys.stderr.write("	Completed interpreting move!\n");		
		return True

	def debugPrintBoard(self):
		""" For debug purposes only. Prints the board to stderr.
			Does not indicate difference between allied and enemy pieces
			Unknown (enemy) pieces are shown as '?'
 		"""
		for y in range(0, self.height):
			for x in range(0, self.width):
				if self.board[x][y] == None:
					sys.stderr.write(".");
				else:
					sys.stderr.write(str(self.board[x][y].rank));
			sys.stderr.write("\n")

Sam Moore's avatar
Sam Moore committed
340
341
342
343
344
if __name__ == "__main__":
	basicAI = BasicAI()
	if basicAI.Setup():
		while basicAI.MoveCycle():
			pass
345