#!/usr/local/bin/python import sys import thread import time import traceback import warutil class Controller: def __init__(self, world): self.world = world self.locks = [] self.bots = [] def addBot(self, bot, spec, params): self.bots.append((spec, bot, FunctionWrapper, None) + params) l = thread.allocate_lock() self.locks.append(l) l.acquire_lock() def run(self): # start all the bots self.running = len(self.bots) for i in range(self.running): thread.start_new_thread(self.start_bot, (i,)) # let the first bot go ### pick one randomly! self.idx = 0 self.locks[self.idx].release() # spin until done while self.running > 1: time.sleep(1) def start_bot(self, i): # wait up a bit for all the threads to spin up self.locks[i].acquire_lock() # run the bot print "bot #%d starting." % i sys.settrace(self.trace) try: apply(warutil.launch_bot, self.bots[i]) except: ### maybe log the error? traceback.print_exc() sys.settrace(None) # the bot is done print "bot #%d done." % i self.running = self.running - 1 # let the next guy go ahead self.round_robin() # returning ends this thread... def round_robin(self): "Wake up the next bot." if self.idx + 1 == len(self.locks): self.world.Update() # mark all dead robots for i in range(len(self.bots)): botinfo = self.bots[i] if botinfo and botinfo[1].hp <= 0: print "Bot #%d just died." % i self.bots[i] = None self.running = self.running - 1 self.idx = -1 if self.running > 1: while 1: self.idx = self.idx + 1 if self.bots[self.idx]: break self.locks[self.idx].release() def trace(self, frame, why, arg): if why == 'line': fname = frame.f_code.co_filename #print frame.f_code.co_filename, frame.f_lineno if fname == '__bot__': # get my lock lock = self.locks[self.idx] # let the next guy go self.round_robin() # block lock.acquire_lock() return self.trace class FunctionWrapper: "Used to wrap warlib functions." def __init__(self, bot, func, extraData): self.prepend = (bot,) self.func = func def __call__(self, *args, **kw): return apply(self.func, self.prepend + args, kw)