Menu
CoddyTech

再玩一次

本课属于 Coddy Pygame 学习旅程的“游戏循环”单元。第 34 课,共 35 课。

游戏结束后,玩家不应该需要重新启动程序。让 R 开始新游戏:把所有发生变化的值都恢复到初始状态。

elif event.key == pygame.K_r and (lives == 0 or score == 10):
    score = 0
    lives = 3
    basket.x = 200
    block.y = -20
    block.x = random.randint(0, 460)

这个条件很重要。如果没有 (lives == 0 or score == 10),R 就会在游戏进行到一半时清零分数。括号把两种结束情况组合在一起,所以 and 会同时作用于两者。

告诉玩家要按哪个键:在结果下方显示 Press R to play again。

challenge icon

挑战

中等

按 R 开始新游戏。

  1. 在 KEYDOWN 分支中,当按下的键是 pygame.K_r 且游戏已结束时,将分数设为 0,生命数设为 3,将 basket.x 设为 200,并从随机的 x 位置让一个新方块从 y = -20 处落下。
  2. 游戏结束时,在 (240, 200) 处居中显示 Press R to play again。

按“开始”,输掉游戏,然后按 R:新游戏就会开始。然后按“检查”。

亲手试试

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
paused = False

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN:
            if event.key == pygame.K_p:
                paused = not paused

    if lives > 0 and score < 10 and not paused:
        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))
    if lives == 0:
        message = font.render("Game over", True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(240, 160)))
    elif score == 10:
        message = font.render("You win!", True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(240, 160)))
    if paused:
        message = font.render("Paused", True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(240, 160)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

游戏循环中的所有课

自己练习: Pygame 在线编辑器