跳至正文
View Categories

< 1 min read

植物大战僵尸7 #

  1. 子弹类的创建及移动
  2. 子弹类的碰撞检测及攻击
  3. 子弹类的存储及加载

子弹类的创建及移动 #

本小节主要介绍创建子弹类PeaBullet()及在屏幕范围内实现子弹往右移动

#7 豌豆子弹类
class PeaBullet(pygame.sprite.Sprite):
    def __init__(self,peashooter):
        self.live = True
        self.image = pygame.image.load('imgs/peabullet.png')
        self.damage = 50
        self.speed  = 10
        self.rect = self.image.get_rect()
        self.rect.x = peashooter.rect.x + 60
        self.rect.y = peashooter.rect.y + 15

    #7 在屏幕范围内,实现往右移动
    def move_bullet(self):

        if self.rect.x < scrrr_width:
            self.rect.x += self.speed
        else:
            self.live = False

    def display_peabullet(self):
        MainGame.window.blit(self.image,self.rect)

子弹类的碰撞检测及攻击 #

本小节主要介绍子弹碰到僵尸时的攻击触发及功能设计,在子弹类class PeaBullet()中添加函数hit_zombie()

#class PeaBullet(pygame.sprite.Sprite):
#7 新增,子弹与僵尸的碰撞
    def hit_zombie(self):
        for zombie in MainGame.zombie_list:
            if pygame.sprite.collide_rect(self,zombie):
                #打中僵尸之后,修改子弹的状态,
                self.live = False
                #僵尸掉血
                zombie.hp -= self.damage

子弹类的存储及加载 #

本小节主要介绍存储所有豌豆子弹的列表和加载所有子弹的方法。在主程序类class MainGame()中添加储存子弹的列表及子弹加载方法。

同时,由于游戏界面需要不断更新,需在主程序类class MainGame()中的开始游戏函数def start_game()中的循环while not GAMEOVER:中添加子弹加载函数self.load_peabullets()。

   
class MainGame():

    #7 存储所有豌豆子弹的列表
    peabullet_list = []

    #7 加载所有子弹的方法
    def load_peabullets(self):
        for b in MainGame.peabullet_list:
            if b.live:
                b.display_peabullet()
                b.move_bullet()
                #7  调用子弹是否打中僵尸的方法
                b.hit_zombie()
            else:
                MainGame.peabullet_list.remove(b) 

    #def start_game(self):

        while not GAMEOVER:
            #7  调用加载所有子弹的方法
            self.load_peabullets()


小结 #

本节主要介绍了植物大战游戏中子弹类的创建、移动及攻击触发方式,以及存储和加载