跳至正文
View Categories

1 min read

植物大战僵尸4 #

  1. 植物类加载及错误提示
  2. 向日葵类的创建及功能
  3. 事件处理-向日葵装填

植物类加载及错误提示 #

本小节主要介绍创建植物类class Plant()的方法,包括植物加载方法,游戏图片加载报错处理。

同时在主程序类中添加储存植物的列表

#4 图片加载报错处理
LOG = '文件:{}中的方法:{}出错'.format(__file__,__name__)
#4 植物类
class Plant(pygame.sprite.Sprite):
    def __init__(self):
        super(Plant, self).__init__()
        self.live=True

    # 加载图片
    def load_image(self):
        if hasattr(self, 'image') and hasattr(self, 'rect'):
            MainGame.window.blit(self.image, self.rect)
        else:
            print(LOG)

class MainGame():
    
    #4 存储所有植物的列表
    plants_list = []

向日葵类的创建及功能 #

本小节主要介绍创建向日葵类class Sunflower()的方法,包括时间计数器的使用,以及将图片实时加载到窗口中的方法

#5 向日葵类
class Sunflower(Plant):
    def __init__(self,x,y):
        super(Sunflower, self).__init__()
        self.image = pygame.image.load('imgs/sunflower.png')
        self.rect = self.image.get_rect()
        self.rect.x = x
        self.rect.y = y
        self.price = 50
        self.hp = 100
        #5 时间计数器
        self.time_count = 0

    #5 功能:生成阳光(生产钱)
    def produce_money(self):
        self.time_count += 1
        if self.time_count == 25:
            MainGame.money += 5
            self.time_count = 0
    #5 向日葵加入到窗口中
    def display_sunflower(self):
        MainGame.window.blit(self.image,self.rect)

事件处理-向日葵装填 #

本小节主要介绍向日葵在事件窗口中的装填。在主程序类class MainGame()中添加事件处理函数deal_events()。

同时,由于游戏界面需要不断更新,需在主程序类class MainGame()中的开始游戏函数def start_game()中的循环while not GAMEOVER:中添加事件处理函数deal_events()以实现反复加载。

#1 主程序
#class MainGame():
#8事件处理
    def deal_events(self):
        #8 获取所有事件
        eventList = pygame.event.get()
        #8 遍历事件列表,判断
        for e in eventList:
            if e.type == pygame.QUIT:
                self.gameOver()
            elif e.type == pygame.MOUSEBUTTONDOWN:
                # print('按下鼠标按键')
                print(e.pos)
                # print(e.button)#左键1  按下滚轮2 上转滚轮为4 下转滚轮为5  右键 3

                x = e.pos[0] // 80
                y = e.pos[1] // 80
                print(x, y)
                map = MainGame.map_list[y - 1][x]
                print(map.position)
                #8 增加创建时候的地图装填判断以及金钱判断
                if e.button == 1: #按左键,种向日葵
                    if map.can_grow and MainGame.money >= 50:
                        sunflower = Sunflower(map.position[0], map.position[1])
                        MainGame.plants_list.append(sunflower)
                        print('当前植物列表长度:{}'.format(len(MainGame.plants_list)))
                        map.can_grow = False
                        MainGame.money -= 50

    #def start_game(self):

        while not GAMEOVER:

            #8 调用事件处理的方法
            self.deal_events()




小结 #

本节主要介绍了植物大战游戏中植物类-向日葵类的设置及装填