前言
一段時間沒有敲代碼,感覺忘得好快!!今天我們繼續完成前面的任務,不知道大家有木有發現之前的飛機撞到敵人是不會爆炸的,這很不符合規律,今天我們加入這個小功能,玩家飛機墜毀並產生動畫。(°∀°)ノ
正片開始~
1. 判斷飛機是否墜毀
關於碰撞檢測,我們在上一節的內容中就作了簡單介紹了,這一節中我們使用一個新函數,用於判斷玩家是否被敵機擊中:
pygame.sprite.spritecollide()——檢測sprite與group之間的碰撞
spritecollide(sprite, group, dokill, collided = None) -> Sprite_list
參數跟上一節中參數說明相同,函數返回group中與sprite發生碰撞的所有精靈,以列表(list)形式
我們現在加入幾代碼
1 enemy1_down_list = pygame.sprite.spritecollide(hero, enemy1_group, True) 2 if len(enemy1_down_list) > 0: # 不空 3 enemy1_down_group.add(enemy1_down_list) 4 hero.is_hit = True
如果玩家被擊中(即enemy1_down_list不空),就將擊中玩家的敵機加入到enemy1_down_group中,將渲染enemy1墜毀動畫的過程交給該group;最后將hero的is_hit屬性更改為True(Hero類新加入的屬性,便於進行后續的邏輯判斷)。
2. 制造玩家飛機墜毀動畫
當然玩家被擊中了也是不可能憑空消失的,我們將以前在主循環中制造玩家飛機動畫的代碼更新一下,即將:
1 hero.image = hero_surface[ticks//(ANIMATE_CYCLE//2)]
改為:
1 if hero.is_hit: 2 if ticks%(ANIMATE_CYCLE//2) == 0: 3 hero_down_index += 1 4 hero.image = hero_surface[hero_down_index] 5 if hero_down_index == 5: 6 break 7 else: 8 hero.image = hero_surface[ticks//(ANIMATE_CYCLE//2)]
如果玩家沒有被擊中,則按以前普通的玩家圖片制造動畫;若玩家被擊中,則按每15tick換一次圖片的頻率制造爆炸動畫,當圖片索引增加至上限時(爆炸動畫顯示完成),跳出主循環,即結束游戲。
3. 完整的結束游戲
如果你只完成了上面的代碼,你會發現,玩家被擊中了之后,飛機爆炸,之后畫面靜止,然后所有動作都進行不了,包括右上角紅叉。這是怎么回事?(╯°口°)╯(┴—┴ 認真思考過后你會發現,你此時已經跳出了主循環,而捕捉擊鍵事件和點擊事件的功能卻寫在主循環中~就是這樣啦~
無奈之下只能再寫一段捕捉事件的代碼(#-_-)┯━┯
1 # 跳出主循環 2 screen.blit(gameover, (0, 0)) 3 # 玩家墜毀后退出游戲 4 while True: 5 pygame.display.update() 6 for event in pygame.event.get(): 7 if event.type == pygame.QUIT: 8 pygame.quit() 9 exit()
跳出主循環后,我們重寫繪制一個“gameover”的背景,用戶通過右上角紅叉結束游戲~
這樣就算是一個完整的游戲了吧(°∀°)ノ
附上此節的完整代碼:

1 # -*- coding = utf-8 -*- 2 """ 3 @author: Will Wu 4 5 增加功能: 6 1. 玩家碰到敵人會墜毀 7 2. 游戲結束 8 """ 9 10 import pygame # 導入pygame庫 11 from pygame.locals import * # 導入pygame庫中的一些常量 12 from sys import exit # 導入sys庫中的exit函數 13 from random import randint 14 15 # 定義窗口的分辨率 16 SCREEN_WIDTH = 480 17 SCREEN_HEIGHT = 640 18 19 # 子彈類 20 class Bullet(pygame.sprite.Sprite): 21 22 def __init__(self, bullet_surface, bullet_init_pos): 23 pygame.sprite.Sprite.__init__(self) 24 self.image = bullet_surface 25 self.rect = self.image.get_rect() 26 self.rect.topleft = bullet_init_pos 27 self.speed = 8 28 29 # 控制子彈移動 30 def update(self): 31 self.rect.top -= self.speed 32 if self.rect.bottom < 0: 33 self.kill() 34 35 36 # 玩家類 37 class Hero(pygame.sprite.Sprite): 38 39 def __init__(self, hero_surface, hero_init_pos): 40 pygame.sprite.Sprite.__init__(self) 41 self.image = hero_surface 42 self.rect = self.image.get_rect() 43 self.rect.topleft = hero_init_pos 44 self.speed = 6 45 self.is_hit = False # new 46 47 # 子彈1的Group 48 self.bullets1 = pygame.sprite.Group() 49 50 # 控制射擊行為 51 def single_shoot(self, bullet1_surface): 52 bullet1 = Bullet(bullet1_surface, self.rect.midtop) 53 self.bullets1.add(bullet1) 54 55 # 控制飛機移動 56 def move(self, offset): 57 x = self.rect.left + offset[pygame.K_RIGHT] - offset[pygame.K_LEFT] 58 y = self.rect.top + offset[pygame.K_DOWN] - offset[pygame.K_UP] 59 if x < 0: 60 self.rect.left = 0 61 elif x > SCREEN_WIDTH - self.rect.width: 62 self.rect.left = SCREEN_WIDTH - self.rect.width 63 else: 64 self.rect.left = x 65 66 if y < 0: 67 self.rect.top = 0 68 elif y > SCREEN_HEIGHT - self.rect.height: 69 self.rect.top = SCREEN_HEIGHT - self.rect.height 70 else: 71 self.rect.top = y 72 73 # 敵人類 74 class Enemy(pygame.sprite.Sprite): 75 def __init__(self, enemy_surface, enemy_init_pos): 76 pygame.sprite.Sprite.__init__(self) 77 self.image = enemy_surface 78 self.rect = self.image.get_rect() 79 self.rect.topleft = enemy_init_pos 80 self.speed = 2 81 82 # 爆炸動畫畫面索引 83 self.down_index = 0 84 85 def update(self): 86 self.rect.top += self.speed 87 if self.rect.top > SCREEN_HEIGHT: 88 self.kill() 89 90 ########################################################################### 91 92 # 定義畫面幀率 93 FRAME_RATE = 60 94 95 # 定義動畫周期(幀數) 96 ANIMATE_CYCLE = 30 97 98 ticks = 0 99 clock = pygame.time.Clock() 100 offset = {pygame.K_LEFT:0, pygame.K_RIGHT:0, pygame.K_UP:0, pygame.K_DOWN:0} 101 102 # 玩家墜毀圖片索引 103 hero_down_index = 1 # new 104 105 # 初始化游戲 106 pygame.init() # 初始化pygame 107 screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) # 初始化窗口 108 pygame.display.set_caption('This is my first pygame-program') # 設置窗口標題 109 110 # 載入背景圖 111 background = pygame.image.load('resources/image/background.png') 112 # 游戲結束圖 113 gameover = pygame.image.load('resources/image/gameover.png') # new 114 115 # 載入資源圖片 116 shoot_img = pygame.image.load('resources/image/shoot.png') 117 118 # 用subsurface剪切讀入的圖片 119 # Hero圖片 120 hero_surface = [] 121 hero_surface.append(shoot_img.subsurface(pygame.Rect(0, 99, 102, 126))) 122 hero_surface.append(shoot_img.subsurface(pygame.Rect(165, 360, 102, 126))) 123 hero_surface.append(shoot_img.subsurface(pygame.Rect(165, 234, 102, 126))) 124 hero_surface.append(shoot_img.subsurface(pygame.Rect(330, 624, 102, 126))) 125 hero_surface.append(shoot_img.subsurface(pygame.Rect(330, 498, 102, 126))) 126 hero_surface.append(shoot_img.subsurface(pygame.Rect(432, 624, 102, 126))) 127 hero_pos = [200, 500] 128 129 # bullet1圖片 130 bullet1_surface = shoot_img.subsurface(pygame.Rect(1004, 987, 9, 21)) 131 132 # enemy1圖片 133 enemy1_surface = shoot_img.subsurface(pygame.Rect(534, 612, 57, 43)) 134 enemy1_down_surface = [] 135 enemy1_down_surface.append(shoot_img.subsurface(pygame.Rect(267, 347, 57, 43))) 136 enemy1_down_surface.append(shoot_img.subsurface(pygame.Rect(873, 697, 57, 43))) 137 enemy1_down_surface.append(shoot_img.subsurface(pygame.Rect(267, 296, 57, 43))) 138 enemy1_down_surface.append(shoot_img.subsurface(pygame.Rect(930, 697, 57, 43))) 139 140 # 創建玩家 141 hero = Hero(hero_surface[0], hero_pos) 142 143 # 創建敵人組 144 enemy1_group = pygame.sprite.Group() 145 146 # 創建擊毀敵人組 147 enemy1_down_group = pygame.sprite.Group() 148 149 # 事件循環(main loop) 150 while True: 151 152 # 控制游戲最大幀率 153 clock.tick(FRAME_RATE) 154 155 # 繪制背景 156 screen.blit(background, (0, 0)) 157 158 # 改變飛機圖片制造動畫 159 if ticks >= ANIMATE_CYCLE: 160 ticks = 0 161 162 # 制造飛機動畫 ###################################### 163 # 更新的代碼段 164 if hero.is_hit: 165 if ticks%(ANIMATE_CYCLE//2) == 0: 166 hero_down_index += 1 167 hero.image = hero_surface[hero_down_index] 168 if hero_down_index == 5: 169 break 170 else: 171 hero.image = hero_surface[ticks//(ANIMATE_CYCLE//2)] 172 # ################################################# 173 174 # 射擊 175 if ticks % 10 == 0: 176 hero.single_shoot(bullet1_surface) 177 # 控制子彈 178 hero.bullets1.update() 179 # 繪制子彈 180 hero.bullets1.draw(screen) 181 182 # 產生敵機 183 if ticks % 30 == 0: 184 enemy = Enemy(enemy1_surface, [randint(0, SCREEN_WIDTH - enemy1_surface.get_width()), -enemy1_surface.get_height()]) 185 enemy1_group.add(enemy) 186 # 控制敵機 187 enemy1_group.update() 188 # 繪制敵機 189 enemy1_group.draw(screen) 190 191 # 檢測敵機與子彈的碰撞 192 enemy1_down_group.add(pygame.sprite.groupcollide(enemy1_group, hero.bullets1, True, True)) 193 194 for enemy1_down in enemy1_down_group: 195 screen.blit(enemy1_down_surface[enemy1_down.down_index], enemy1_down.rect) 196 if ticks % (ANIMATE_CYCLE//2) == 0: 197 if enemy1_down.down_index < 3: 198 enemy1_down.down_index += 1 199 else: 200 enemy1_down_group.remove(enemy1_down) 201 202 # 檢測敵機與玩家的碰撞 ################################# 203 # 更新的代碼段 204 enemy1_down_list = pygame.sprite.spritecollide(hero, enemy1_group, True) 205 if len(enemy1_down_list) > 0: # 不空 206 enemy1_down_group.add(enemy1_down_list) 207 hero.is_hit = True 208 # ################################################### 209 210 # 繪制飛機 211 screen.blit(hero.image, hero.rect) 212 ticks += 1 # python已略去自增運算符 213 214 # 更新屏幕 215 pygame.display.update() 216 217 # 處理游戲退出 218 # 從消息隊列中循環取 219 for event in pygame.event.get(): 220 if event.type == pygame.QUIT: 221 pygame.quit() 222 exit() 223 224 # ※ Python中沒有switch-case 多用字典類型替代 225 # 控制方向 226 if event.type == pygame.KEYDOWN: 227 if event.key in offset: 228 offset[event.key] = hero.speed 229 elif event.type == pygame.KEYUP: 230 if event.key in offset: 231 offset[event.key] = 0 232 233 # 移動飛機 234 hero.move(offset) 235 236 # 更新的代碼段 ############################### 237 # 跳出主循環 238 screen.blit(gameover, (0, 0)) 239 # 玩家墜毀后退出游戲 240 while True: 241 pygame.display.update() 242 for event in pygame.event.get(): 243 if event.type == pygame.QUIT: 244 pygame.quit() 245 exit() 246 ############################################