企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
## 游戏得分 为了记录游戏得分,我们在代码主循环外面定义`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) ``` 此时游戏效果如下: ![](https://adatech-1256165843.cos.ap-chengdu.myqcloud.com/20181023075400.png) ## 飞机生命数 一般的飞机大战我方的飞机都有一个生命值,当生命值等于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 ``` 此时,游戏效果如下: ![](https://adatech-1256165843.cos.ap-chengdu.myqcloud.com/20181023075445.png) ## 敌舰生命值 敌舰的生命值要比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) ``` 此时,游戏效果如下: ![](https://adatech-1256165843.cos.ap-chengdu.myqcloud.com/20181023075456.png)