生命值
本课属于 Coddy Pygame 学习旅程的“游戏循环”单元。第 31 课,共 35 课。
漏接一次就要付出代价。给玩家 3 条命,每当方块掉到底部以下时,就扣掉 1 条命。代码中已经有处理这种情况的位置:block.top > 360分支。
if block.top > 360:
block.y = -20
block.x = random.randint(0, 460)
lives -= 1像显示分数一样显示剩余生命:每一帧都渲染 f"Lives: {lives}",并将它绘制在右上角的 (370, 10) 处。
挑战
简单给玩家 3 条生命。
- 在循环之前,设置
lives = 3。 - 方块掉到屏幕底部以下时,减少 1 条生命。
- 用
(240, 240, 240)渲染f"Lives: {lives}",并将它 blit 到(370, 10)。
按“开始”,让一个方块掉下去:会显示 Lives: 2。然后点击“检查”。
亲手试试
import random
import pygame
pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Catch the Blocks")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)
basket = pygame.Rect(200, 330, 80, 16)
block = pygame.Rect(220, 0, 20, 20)
score = 0
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
basket.x -= 8
if keys[pygame.K_RIGHT]:
basket.x += 8
basket.clamp_ip(screen.get_rect())
block.y += 3
if block.top > 360:
block.y = -20
block.x = random.randint(0, 460)
if block.colliderect(basket):
block.y = -20
block.x = random.randint(0, 460)
score += 1
screen.fill((30, 30, 46))
pygame.draw.rect(screen, (80, 160, 255), basket)
pygame.draw.rect(screen, (235, 80, 80), block)
score_text = font.render(f"Score: {score}", True, (240, 240, 240))
screen.blit(score_text, (10, 10))
pygame.display.flip()
clock.tick(60)
pygame.quit()
游戏循环中的所有课
自己练习: Pygame 在线编辑器