import core.model from core.event import SimulationStartedEvent, AgentMoveRequest, AgentMovedEvent from core.model import DIRECTION_UP, DIRECTION_DOWNRIGHT import random class Ball(core.model.Agent): def __init__(self, disp): core.model.Agent.__init__(self, disp) self.mov = random.randint(DIRECTION_UP, DIRECTION_DOWNRIGHT) def move(self): dir = self.mov if self.sector.move_possible(dir): self.sector.occupant = None self.sector = self.sector.neighbors[dir] self.sector.occupant = self self.disp.post(AgentMovedEvent(self)) else: # If there's something on the case, shock it, then reverse our movement if self.sector.neighbors[dir] and self.sector.neighbors[dir].occupant != None: self.sector.neighbors[dir].occupant.mov = self.mov self.mov = core.model.reverse_dir(dir) if self.sector.move_possible(dir): self.sector.occupant = None self.sector = self.sector.neighbors[dir] self.sector.occupant = self self.disp.post(AgentMovedEvent(self)) def notify(self, e): if isinstance(e, SimulationStartedEvent): self.place(e.sim.env.sectors[random.randint(0, e.sim.env.h-1)][random.randint(0, e.sim.env.w-1)]) elif isinstance(e, AgentMoveRequest): self.move() class BallSimulation(core.model.Simulation): def __init__(self, disp, env, ball_count): core.model.Simulation.__init__(self, disp, env) # Create agents self.agents = [] for i in range(ball_count): self.agents.append(Ball(disp))