-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathengine.py
365 lines (299 loc) · 11.3 KB
/
engine.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
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
224
225
226
227
228
229
230
231
232
233
234
235
236
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
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
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
#!/usr/bin/env python
import subprocess
import shlex
import threading
import Queue
import sys
from Queue import Queue, Empty
from subprocess import Popen
from threading import Thread
import PlanetWars
class BotThread(Thread):
"""
Class to run a bot in a thread.
Starts up a thread to talk to a bot process, and provide an
interface to call it. Handles the timeout here.
"""
def __init__(self, command):
Thread.__init__(self)
self.input = Queue()
self.output = Queue()
args = shlex.split(command)
self.process = None
print(args)
self.process = Popen(args,
stdout=subprocess.PIPE,
stdin=subprocess.PIPE)
self.daemon = False
self.start()
def run_step(self, game_state, timeoutms):
"""Run one step of the game state."""
self.input.put(game_state)
try:
result = self.output.get(True, timeoutms/1000.0)
return result, True
except Empty:
return "TIMEOUT", False
except Crashed:
return "CRASHED", False
def __del__(self):
"""Clean up the process if it is still running"""
if self.process and self.process.poll() is None:
self.process.kill()
def stop(self):
try:
self.input.put(None)
self.process.stdin.close()
if self.process.poll() is None:
self.process.kill()
except:
print "got an exception trying to end the bot"
def run(self):
"""Run the bot loop. Use run_step for individual steps"""
try:
if self.process.poll() is not None:
raise Exception("bot did not start")
while True:
command = self.input.get(True)
try:
if command is None:
self.process.kill()
break
# not sure if this is excesive poll()'ing...
if self.process.poll() is not None:
self.output.put("CRASHED")
break
self.process.stdin.write(command)
result = []
while True:
if self.process.poll() is not None:
print "process crashed"
self.output.put("CRASHED")
return
line = self.process.stdout.readline()
if line is None:
self.output.put("CRASHED")
return
result.append(line)
if line.startswith("go"): break
self.output.put("".join(result))
except:
self.output("CRASHED WITH EXCEPTION")
except:
pass
class EngineThread(Thread):
"""
Class to run a bot in an engine.
Need another level of threads to wait for the bot result.
"""
def __init__(self, bot):
Thread.__init__(self)
self.bot = bot
self.input = Queue()
self.output = Queue()
self.event = threading.Event()
self.daemon = False
self.start()
self.result = None
def run(self):
try:
while True:
x = self.input.get(True)
if x is None: break
command, timeout = x
result = self.bot.run_step(command, timeout)
self.output.put(result)
except:
pass
def send_input(self, game_state, timeoutms):
self.result = None
self.input.put((game_state, timeoutms))
def wait(self, timeoutms):
if self.result is None:
result = self.output.get(timeoutms/1000.0)
if result:
self.result = result
else:
self.result = ("TIMEOUTWAIT", False)
return self.result
def stop(self):
self.input.put(None)
self.bot.stop()
def output_game_state(pw, flip_owner):
result = []
for p in pw.planets:
o = p.owner
if flip_owner and o > 0:
o = 3 - o
result.append("P %f %f %d %d %d" %
(p.x, p.y, o, p.num_ships, p.growth_rate))
for f in pw.fleets:
o = f.owner
if flip_owner:
o = 3 - o
result.append("F %d %d %d %d %d %d" %
(o, f.num_ships,
f.source_planet, f.destination_planet,
f.total_trip_length, f.turns_remaining))
result.append("go\n")
return "\n".join(result)
def resolve(counts,owner):
"""Resolve a battle
counts is a list of the number of ships from each player (neutral,
self, enemy), and owner is the current owner of the planet.
Returns the number of ships and owner after the battle."""
if counts[0] < counts[1]:
a,b = 0,1
else:
a,b = 1,0
if counts[b] < counts[2]:
c = 2
elif counts[2] < counts[a]:
b,c = a,b
else:
b,c = 2,b
d = counts[c] - counts[b]
if d == 0:
return owner, 0
else:
return c, d
def game_step(initial_pw, p1_orders, p2_orders):
p1_error = None
p2_error = None
def create_fleets(player, orders):
result = []
for line in orders.split("\n"):
if line.startswith("go"):
break
src, dst, num = [int(x) for x in line.split()]
if src == dst:
return ([], "Invalid Move: Sent from %d to itself" % src)
if src < 0 or src >= len(initial_pw.planets):
return ([], "Invalid source planet: %d" % src)
if dst < 0 or dst >= len(initial_pw.planets):
return ([], "Invalid destination planet: %d" % dst)
src_planet = initial_pw.planets[src]
if src_planet.owner != player:
return ([], "Player does not own source planet %d" % src)
if num < 0:
return ([], "Cannot send negative number of ships")
if num > src_planet.num_ships:
return ([], "Sent too many ships from %d. Sent %d, only %d available" %
(src, num, src_planet.num_ships))
if num > 0:
dist = initial_pw.Distance(src, dst)
result.append(PlanetWars.Fleet(player, num, src, dst, dist, dist))
src_planet.num_ships -= num
return (result, None)
# Send out new fleets
p1_fleets, p1_error = create_fleets(1, p1_orders)
p2_fleets, p2_error = create_fleets(2, p2_orders)
if p1_error or p2_error:
return initial_pw, p1_error, p2_error
initial_pw.fleets.extend(p1_fleets)
initial_pw.fleets.extend(p2_fleets)
# Grow planets
for planet in initial_pw.planets:
if planet.owner > 0:
planet.num_ships += planet.growth_rate
# Decrement fleet numbers
for fleet in initial_pw.fleets:
fleet.turns_remaining -= 1
# Battle
arriving_counts = [[0,0,0] for p in initial_pw.planets]
for fleet in initial_pw.fleets:
if fleet.turns_remaining == 0:
dst,owner,num = (fleet.destination_planet,
fleet.owner,
fleet.num_ships)
arriving_counts[dst][owner] += num
for planet, counts in zip(initial_pw.planets, arriving_counts):
if sum(counts) > 0:
counts[planet.owner] += planet.num_ships
owner, num = resolve(counts, planet.owner)
planet.owner = owner
planet.num_ships = num
initial_pw.fleets = [fleet for fleet in initial_pw.fleets
if fleet.turns_remaining > 0]
return initial_pw, None, None
def run_game(pw, bot_one, bot_two, timeoutms, num_turns=200,
output_file="testout.txt", verbose=False, serial=False):
try:
if output_file:
of = open(output_file, "w")
of.write(pw.dump_state(first_turn=True))
of.flush()
for turn in xrange(1, num_turns+1):
# get the moves from each player
# if both crash, draw. if one crashes, it loses
try:
timeout = timeoutms
if turn == 1:
timeout *= 3
bot_one.send_input(output_game_state(pw, False), timeout)
if serial:
bot_one.wait(timeoutms)
bot_two.send_input(output_game_state(pw, True), timeout)
try:
moves_one, ok_one = bot_one.wait(timeout)
except:
moves_one, ok_one = "EXCEPT", False
try:
moves_two, ok_two = bot_two.wait(timeout)
except:
moves_two, ok_two = "EXCEPT", False
except:
print "Got an error running the bots."
raise
if not (ok_one or ok_two):
return "Draw! p1: %s, p2: %s" % (moves_one, moves_two)
if not ok_one:
return "Player 2 Wins (p1: %s)" % moves_one
if not ok_two:
return "Player 1 Wins (p2: %s)" % moves_two
# update the game state
pw, p1_error, p2_error = game_step(pw, moves_one, moves_two)
if output_file:
of.write(pw.dump_state(False))
of.flush()
if (p1_error and p2_error):
return "Draw! p1: %s, p2: %s" % (p1_error, p2_error)
if p1_error:
return "Player 2 Wins (p1: %s)" % p1_error
if p2_error:
return "Player 1 Wins (p2: %s)" % p2_error
counts = [0,0,0]
rates = [0,0,0]
for p in pw.planets:
counts[p.owner] += p.num_ships
rates[p.owner] += p.growth_rate
for f in pw.fleets:
counts[f.owner] += f.num_ships
if verbose:
s = ("turn %3d counts: [%4s, %4s] rates: [%3s, %3s] count diff: %5d"
% (turn,
counts[1], counts[2], rates[1], rates[2],
counts[1] - counts[2]))
sys.stderr.write("\r%-50s" % s)
# check if they made bad moves
p1_alive = pw.IsAlive(1)
p2_alive = pw.IsAlive(2)
if not (p1_alive or p2_alive):
return "Draw! : both out of ships"
if not p1_alive:
return "Player 2 Wins in %d turns" % turn
if not p2_alive:
return "Player 1 Wins in %d turns" % turn
if counts[1] == counts[2]:
return "Draw! in %d moves" % turn
elif counts[1] > counts[2]:
return "Player 1 Wins in %d turns (%d to %d)" % (turn, counts[1],
counts[2])
elif counts[2] > counts[1]:
return "Player 2 Wins in %d turns (%d to %d)" % (turn, counts[2],
counts[1])
else:
raise "This should never happen"
finally:
if output_file:
of.close()