This repository has been archived by the owner on May 30, 2024. It is now read-only.
forked from jav/pybotwar
-
Notifications
You must be signed in to change notification settings - Fork 0
/
game.py
341 lines (297 loc) · 11.4 KB
/
game.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
# Copyright 2009-2014 Lee Harr
#
# This file is part of pybotwar.
# http://pybotwar.googlecode.com/
#
# Pybotwar is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# Pybotwar is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with Pybotwar. If not, see <http://www.gnu.org/licenses/>.
import subprocess
from subprocess import PIPE
import time
import random
import os
import logging
logger = logging.getLogger('PybotwarLogger')
import viewselect
view = viewselect.get_view_module()
import world
from world import box2d
import stats
import util
import conf
class Game(object):
def __init__(self, testmode=False, tournament=None):
self.testmode = testmode
self.tournament = tournament
self.models = {}
self.procs = {}
self.results = {}
self.timeouts = {}
self.rnd = 0
self.w = world.World()
self.cl = world.CL()
self.w.w.contactListener = self.cl
self.cl.w = self.w
def run(self):
self.load_robots()
if not self.nrobots:
self.finish()
return
while ((self.testmode and not self.tournament)
or len(self.procs) > 1) and not self.w.v.quit:
if self.rnd > 60 * conf.maxtime:
break
self.tick()
self.finish()
def robot_module_file(self, robot):
for d in util.get_robot_dirs():
fname = '%s.py' % robot
fpath = os.path.join(d, fname)
if os.path.exists(fpath):
return os.path.abspath(fpath)
return None
def load_robots(self):
robots = conf.robots
for robot in robots:
robotname = robot
while robotname in self.w.robots:
robotname += '_'
rfile = self.robot_module_file(robot)
if rfile is None:
continue
print 'STARTING', robotname, rfile
proc = subprocess.Popen([conf.subproc_python,
conf.subproc_main,
robot, rfile, robotname,
str(int(self.testmode))],
stdin=PIPE, stdout=PIPE)
try:
result = proc.stdout.readline().strip()
except IOError:
result = 'FAIL'
if result == 'START':
print 'STARTED'
model = self.w.makerobot(robot, robotname)
self.models[robotname] = model
self.procs[robotname] = proc
self.timeouts[robotname] = 0
elif result in ['ERROR', 'END']:
print 'ERROR!'
else:
print 'FAIL', result
self.nrobots = len(self.models)
self.t0 = int(time.time())
def tick(self):
procs = self.procs
nrobots = self.nrobots
timeouts = self.timeouts
w = self.w
rnd = self.rnd
result = ''
items = self.models.items()
random.shuffle(items)
for robotname, model in items:
if robotname not in self.procs:
continue
proc = procs[robotname]
if model._enable_debug is None:
pass
elif model._enable_debug:
line = 'DEBUG\n'
proc.stdin.write(line)
model._enable_debug = None
continue
else:
line = 'NODEBUG\n'
proc.stdin.write(line)
model._enable_debug = None
continue
health = model.health
body = model.body
pos = body.position
possens = '%s;%s' % (int(pos.x), int(pos.y))
tur = model.get_turretangle()
ping = '%s;%s;%s' % (model._pingtype,
model._pingangle,
model._pingdist)
gyro = model.gyro()
heat = int(model._cannonheat)
loading = int(model._cannonreload)
pinged = int(model._pinged == rnd - 1)
line = 'TICK:%s|HEALTH:%s|POS:%s|TUR:%s|PING:%s|GYRO:%s|HEAT:%s|LOADING:%s|PINGED:%s\n' % (rnd, health, possens, tur, ping, gyro, heat, loading, pinged)
#print robotname, line
if not model.alive:
model._outlasted = nrobots - len(procs)
del procs[robotname]
print 'DEAD robot', robotname, 'health is 0'
proc.stdin.flush()
proc.stdin.close()
proc.stdout.close()
proc.kill()
time.sleep(0.1)
model._commands = {'INACTIVE':'DEAD'}
continue
proc.stdin.write(line)
try:
result = proc.stdout.readline().strip()
except IOError:
print 'ERROR with', robotname
continue
if result == 'TIMEOUT':
timeouts[robotname] += 1
if timeouts[robotname] > 5:
del procs[robotname]
print 'REMOVED robot', robotname, 'due to excessive timeouts'
proc.stdin.flush()
proc.stdin.close()
proc.stdout.close()
proc.kill()
elif result == 'END':
del procs[robotname]
print 'FINISHED: robot', robotname
proc.stdin.flush()
proc.stdin.close()
proc.stdout.close()
proc.kill()
elif result == 'ERROR':
del procs[robotname]
print 'ERROR: robot', robotname
proc.stdin.flush()
proc.stdin.close()
proc.stdout.close()
proc.kill()
else:
timeouts[robotname] = 0
#print 'RR', result, 'RR'
commands = {}
try:
props = result.split('|')
for prop in props:
kind, val = prop.split(':')
try:
vconv = int(val)
except ValueError:
pass
else:
val = vconv
commands[kind] = val
except ValueError:
continue
#print 'KV', kind, val
#print 'R', model, 'R', result, 'R'
#print 'R', robotname, 'T', '%s -> %.3f' % (model._turretangletarget, model.turretjoint.angle)
model._commands = commands or {'INACTIVE':result}
for kind, val in commands.items():
if kind == 'FORCE':
# Make sure force is not more than 100% or less than -100%
val = min(val, 100)
val = max(-100, val)
force = conf.maxforce * val/100.0
localforce = box2d.b2Vec2(val, 0)
worldforce = body.GetWorldVector(localforce)
body.ApplyForce(worldforce, pos, True)
elif kind == 'TORQUE':
# Make sure torque is not more than 100% or less than -100%
val = min(val, 100)
val = max(-100, val)
torque = conf.maxtorque * val/100.0
body.ApplyTorque(torque, True)
elif kind == 'FIRE':
if val == '_':
# no fire
pass
elif val == 'X':
# non-exploding shell
w.makebullet(robotname)
else:
# exploding shell
ticks = int(60 * val / conf.bulletspeed)
w.makebullet(robotname, ticks)
elif kind == 'PING':
if val:
kind, angle, dist = w.makeping(robotname, rnd)
if kind is not None:
model._pingtype = kind[0]
model._pingangle = angle
model._pingdist = int(dist)
elif kind == 'TURRET':
val = min(val, 100)
val = max(-100, val)
torque = conf.turret_maxMotorSpeed * val/100.0
model.turretcontrol(torque)
w.step()
if not rnd%60:
print '%s seconds (%s real)' % (rnd/60, int(time.time())-self.t0)
self.rnd += 1
def enable_debug(self):
items = self.models.items()
for robotname, model in items:
model._enable_debug = True
def disable_debug(self):
items = self.models.items()
for robotname, model in items:
model._enable_debug = False
def finish(self, update_stats=True):
print 'FINISHING'
if hasattr(self, '_FINISHED'):
print 'ALREADY FINISHED'
return
self._FINISHED = True
models = self.models
testmode = self.testmode
nrobots = self.nrobots
procs = self.procs
tournament = self.tournament
alive = [model for model in models.values() if model.alive]
if not testmode and len(alive)==1:
model = alive[0]
print 'WINNER:', model.name
winner = model
model._outlasted = nrobots-1
elif not testmode:
winner = None
if self.rnd >= conf.maxtime*60:
print 'Battle stopped after maximum time:', conf.maxtime, 'seconds.'
else:
print 'Battle stopped after', int(self.rnd/60), 'seconds.'
print 'STILL ALIVE:'
for model in alive:
print ' ', model.name
else:
print 'Test mode ended'
winner = None
for robotname, model in models.items():
print robotname, 'caused', model._damage_caused, 'damage'
if robotname in procs:
line = 'FINISH\n'
proc = procs[robotname]
proc.stdin.write(line)
proc.stdin.flush()
proc.stdin.close()
proc.stdout.close()
del procs[robotname]
if winner is None and model.alive:
model._outlasted = nrobots - len(alive)
if model == winner:
win = 1
else:
win = 0
if update_stats and not testmode:
stats.update(model.kind, win, nrobots-1, model._outlasted,
model._damage_caused, model._kills)
if update_stats and tournament is not None:
stats.tournament_update(tournament,
model.kind, model.name, win,
nrobots-1, model._outlasted,
model._damage_caused,
model._kills)