moth/tanks/run_tanks.py

99 lines
2.4 KiB
Python
Raw Normal View History

#! /usr/bin/python
2009-10-08 11:15:06 -06:00
import asynchat
import asyncore
import optparse
2009-10-08 11:18:40 -06:00
import os
2009-10-08 09:04:07 -06:00
import shutil
2009-10-08 11:15:06 -06:00
import socket
2009-10-08 09:04:07 -06:00
import time
from tanks import Pflanzarr
T = 60*5
2009-10-08 09:04:07 -06:00
MAX_HIST = 30
2009-10-08 11:03:50 -06:00
HIST_STEP = 100
key = 'tanks:::2bac5e912ff2e1ad559b177eb5aeecca'
2009-10-08 16:42:26 -06:00
running = True
2009-10-08 11:03:50 -06:00
class Flagger(asynchat.async_chat):
"""Use to connect to flagd and submit the current flag holder."""
def __init__(self, addr, auth):
asynchat.async_chat.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect((addr, 6668))
self.push(auth + '\n')
self.flag = None
def handle_read(self):
msg = self.recv(4096)
raise ValueError("Flagger died: %r" % msg)
def handle_error(self):
# If we lose the connection to flagd, nobody can score any
# points. Terminate everything.
2009-10-08 16:42:26 -06:00
running = False
2009-10-08 11:03:50 -06:00
asyncore.close_all()
asynchat.async_chat.handle_error(self)
def set_flag(self, team):
if team:
eteam = team
else:
eteam = ''
self.push(eteam + '\n')
self.flag = team
2009-10-08 11:19:46 -06:00
def run_tanks(args, turns, flagger):
p = Pflanzarr.Pflanzarr(args[0], args[1])
p.run(turns)
2009-10-08 09:04:07 -06:00
path = os.path.join(args[0], 'results')
files = os.listdir(path)
gameNums = []
for file in files:
try:
gameNums.append( int(file) )
except:
continue
gameNums.sort(reverse=True)
highest = gameNums[0]
for num in gameNums:
if highest - MAX_HIST > num and not (num % HIST_STEP == 0):
2009-10-08 11:18:40 -06:00
shutil.rmtree(os.path.join(path, str(num)))
2009-10-08 09:04:07 -06:00
2009-10-08 11:03:50 -06:00
try:
winner = open('/var/lib/tanks/winner').read().strip()
except:
winner = None
flagger.set_flag(winner)
def main():
parser = optparse.OptionParser('DATA_DIR easy|medium|hard MAX_TURNS')
opts, args = parser.parse_args()
if (len(args) != 3) or (args[1] not in ('easy', 'medium', 'hard')):
parser.error('Wrong number of arguments')
try:
turns = int(args[2])
except:
parser.error('Invalid number of turns')
flagger = Flagger('localhost', key)
lastrun = 0
while True:
asyncore.loop(60, count=1)
2009-10-08 16:42:26 -06:00
if not running:
break
2009-10-08 11:03:50 -06:00
now = time.time()
if now - lastrun >= 60:
2009-10-08 11:19:46 -06:00
run_tanks(args, turns, flagger)
2009-10-08 11:03:50 -06:00
lastrun = now
if __name__ == '__main__':
main()