Menu
CoddyTech

暂停

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

读取键盘有两种方式。pygame.key.get_pressed() 会在每一帧告诉你当前哪些按键正被按住:适合用于移动。KEYDOWN 事件只会在按键按下的那一帧触发一次,就像点击时触发的 MOUSEBUTTONDOWN 一样:适合用于每次按下只执行一次的操作。

暂停是每次按下只执行一次的操作。使用 get_pressed 时,按住 P 一会儿,就会在每一帧切换一次暂停状态。使用事件时,它只会切换一次:

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

not paused 会将 True 变成 False,反之亦然。把暂停状态加入运行游戏的条件中,并在暂停时显示 Paused。

challenge icon

挑战

中等

按 P 暂停游戏。

  1. 在循环之前,将 paused = False。在事件循环中,当 KEYDOWN 事件的键为 pygame.K_p 时切换它。
  2. 仅当 lives > 0 and score < 10 and not paused 时运行游戏。
  3. 当 paused 为真时,在 (240, 160) 处居中显示 Paused。

按“开始”,然后按 P:游戏会暂停并显示 Paused。然后按“检查”。

亲手试试

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

    if lives > 0 and score < 10:
        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)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

用 Pygame 制作游戏中的所有课

自己练习: Pygame 在线编辑器