玩家爆炸
单击此处下载这些图像的 zip。
explosion_anim 字典,添加 ‘player’ 键 ,加载sonicExplosion 00-08图片
explosion_anim = {}
explosion_anim['lg'] = []
explosion_anim['sm'] = []
explosion_anim['player'] = []
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)
filename = 'sonicExplosion0{}.png'.format(i)
img = pygame.image.load(path.join(img_dir, filename)).convert()
img.set_colorkey(BLACK)
explosion_anim['player'].append(img)
玩家碰到陨石处,玩家护盾 shield<=0 时,显示玩家爆炸动画
# 检查是否有陨石击中了玩家
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:
death_explosion = Explosion(player.rect.center, 'player')
all_sprites.add(death_explosion)
running = False
玩家爆炸动画没显示玩,游戏就退出了
设置代码:
if player.shield <= 0:
death_explosion = Explosion(player.rect.center, 'player')
all_sprites.add(death_explosion)
player.kill()
# 如果玩家死亡 并且 爆炸动画 播放完毕。
if not player.alive() and not death_explosion.alive():
running = False
添加玩家生命:
玩家多条名,剩余几条命显示几个小飞机
加载小飞机图像
player_img = pygame.image.load(path.join(img_dir, "playerShip1_orange.png")).convert()
player_mini_img = pygame.transform.scale(player_img, (25, 19))
player_mini_img.set_colorkey(BLACK)
Player 类,添加几个属性:
lives 生命数
hidden 隐藏/显示玩家的标志
hide_timer 隐藏时间戳
self.lives = 3
self.hidden = False
self.hide_timer = pygame.time.get_ticks()
玩家碰撞代码,当玩家死亡时,减少生命 live -1 ,替换原来的 player.kill()
shield 护盾重置为100
if player.shield <= 0:
death_explosion = Explosion(player.rect.center, 'player')
all_sprites.add(death_explosion)
player.hide()
player.lives -= 1
player.shield = 100
# 如果玩家死亡 并且 爆炸动画播放完毕。
if player.lives==0 and not death_explosion.alive():
running = False
Player 类添加 hide() 方法处理 玩家隐藏
def hide(self):
# 临时隐藏
self.hidden = True
self.hide_timer = pygame.time.get_ticks()
self.rect.center = (WIDTH / 2, HEIGHT + 200)
Player 类, update() 方法,添加代码 一定时间后再次显示
def update(self):
# 再次显示
if self.hidden and pygame.time.get_ticks() - self.hide_timer > 1000:
self.hidden = False
self.rect.centerx = WIDTH / 2
self.rect.bottom = HEIGHT - 10
显示生命数据
添加函数 draw_lives() 处理生命图像显示数据
def draw_lives(surf, x, y, lives, img):
for i in range(lives):
img_rect = img.get_rect()
img_rect.x = x + 30 * i
img_rect.y = y
surf.blit(img, img_rect)
主循环绘制生命数据
draw_lives(screen, WIDTH - 100, 5, player.lives, player_mini_img)