import string import types import whrandom import math import warparse import warlib import warevents class Sim: "The Sim class maintains and operates a warbot simulation." def __init__(self, configFile): """Sim.__init__(self): set up the simulation""" print "Loading config file..." cfg = warparse.parse(configFile) warparse.validate(cfg) print "Read config file." ### load hardware, object defns, etc from subdirs? # create the simulation world self.world = world = SimWorld(cfg) # create the controller for the simulation m = __import__(cfg.sim.system) self.controller = c = m.Controller(world) # create viewer for the simulation if hasattr(cfg.sim, 'viewer'): m = __import__(cfg.sim.viewer) v = m.Viewer(world) world.AddViewer(v) # add the robots to the world and the controller for name, inst in cfg.bot.items(): bot = world.AddBot(name, inst) params = inst.params if type(params) == types.ListType: params = tuple(params) else: params = (params,) c.addBot(bot, inst.spec, params) self.cfg = cfg def run(self): "Run the simulation." self.controller.run() class SimWorld: """The SimWorld class represents the bots' world. It is responsible for implementing all the laws of physics in the game. It keeps track of all the variables, including bot states, flying projectiles, etc.; and it has one main external method (Update), which must be called with a reasonably small time step by the engine.""" def __init__(self, cfg): self.objects = [ ] self.viewers = [ ] self.sizex = string.atoi(cfg.arena.size[0]) self.sizey = string.atoi(cfg.arena.size[1]) def AddBot(self, name, cfg): # figure out where to put the thing ### this could do "better" placement if desired x, y = self.PlaceBot(cfg) print 'Bot "%s" placed at %d, %d.' % (name, x, y) bot = SimBot(name, cfg, x, y) # add the bot to the world self.AddObject(bot) return bot def AddViewer(self, v): v.world = self self.viewers.append(v) def RemoveViewer(self, v): del v.world self.viewers.remove(v) def AddObject(self, ob): ob.world = self self.objects.append(ob) for v in self.viewers: v.AddObject(ob) def RemoveObject(self, ob): # remove the circular ref del ob.world self.objects.remove(ob) for v in self.viewers: v.RemoveObject(ob) def PlaceBot(self, inst): "Return an x,y coordinate for placing the given bot." ### inst could contain config params such as size/shape/etc # figure out where to place the robot ### 0 is probably too small... need to figure out margins x = whrandom.randint(0, self.sizex) y = whrandom.randint(0, self.sizey) return x, y def Update(self, timestep=1): """Sim.Update(self, timestep): update the simulation, given than the specified amount of time has passed.""" # look for collisions between all pairs of objects for i in range(len(self.objects)-1): for j in range(i+1, len(self.objects)): ob1 = self.objects[i] ob2 = self.objects[j] if collide(ob1, ob2, timestep): #print 'collide:', ob1, ob2 ob1.OnCollision(ob2) ob2.OnCollision(ob1) # look for wall collisions ### need code # look for dead objects i = 0 while i < len(self.objects): ob = self.objects[i] if ob.hp <= 0: ob.Die() self.RemoveObject(ob) else: i = i + 1 # move all the objects for ob in self.objects: ob.Update(timestep) #if ob.dx or ob.dy: # print "%s at: %.3f, %.3f" % (ob, ob.x, ob.y) for v in self.viewers: v.Update() class SimObject(warevents.mixinEventManager): """A SimObject is any "physical" object in the simulation -- including bots, projectiles, hunks of wreckage, etc. This class should be considered private to class Sim, and not accessed elsewhere.""" def __init__(self, x, y, dx=0, dy=0, hp=1, size=1): """SimObject.__init__(self,world,x,y): init self at position x,y""" # initialize the event manager; we aren't interested in any events warevents.mixinEventManager.__init__(self, []) self.x = x # x,y is current position self.y = y self.hp = hp self.size = size # dx, dy is the current velocity ### we might want to switch to polar coords ### definitely: use heading and speed. add methods to get dx/dy. self.dx = dx self.dy = dy def Update(self, timestep=1): """SimObject.Update(self, timestep): update self over the given timestep. Called from Sim.Update().""" self.x = self.x + self.dx * timestep self.y = self.y + self.dy * timestep def TakeDamage(self, damage): self.hp = self.hp - damage def OnCollision(self, target): pass def Die(self): pass class SimBot(SimObject): """A SimBot is the physical simulation of a bot in the game. This should not be confused with the bot program, which is supplied by the player.""" def __init__(self, name, cfg, x, y): SimObject.__init__(self, x, y, size=10) self.name = name self.cfg = cfg # this bot's config self.hp = 100 self.energy = 2000 self.heading = self.turretAngle = whrandom.randint(0, 359) def Update(self, timestep): SimObject.Update(self, timestep) self.energy = self.energy + int(timestep) # do other bot-specific updating here as well! def Radar(self): "Ping with the radar." # use an object to simulate the radar ping to look for a collision with # other objects rad = self.turretAngle * math.pi / 180 speed = self.world.sizex + self.world.sizey dx = speed * math.cos(rad) dy = speed * math.sin(rad) radar = SimObject(self.x, self.y, dx, dy) for ob in self.world.objects: if ob != self and collide(radar, ob): return math.sqrt((self.x - ob.x) ** 2 + (self.y - ob.y) ** 2), warlib.ROBOT ### return the distance to the wall sometime return 0, warlib.WALL def Fire(self): bulletSize = 1 ### should be based on weapon bullet = SimBullet(self.x, self.y, self.turretAngle, 100, 10, bulletSize, self.size + bulletSize + 1) self.world.AddObject(bullet) def Die(self): ### what to do? pass class SimBullet(SimObject): """A SimBullet is the physical simulation of a "bullet" in the game.""" def __init__(self, x, y, heading, speed, strength, size=1, delta=0): #print 'bullet launched:', x, y, heading, speed, strength, size, delta rad = heading * math.pi / 180 x = x + delta * math.cos(rad) y = y + delta * math.sin(rad) SimObject.__init__(self, x, y, speed * math.cos(rad), speed * math.sin(rad), size=size) self.strength = strength def OnCollision(self, target): # smash the target target.TakeDamage(self.strength) # we're dead now self.hp = 0 def collide(ob1, ob2, timestep=1): "Determine if two objects collide during this timestep." # compute some key constants k1 = ob1.x - ob2.x k2 = ob1.dx - ob2.dx k3 = ob1.y - ob2.y k4 = ob1.dy - ob2.dy if k2 == 0 and k4 == 0: # the two objects are travelling in parallel. see if they are colliding # right at this moment t = 0 else: # compute the time when they will be closest to each other t = - (k1 * k2 + k3 * k4) / (k2 * k2 + k4 * k4) if t < 0 or t > timestep: # they won't collide during this timestep return 0 # compute their distance at the critical time d2 = (k1 + k2 * t) ** 2 + (k3 + k4 * t) ** 2 hitdist = (ob1.size + ob2.size) ** 2 return d2 <= hitdist ### objects for armor, weapons, advanced detection systems, motor control...