增加能量

截至目前,我们为编写这个游戏已经走了很长一段路,但我们仍然缺少一件事,那就是让玩家的飞船变得更强大。 我们可以考虑添加多种强化道具,但现在我们将重点关注两种:

  • 盾牌 - 一个可以恢复生命值的物体
  • 枪 - 一种可以增强火力的物体

能量精灵

首先,我们需要定义另一个 Sprite,这一次代表我们的 powerup(能量) 对象。 为简单起见,我们可以复制我们已经创建的 Bullet 类并进行一些更改,因为它们的行为很相似:从一个位置(刚刚被摧毁的Mob的位置)开始并向下移动, 如果精灵离开屏幕底部,则将其销毁。 对于它所显示的图片,我们将在“枪”和“盾”之间随机选择,这将是我们两种增加能量的方式。

class Pow(pygame.sprite.Sprite):
    def __init__(self, center):
        pygame.sprite.Sprite.__init__(self)
        self.type = random.choice(['shield', 'gun'])
        self.image = powerup_images[self.type]
        self.image.set_colorkey(BLACK)
        self.rect = self.image.get_rect()
        self.rect.center = center
        self.speedy = 2

    def update(self):
        self.rect.y += self.speedy
        # kill if it moves off the bottom of the screen
        if self.rect.top > HEIGHT:
            self.kill()

我们需要在资源加载部分加载图像,使用字典来保存以 powerup 类型为键的图像:

powerup_images = {}
powerup_images['shield'] = pygame.image.load(path.join(img_dir, 'shield_gold.png')).convert()
powerup_images['gun'] = pygame.image.load(path.join(img_dir, 'bolt_gold.png')).convert()

以下是我们使用的图片:

生成精灵对象

为了生成它们,我们需要一个组来保存它们(用于碰撞):

powerups = pygame.sprite.Group()

然后,当一颗子弹摧毁一个Mob时,我们希望有一个(小)随机的机会使能量道具掉落:

# check to see if a bullet hit a mob
hits = pygame.sprite.groupcollide(mobs, bullets, True, True)
for hit in hits:
    score += 50 - hit.radius
    random.choice(expl_sounds).play()
    expl = Explosion(hit.rect.center, 'lg')
    all_sprites.add(expl)
    if random.random() > 0.9:
        pow = Pow(hit.rect.center)
        all_sprites.add(pow)
        powerups.add(pow)
    newmob()

在这里,random.random() 选择一个介于 0 和 1 之间的随机十进制数,因此只有在该数字大于 0.9 时才生成精灵,这意味着我们有 10% 的机会从被摧毁的Mob中掉落能量道具。

与玩家碰撞

现在,我们需要再次进行碰撞检查,这次是在玩家和 powerups 组之间。 在其他精灵之后添加它:

# check to see if player hit a powerup
hits = pygame.sprite.spritecollide(player, powerups, True)
for hit in hits:
    if hit.type == 'shield':
        player.shield += random.randrange(10, 30)
        if player.shield >= 100:
            player.shield = 100
    if hit.type == 'gun':
        pass

首先,我们处理生命值能量道具,这将为玩家提供随机数量的生命值回血。 “枪”能量道具的处理有点复杂,所以我们将在下一部分中处理它。 完整代码请参考这里

文章分享二维码

微信扫码分享这篇文章

扫描二维码即可在手机中继续阅读,也方便转发给老师、家长或同学。

上一篇 少儿编程之使用PyGame编写游戏(15):太空大撞击 增加能量道具 (续) 下一篇 少儿编程之使用PyGame编写游戏(13):太空大撞击 添加几条命