添加护盾
Player类,添加护盾属性shield =100,
class Player(pygame.sprite.Sprite):
def __init__(self):
self.speedx = 0
self.shield = 100
对玩家造成伤害
修改碰撞检测代码,每次被陨石击中shield -1
# 检查是否有敌人击中了玩家
hits = pygame.sprite.spritecollide(player, mobs, True, pygame.sprite.collide_circle)
for hit in hits:
player.shield -= 10
if player.shield <= 0:
running = False
陨石碰到子弹,陨石碰到玩家 都会消失,为了保证陨石总数不变,陨石消失时都需要生成新的陨石,新建一个陨石生成函数 newmob()
def newmob():
m = Mob()
all_sprites.add(m)
mobs.add(m)
陨石碰到子弹,陨石碰到玩家消失后,调用 newmob()生成新陨石
# 检查是否有敌人击中了玩家
hits = pygame.sprite.spritecollide(player, mobs, False, pygame.sprite.collide_circle)
for hit in hits:
player.shield -= 10
newmob()
if player.shield <= 0:
running = False
# 检查子弹是否击中了敌人
hits = pygame.sprite.groupcollide(mobs, bullets, True, True)
for hit in hits:
score += 10
random.choice(expl_sounds).play()
newmob()
护盾进度条
生成 护盾进度条 函数 draw_shield_bar()
def draw_shield_bar(surf, x, y, pct):
if pct < 0:
pct = 0
BAR_LENGTH = 100
BAR_HEIGHT = 10
fill = (pct / 100) * BAR_LENGTH
outline_rect = pygame.Rect(x, y, BAR_LENGTH, BAR_HEIGHT)
fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)
pygame.draw.rect(surf, GREEN, fill_rect)
pygame.draw.rect(surf, WHITE, outline_rect, 2)
添加护盾进度条
draw_text(screen, str(score), 18, WIDTH / 2, 10)
draw_shield_bar(screen, 5, 5, player.shield)