Menu
CoddyTech

输赢

Coddy 用 Pygame 制作游戏 课程的第 15 课,共 41 课。

游戏会结束。当生命值降到 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 进行绘制时,会以其左上角为基准,因此文本会居中。

challenge icon

挑战

中等

以胜利或失败结束游戏。

  1. 将所有会移动的内容(按键、篮子、方块、接住和漏掉方块的操作)缩进到 if lives > 0 and score < 10: 下方。
  2. 显示分数和生命值后,如果 lives == 0,就显示 Game over;如果 score == 10,就显示 You win!,并将它们放在 (240, 160) 位置居中显示。

按“运行”,连续漏掉三个方块:屏幕会显示 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 制作游戏中的所有课

自己练习: Pygame 在线编辑器