植物大战僵尸5 #
- 豌豆射手类的创建及功能
- 豌豆射手类的窗口添加及发射处理
- 事件处理-向日葵装填
豌豆射手类的创建及功能 #
本小节主要介绍创建豌豆射手类class PeaShooter()的方法,包括射击方法的定义
#6 豌豆射手类
class PeaShooter(Plant):
def __init__(self,x,y):
super(PeaShooter, self).__init__()
# self.image 为一个 surface
self.image = pygame.image.load('imgs/peashooter.png')
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
self.price = 50
self.hp = 200
#6 发射计数器
self.shot_count = 0
#6 增加射击方法
def shot(self):
#6 记录是否应该射击
should_fire = False
for zombie in MainGame.zombie_list:
if zombie.rect.y == self.rect.y and zombie.rect.x < 800 and zombie.rect.x > self.rect.x:
should_fire = True
#6 如果活着
if self.live and should_fire:
self.shot_count += 1
# 计数器到25发射一次
if self.shot_count == 25:
#6 基于当前豌豆射手的位置,创建子弹
peabullet = PeaBullet(self)
#6 将子弹存储到子弹列表中
MainGame.peabullet_list.append(peabullet)
self.shot_count = 0
豌豆射手类的窗口添加及发射处理 #
本小节主要介绍将豌豆射手加入到窗口中的方法,在豌豆射手类class PeaShooter()中增加函数display_peashooter()。同时在主程序类class MainGame()中增加豌豆射手发射处理函数load_plants()
#class PeaShooter(Plant):
#6 将豌豆射手加入到窗口中的方法
def display_peashooter(self):
MainGame.window.blit(self.image,self.rect)
#class MainGame():
#6 增加豌豆射手发射处理
def load_plants(self):
for plant in MainGame.plants_list:
#6 优化加载植物的处理逻辑
if plant.live:
if isinstance(plant, Sunflower):
plant.display_sunflower()
plant.produce_money()
elif isinstance(plant, PeaShooter):
plant.display_peashooter()
plant.shot()
else:
MainGame.plants_list.remove(plant)
事件处理-豌豆射手装填 #
本小节主要介绍豌豆射手在事件窗口中的装填。在主程序类class MainGame()的事件处理函数deal_events()中,
if e.button == 1: 模块后添加豌豆射手的功能。
同时,由于游戏界面需要不断更新,需在主程序类class MainGame()中的开始游戏函数def start_game()中的循环while not GAMEOVER:中添加植物加载函数self.load_plants()。
#1 主程序
#class MainGame():
#8事件处理
#def deal_events(self):
elif e.button == 3: #按右键,种豌豆射手
if map.can_grow and MainGame.money >= 50:
peashooter = PeaShooter(map.position[0], map.position[1])
MainGame.plants_list.append(peashooter)
print('当前植物列表长度:{}'.format(len(MainGame.plants_list)))
map.can_grow = False
MainGame.money -= 50
#def start_game(self):
while not GAMEOVER:
#6 调用加载植物的方法
self.load_plants()
小结 #
本节主要介绍了植物大战游戏中植物类-豌豆射手类的射击设置及装填