## 游戲得分
為了記錄游戲得分,我們在代碼主循環外面定義`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)
```
此時游戲效果如下:

## 飛機生命數
一般的飛機大戰我方的飛機都有一個生命值,當生命值等于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
```
此時,游戲效果如下:

## 敵艦生命值
敵艦的生命值要比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)
```
此時,游戲效果如下:

- 課程介紹
- 搭建環境
- 什么是計算機
- 程序是怎么運行的
- 安裝python
- 項目實例-安裝IDE
- 變量和簡單數據類型
- 數據&變量
- 數字
- 字符串
- 布爾類型
- 項目實例
- 容器-列表
- 容器
- 列表
- 項目實例
- 容器-字典
- 定義字典
- 項目實例
- 數據類型總結
- 條件語句
- python條件語句
- 項目實例
- 循環語句
- for循環
- while循環
- 項目實例
- 函數
- 5.0函數定義
- 5.2函數實戰
- 6.文件系統
- 6.1 文件系統介紹&python查找文件
- 6.2 用python讀寫文件
- 7. python操作時間
- 8.面向對象
- 8.1 類和對象
- 8.2 繼承和重寫
- 8.3 面向對象項目實戰
- 9 GUI編程
- 9.1 GUI基礎
- 9.2 備忘清單GUI版
- 10.網絡
- 10.1 網絡的發展
- 10.2 python http
- 11.web開發
- 11.1 web基礎&HTML
- 11.2 CSS&JavaScript
- 11.3 網頁計算器
- 11.3 網站開發實戰-播客搭建
- 11.3 python-web
- 12. 項目實戰-數據處理
- 13. 項目實戰-AI入門
- 13.1 環境搭建
- 心得
- 13.2 Tensorflow的瓜怎么吃
- 14 pygame
- 14.1 pygame Helloworld
- 14.4 pygame 動畫基礎 Animation
- 從0開始學python第14.5節 pygame 加載圖片和聲音
- 從0開始學python第14.6節 pygame.sprite(上)
- 14.7 pygame.sprite模塊(下)
- 14.8 pygame射擊游戲(一)
- pygame射擊游戲(二)
- 14.8 pygame射擊游戲(三)
- 14.8 pygame射擊游戲(四)
- 14.8 pygame射擊游戲(五)