输赢
本课属于 Coddy Pygame 学习旅程的“游戏循环”单元。第 32 课,共 35 课。
游戏会结束。当生命值降到 0 时,你会输;当分数达到 10 时,你会赢。在这两种情况都没有发生时,游戏仍在进行。
把所有会移动的内容都放在同一个条件下,这样游戏结束时它们就会停止:
if lives > 0 and score < 10:
# 按键、篮子、方块、接住和没接住绘制内容要放在 if 外面:屏幕仍会显示最后一帧,并在其上方显示结果。
if lives == 0:
message = font.render("Game over", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(240, 160)))message.get_rect(center=(240, 160)) 是文本图像对应的 Rect,它的中心位于 (240, 160)。在 Rect 上绘制时会使用它的左上角,因此文本会居中。
挑战
中等让游戏以胜利或失败结束。
- 将所有会移动的内容(按键、篮子、方块、接住和漏接)缩进到
if lives > 0 and score < 10:下。 - 显示分数和生命值后,当
lives == 0时显示Game over,或者当score == 10时在(240, 160)处居中显示You win!。
按“开始”,让三个方块都掉落:屏幕会显示 Game over,游戏也会停止。然后按“检查”。
亲手试试
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
lives = 3
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)
lives -= 1
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))
lives_text = font.render(f"Lives: {lives}", True, (240, 240, 240))
screen.blit(lives_text, (370, 10))
pygame.display.flip()
clock.tick(60)
pygame.quit()
游戏循环中的所有课
自己练习: Pygame 在线编辑器