10.爆炸效果

当按下空格,自动发射子弹...

当按下空格,自动发射子弹
player 添加两个新属性 shoot_delay 发射间隔和 last_shot 上次发射时间

self.shoot_delay = 250
self.last_shot = pygame.time.get_ticks()

将侦测空格发射,添加到 Player类的 update 方法中:

def update(self):
    self.speedx = 0
    keystate = pygame.key.get_pressed()
    if keystate[pygame.K_LEFT]:
        self.speedx = -8
    if keystate[pygame.K_RIGHT]:
        self.speedx = 8
    if keystate[pygame.K_SPACE]:
        self.shoot()

修改 Player类的 shoot 方法:

def shoot(self):
        now = pygame.time.get_ticks()
        if now - self.last_shot > self.shoot_delay:
            self.last_shot = now
            bullet = Bullet(self.rect.centerx, self.rect.top)
            all_sprites.add(bullet)
            bullets.add(bullet)
            shoot_sound.play()

删除主循环中的 空格键侦测哪个好dongh:

elif event.type == pygame.KEYDOWN:
    if event.key == pygame.K_SPACE:
        player.shoot()

爆炸动画
陨石摧毁时的爆炸效果,
单击此处下载素材。

blank
pygame.transform.scale() 调整图片大小,
创建两个不同大小的爆炸动画列表,图片从00-08为一个循环。
加载图片处,添加代码:

explosion_anim = {}
explosion_anim['lg'] = []
explosion_anim['sm'] = []
for i in range(9):
    filename = 'regularExplosion0{}.png'.format(i)
    img = pygame.image.load(path.join(img_dir, filename)).convert()
    img.set_colorkey(BLACK)
    img_lg = pygame.transform.scale(img, (75, 75))
    explosion_anim['lg'].append(img_lg)
    img_sm = pygame.transform.scale(img, (32, 32))
    explosion_anim['sm'].append(img_sm)

定义一个新类:爆炸类 Explosion,展示爆炸效果:

class Explosion(pygame.sprite.Sprite):
    def __init__(self, center, size):
        pygame.sprite.Sprite.__init__(self)
        self.size = size
        self.image = explosion_anim[self.size][0]
        self.rect = self.image.get_rect()
        self.rect.center = center
        self.frame = 0
        self.last_update = pygame.time.get_ticks()
        self.frame_rate = 50

    def update(self):
        now = pygame.time.get_ticks()
        if now - self.last_update > self.frame_rate:
            self.last_update = now
            self.frame += 1
            if self.frame == len(explosion_anim[self.size]):
                self.kill()
            else:
                center = self.rect.center
                self.image = explosion_anim[self.size][self.frame]
                self.rect = self.image.get_rect()
                self.rect.center = center

子弹击中陨石 或 陨石撞击玩家,播放爆炸效果

    # 检查是否有陨石击中了玩家
    hits = pygame.sprite.spritecollide(player, mobs, True, pygame.sprite.collide_circle)
    for hit in hits:
        player.shield -= 10
        expl = Explosion(hit.rect.center, 'lg')
        all_sprites.add(expl)
        newmob()
        if player.shield <= 0:
            running = False

    # 检查子弹是否击中了陨石
    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)
        newmob()

blank