用Python和Pygame写游戏-从入门到精通(16)

来源:互联网 发布:联通免费发短信软件 编辑:程序博客网 时间:2024/06/06 09:45

本文转自:http://eyehere.net/2011/python-pygame-novice-professional-16/


经历了长年的艰苦卓绝的披星戴月的惨绝人寰的跋山涉水,我们终于接近了AI之旅的尾声(好吧,实际上我们这才是刚刚开始)。这一次真正展示一下这几回辛勤工作的结果,最后的画面会是这个样子:

蚁巢系统AI演示

下面给出完整代码(注意需要gameobjects库才可以运行,参考之前的向量篇):

[python] view plain copy
  1. SCREEN_SIZE = (640480)  
  2. NEST_POSITION = (320240)  
  3. ANT_COUNT = 20  
  4. NEST_SIZE = 100.  
  5.   
  6. import pygame  
  7. from pygame.locals import *  
  8.   
  9. from random import randint, choice  
  10. from gameobjects.vector2 import Vector2  
  11.   
  12. class State(object):  
  13.     def __init__(self, name):  
  14.         self.name = name  
  15.     def do_actions(self):  
  16.         pass  
  17.     def check_conditions(self):  
  18.         pass  
  19.     def entry_actions(self):  
  20.         pass  
  21.     def exit_actions(self):  
  22.         pass          
  23.   
  24. class StateMachine(object):  
  25.     def __init__(self):  
  26.         self.states = {}  
  27.         self.active_state = None  
  28.   
  29.     def add_state(self, state):  
  30.         self.states[state.name] = state  
  31.   
  32.     def think(self):  
  33.         if self.active_state is None:  
  34.             return  
  35.         self.active_state.do_actions()  
  36.         new_state_name = self.active_state.check_conditions()  
  37.         if new_state_name is not None:  
  38.             self.set_state(new_state_name)  
  39.   
  40.     def set_state(self, new_state_name):  
  41.         if self.active_state is not None:  
  42.             self.active_state.exit_actions()  
  43.         self.active_state = self.states[new_state_name]  
  44.         self.active_state.entry_actions()  
  45.   
  46. class World(object):  
  47.     def __init__(self):  
  48.         self.entities = {}  
  49.         self.entity_id = 0  
  50.         self.background = pygame.surface.Surface(SCREEN_SIZE).convert()  
  51.         self.background.fill((255255255))  
  52.         pygame.draw.circle(self.background, (200255200), NEST_POSITION, int(NEST_SIZE))  
  53.   
  54.     def add_entity(self, entity):  
  55.         self.entities[self.entity_id] = entity  
  56.         entity.id = self.entity_id  
  57.         self.entity_id += 1  
  58.   
  59.     def remove_entity(self, entity):  
  60.         del self.entities[entity.id]  
  61.   
  62.     def get(self, entity_id):  
  63.         if entity_id in self.entities:  
  64.             return self.entities[entity_id]  
  65.         else:  
  66.             return None  
  67.   
  68.     def process(self, time_passed):  
  69.         time_passed_seconds = time_passed / 1000.0  
  70.         for entity in self.entities.values():  
  71.             entity.process(time_passed_seconds)  
  72.   
  73.     def render(self, surface):  
  74.         surface.blit(self.background, (00))  
  75.         for entity in self.entities.itervalues():  
  76.             entity.render(surface)  
  77.   
  78.     def get_close_entity(self, name, location, range=100.):  
  79.         location = Vector2(*location)  
  80.         for entity in self.entities.itervalues():  
  81.             if entity.name == name:  
  82.                 distance = location.get_distance_to(entity.location)  
  83.                 if distance < range:  
  84.                     return entity  
  85.         return None  
  86.   
  87. class GameEntity(object):  
  88.   
  89.     def __init__(self, world, name, image):  
  90.   
  91.         self.world = world  
  92.         self.name = name  
  93.         self.image = image  
  94.         self.location = Vector2(00)  
  95.         self.destination = Vector2(00)  
  96.         self.speed = 0.  
  97.         self.brain = StateMachine()  
  98.         self.id = 0  
  99.   
  100.     def render(self, surface):  
  101.         x, y = self.location  
  102.         w, h = self.image.get_size()  
  103.         surface.blit(self.image, (x-w/2, y-h/2))     
  104.   
  105.     def process(self, time_passed):  
  106.         self.brain.think()  
  107.         if self.speed > 0. and self.location != self.destination:  
  108.             vec_to_destination = self.destination - self.location  
  109.             distance_to_destination = vec_to_destination.get_length()  
  110.             heading = vec_to_destination.get_normalized()  
  111.             travel_distance = min(distance_to_destination, time_passed * self.speed)  
  112.             self.location += travel_distance * heading  
  113.   
  114. class Leaf(GameEntity):  
  115.     def __init__(self, world, image):  
  116.         GameEntity.__init__(self, world, "leaf", image)  
  117.   
  118. class Spider(GameEntity):  
  119.     def __init__(self, world, image):  
  120.         GameEntity.__init__(self, world, "spider", image)  
  121.         self.dead_image = pygame.transform.flip(image, 01)  
  122.         self.health = 25  
  123.         self.speed = 50. + randint(-2020)  
  124.   
  125.     def bitten(self):  
  126.         self.health -= 1  
  127.         if self.health <= 0:  
  128.             self.speed = 0.  
  129.             self.image = self.dead_image  
  130.         self.speed = 140.  
  131.   
  132.     def render(self, surface):  
  133.         GameEntity.render(self, surface)  
  134.         x, y = self.location  
  135.         w, h = self.image.get_size()  
  136.         bar_x = x - 12  
  137.         bar_y = y + h/2  
  138.         surface.fill( (25500), (bar_x, bar_y, 254))  
  139.         surface.fill( (02550), (bar_x, bar_y, self.health, 4))  
  140.   
  141.     def process(self, time_passed):  
  142.         x, y = self.location  
  143.         if x > SCREEN_SIZE[0] + 2:  
  144.             self.world.remove_entity(self)  
  145.             return  
  146.         GameEntity.process(self, time_passed)  
  147.   
  148. class Ant(GameEntity):  
  149.     def __init__(self, world, image):  
  150.         GameEntity.__init__(self, world, "ant", image)  
  151.         exploring_state = AntStateExploring(self)  
  152.         seeking_state = AntStateSeeking(self)  
  153.         delivering_state = AntStateDelivering(self)  
  154.         hunting_state = AntStateHunting(self)  
  155.         self.brain.add_state(exploring_state)  
  156.         self.brain.add_state(seeking_state)  
  157.         self.brain.add_state(delivering_state)  
  158.         self.brain.add_state(hunting_state)  
  159.         self.carry_image = None  
  160.   
  161.     def carry(self, image):  
  162.         self.carry_image = image  
  163.   
  164.     def drop(self, surface):  
  165.         if self.carry_image:  
  166.             x, y = self.location  
  167.             w, h = self.carry_image.get_size()  
  168.             surface.blit(self.carry_image, (x-w, y-h/2))  
  169.             self.carry_image = None  
  170.   
  171.     def render(self, surface):  
  172.         GameEntity.render(self, surface)  
  173.         if self.carry_image:  
  174.             x, y = self.location  
  175.             w, h = self.carry_image.get_size()  
  176.             surface.blit(self.carry_image, (x-w, y-h/2))  
  177.   
  178. class AntStateExploring(State):  
  179.     def __init__(self, ant):  
  180.         State.__init__(self"exploring")  
  181.         self.ant = ant  
  182.   
  183.     def random_destination(self):  
  184.         w, h = SCREEN_SIZE  
  185.         self.ant.destination = Vector2(randint(0, w), randint(0, h))      
  186.   
  187.     def do_actions(self):  
  188.         if randint(120) == 1:  
  189.             self.random_destination()  
  190.   
  191.     def check_conditions(self):  
  192.         leaf = self.ant.world.get_close_entity("leaf"self.ant.location)  
  193.         if leaf is not None:  
  194.             self.ant.leaf_id = leaf.id  
  195.             return "seeking"  
  196.         spider = self.ant.world.get_close_entity("spider", NEST_POSITION, NEST_SIZE)  
  197.         if spider is not None:  
  198.             if self.ant.location.get_distance_to(spider.location) < 100.:  
  199.                 self.ant.spider_id = spider.id  
  200.                 return "hunting"  
  201.         return None  
  202.   
  203.     def entry_actions(self):  
  204.         self.ant.speed = 120. + randint(-3030)  
  205.         self.random_destination()  
  206.   
  207. class AntStateSeeking(State):  
  208.     def __init__(self, ant):  
  209.         State.__init__(self"seeking")  
  210.         self.ant = ant  
  211.         self.leaf_id = None  
  212.   
  213.     def check_conditions(self):  
  214.         leaf = self.ant.world.get(self.ant.leaf_id)  
  215.         if leaf is None:  
  216.             return "exploring"  
  217.         if self.ant.location.get_distance_to(leaf.location) < 5.0:  
  218.             self.ant.carry(leaf.image)  
  219.             self.ant.world.remove_entity(leaf)  
  220.             return "delivering"  
  221.         return None  
  222.   
  223.     def entry_actions(self):  
  224.         leaf = self.ant.world.get(self.ant.leaf_id)  
  225.         if leaf is not None:  
  226.             self.ant.destination = leaf.location  
  227.             self.ant.speed = 160. + randint(-2020)  
  228.   
  229. class AntStateDelivering(State):  
  230.     def __init__(self, ant):  
  231.         State.__init__(self"delivering")  
  232.         self.ant = ant  
  233.   
  234.     def check_conditions(self):  
  235.         if Vector2(*NEST_POSITION).get_distance_to(self.ant.location) < NEST_SIZE:  
  236.             if (randint(110) == 1):  
  237.                 self.ant.drop(self.ant.world.background)  
  238.                 return "exploring"  
  239.         return None  
  240.   
  241.     def entry_actions(self):  
  242.         self.ant.speed = 60.  
  243.         random_offset = Vector2(randint(-2020), randint(-2020))  
  244.         self.ant.destination = Vector2(*NEST_POSITION) + random_offset         
  245.   
  246. class AntStateHunting(State):  
  247.     def __init__(self, ant):  
  248.         State.__init__(self"hunting")  
  249.         self.ant = ant  
  250.         self.got_kill = False  
  251.   
  252.     def do_actions(self):  
  253.         spider = self.ant.world.get(self.ant.spider_id)  
  254.         if spider is None:  
  255.             return  
  256.         self.ant.destination = spider.location  
  257.         if self.ant.location.get_distance_to(spider.location) < 15.:  
  258.             if randint(15) == 1:  
  259.                 spider.bitten()  
  260.                 if spider.health <= 0:  
  261.                     self.ant.carry(spider.image)  
  262.                     self.ant.world.remove_entity(spider)  
  263.                     self.got_kill = True  
  264.   
  265.     def check_conditions(self):  
  266.         if self.got_kill:  
  267.             return "delivering"  
  268.         spider = self.ant.world.get(self.ant.spider_id)  
  269.         if spider is None:  
  270.             return "exploring"  
  271.         if spider.location.get_distance_to(NEST_POSITION) > NEST_SIZE * 3:  
  272.             return "exploring"  
  273.         return None  
  274.   
  275.     def entry_actions(self):  
  276.         self.speed = 160. + randint(050)  
  277.   
  278.     def exit_actions(self):  
  279.         self.got_kill = False  
  280.   
  281. def run():  
  282.     pygame.init()  
  283.     screen = pygame.display.set_mode(SCREEN_SIZE, 032)  
  284.     world = World()  
  285.     w, h = SCREEN_SIZE  
  286.     clock = pygame.time.Clock()  
  287.     ant_image = pygame.image.load("ant.png").convert_alpha()  
  288.     leaf_image = pygame.image.load("leaf.png").convert_alpha()  
  289.     spider_image = pygame.image.load("spider.png").convert_alpha()  
  290.   
  291.     for ant_no in xrange(ANT_COUNT):  
  292.         ant = Ant(world, ant_image)  
  293.         ant.location = Vector2(randint(0, w), randint(0, h))  
  294.         ant.brain.set_state("exploring")  
  295.         world.add_entity(ant)  
  296.   
  297.     while True:  
  298.         for event in pygame.event.get():  
  299.             if event.type == QUIT:  
  300.                 return  
  301.         time_passed = clock.tick(30)  
  302.   
  303.         if randint(110) == 1:  
  304.             leaf = Leaf(world, leaf_image)  
  305.             leaf.location = Vector2(randint(0, w), randint(0, h))  
  306.             world.add_entity(leaf)  
  307.   
  308.         if randint(1100) == 1:  
  309.             spider = Spider(world, spider_image)  
  310.             spider.location = Vector2(-50, randint(0, h))  
  311.             spider.destination = Vector2(w+50, randint(0, h))  
  312.             world.add_entity(spider)  
  313.   
  314.         world.process(time_passed)  
  315.         world.render(screen)  
  316.   
  317.         pygame.display.update()  
  318.   
  319. if __name__ == "__main__":  
  320.     run()  

这个程序的长度超过了以往任何一个,甚至可能比我们写的加起来都要长一些。然而它可以展现给我们的也前所未有的惊喜。无数勤劳的小蚂蚁在整个地图上到处觅食,随机出现的叶子一旦被蚂蚁发现,就会搬回巢穴,而蜘蛛一旦出现在巢穴范围之内,就会被蚂蚁们群起而攻之,直到被驱逐出地图范围或者挂了,蜘蛛的尸体也会被带入巢穴。

这个代码写的不够漂亮,没有用太高级的语法,甚至都没有注释天哪……基本代码都在前面出现了,只是新引入了四个新的状态,AntStateExploringAntStateSeekingAntStateDeliveringAntStateHunting,意义的话前面已经说明。比如说AntStateExploring,继承了基本的Stat,这个状态的动作平时就是让蚂蚁以一个随机的速度走向屏幕随机一个点,在此过程中,check_conditions会不断检查周围的环境,发现了树叶或蜘蛛都会采取相应的措施(进入另外一个状态)。

游戏设计艺术中,创建一个漂亮的AI是非常有挑战性也非常有趣的事情。好的AI能让玩家沉浸其中,而糟糕的AI则让人感到非常乏味(有的时候AI中的一些bug被当作秘籍使用,也挺有意思的,不过如果到处是“秘籍”,可就惨了)。而且,AI是否足够聪明有时候并不与代码量直接相关,看看我们这个演示,感觉上去蚂蚁会合作攻击蜘蛛,而实际

阅读全文
0 0
原创粉丝点击