12.道具系统-1

添加两种道具盾牌 shi...

添加两种道具
盾牌 shield – 恢复护盾
枪 gun – 增强火力
添加新类 道具类 Pow

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
        # 移出屏幕底部删除
        if self.rect.top > HEIGHT:
            self.kill()

加载素材部分,添加 道具图片
blank blank

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()

当子弹射中陨石,增加随机掉落道具
random.random() 生成 0~1之间的随机小数,只有数字大于0.9时10%纪录掉落道具。

 

# 检查子弹是否击中了陨石
    hits = pygame.sprite.groupcollide(mobs, bullets, True, True)
    for hit in hits:
        score += 10
        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()

检测道具与玩家碰撞

# 检测道具与玩家碰撞
    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