ant
self.leaf_id = None
def check_conditions(self):
leaf = self.ant.world.get(self.ant.leaf_id)
if leaf is None:
return "exploring"
if self.ant.location.get_distance_to(leaf.location) < 5:
self.ant.carry(leaf.image)
self.ant.world.remove_entity(leaf)
return "delivering"
return None
def entry_actions(self):
leaf = self.ant.world.get(self.ant.leaf_id)
if leaf is not None:
self.ant.destination = leaf.location
self.ant.speed = 160 + randint(-20,20)
class AntStateDelivering(State):
def __init__(self, ant):
State.__init__(self, "delivering")
self.ant = ant
def check_conditions(self):
if Vector2D(*NestLocation).get_distance_to(self.ant.location) < NestSize:
if randint(1, 10) == 1:
self.ant.drop(self.ant.world.background)
return "exploring"
return None
def entry_actions(self):
self.ant.speed = 60
random_offset = Vector2D(randint(-20,20), randint(-20,20))
self.ant.destination = Vector2D(*NestLocation) + random_offset
class AntStateHunting(State):
def __init__(self, ant):
State.__init__(self, "hunting")
self.ant = ant
self.got_kill = False
def do_actions(self):
spider = self.ant.world.get(self.ant.spider_id)
if spider is None:
return
self.ant.destination = spider.location
if self.ant.location.get_distance_to(spider.location) < 15:
if randint(1,5) == 1:
spider.bitten()
if spider.health <= 0:
self.ant.carry(spider.image)
self.ant.world.remove_entity(spider)
self.got_kill = True
def check_conditions(self):
if self.got_kill:
return "delivering"
spider = self.ant.world.get(self.ant.spider_id)
if spider is None:
return "exploring"
if spider.location.get_distance_to(NestLocation) > NestSize * 3:
return "exploring"
return None
def entry_actions(self):
self.speed = 160 + randint(0,50)
def exit_actions(self):
self.got_kill = False
def run():
pygame.init()
screen = pygame.display.set_mode(ScreenSize, 0, 32)
world = World()
w,h = ScreenSize
clock = pygame.time.Clock()
ant_image = pygame.image.load(ImgPath + "ant.png").convert_alpha()
leaf_image = pygame.image.load(ImgPath + "leaf.png").convert_alpha()
spider_image = pygame.image.load(ImgPath + "spider.png").convert_alpha()
for ant_nr in range(AntCount):
ant = Ant(world, ant_image)
ant.location = Vector2D(randint(0,w), randint(0,h))
ant.brain.set_state("exploring")
world.add_entity(ant)
while True:
for e in pygame.event.get():
if e.type == QUIT:
return
time_passed = clock.tick(30)
if randint(1,10) == 1:
leaf = Leaf(world, leaf_image)
leaf.location = Vector2D(randint(0,w), randint(0,h))
world.add_entity(leaf)
if randint(1,100) == 1:
spider = Spider(world, spider_image)
spider.location = Vector2D(-50, randint(0,h))
spider.destination = Vector2D(w+50, randint(0,h))
world.add_entity(spider)
world.process(time_passed)
world.render(screen)
pygame.display.update()
antworld.py
运行效果图如下:
完整源代码下载:http://download.csdn.net/download/china_x01/10125074
|