最新消息:380元/半年,推荐全网最具性价比的一站式编程学习平台码丁实验室

14.8 pygame射击游戏(四)

Python 少儿编程 1593浏览 0评论

友情提示:380元/半年,儿童学编程,就上码丁实验室

14.8 pygame射击游戏(四)

游戏得分

为了记录游戏得分,我们在代码主循环外面定义score = 0变量,当子弹击中敌舰后,我们将得分加一。

bullet_collide_dic = pygame.sprite.groupcollide(bullet_sprites, enemy_sprites, True, True)
for bullet in bullet_collide_dic:
    score += 1
    print(bullet, bullet_collide_dic[bullet], score)

为了将得分显示在屏幕上,我们新增了一个渲染文字的方法:

pygame.font.init()


def show_text(word, color, position, font_size):
    sys_font = pygame.font.SysFont('Comic Sans MS', font_size)
    score_surface = sys_font.render(word, False, color)
    screen.blit(score_surface, position)

在游戏窗口渲染完成后,我们将得分渲染到屏幕的右上角:

# 7. 渲染游戏背景
screen.fill(BLACK)
show_text('score:' + str(score), WHITE, (WIDTH - 100, 0), 30)

此时游戏效果如下:
14.8 pygame射击游戏(四)

飞机生命数

一般的飞机大战我方的飞机都有一个生命值,当生命值等于0时才结束游戏。我们来完成这个效果。
首先,我们在plane里定义个life变量self.life = 3
我们把敌舰撞击飞机的方法移动到plane中:

# 撞击
def strike(self, enemy_group):
    collide_planes = pygame.sprite.spritecollide(self, enemy_group, True)
    if len(collide_planes) > 0:
        self.life -= 1
        print('life', self.life)

# 是否存活
def is_survive(self):
    return self.life > 0

在main.py中修改撞击方法

# 敌舰撞击飞机
plane.strike(enemy_sprites)
if not plane.is_survive():
    running = False

此时,游戏效果如下:
14.8 pygame射击游戏(四)

敌舰生命值

敌舰的生命值要比plane的麻烦一些,因为敌舰的生命值要画的敌舰的身上。首先,我们在init方法中增加font属性:self.sys_font = pygame.font.SysFont(‘Comic Sans MS’, 20)。 此外,我们需要改动敌舰的init 和update方法。看代码:

def update(self):
    self.rect.y += self.speed
    score_surface = self.sys_font.render('life:' + str(self.life), False, RED)
    self.image.blit(score_surface, (10, 0))

同理,我们修改Main.py的增加得分逻辑:

# 子弹击毁敌舰
for enemy in enemy_sprites:
    enemy.strike(bullet_sprites)
    if not enemy.is_survive():
        score += 1
        print(enemy, score)

此时,游戏效果如下:
14.8 pygame射击游戏(四)

始发于简书:阿达老师

您必须 登录 才能发表评论!