import random import math import core.model from core.utils import AStar, Alignment from core.model import Environment from core.event import SimulationStartedEvent, AgentMovedEvent, AgentKillEvent from event import MarbleMoveRequest, MarbleSpawnRequest class Marble(core.model.Agent): (TYPE1, TYPE2, TYPE3, TYPE4, TYPE5, TYPE6, TYPE7) = range(7) def __init__(self, disp, type): core.model.Agent.__init__(self, disp) self.type = type def move(self, goal): if goal.occupant != None: return def heur(a, b): return math.fabs(a.pos[0] - b.pos[0]) + math.fabs(a.pos[1] - b.pos[1]) a = AStar(heur) if a.path_exists(self.sector, goal): self.sector.occupant = None goal.occupant = self self.sector = goal self.disp.post(AgentMovedEvent(self)) self.disp.post(MarbleSpawnRequest(3)) else: print "Impossible move!" def notify(self, e): if isinstance(e, MarbleMoveRequest): if e.marble == self: self.move(e.goal) class CGSimulation(core.model.Simulation): def __init__(self, disp): core.model.Simulation.__init__(self, disp, Environment(disp, 9, 9)) self.marbles = [] self.align_test = Alignment(lambda x,y: x.type == y.type, 5) # Create "count" marbles in free sectors def spawn_marbles(self, count): free_sectors = self.env.get_free_sectors() for i in range(count): if len(free_sectors) == 0: return m = Marble(self.disp, random.randint(Marble.TYPE1, Marble.TYPE7)) self.marbles.append(m) sect = random.choice(free_sectors) free_sectors.remove(sect) m.place(sect) self.disp.post(AgentMovedEvent(m)) def notify(self, e): core.model.Simulation.notify(self, e) if isinstance(e, SimulationStartedEvent): self.spawn_marbles(count=3) elif isinstance(e, AgentMovedEvent): print "checking aligments..." r = self.align_test.check(e.agent) print r if len(r) > 0: print "Alignment found !" for sector in r: self.disp.post(AgentKillEvent(sector.occupant)) sector.occupant = None elif isinstance(e, MarbleSpawnRequest): self.spawn_marbles(count=e.count) elif isinstance(e, AgentKillEvent): self.marbles.remove(e.agent)