Menu
CoddyTech

菜单界面

本课属于 Coddy Pygame 学习旅程的“游戏规则”单元。第 2 课,共 30 课。

大多数游戏会先显示菜单:标题和一行告诉你如何开始的文字。菜单是另一种状态。先设置 state = "menu",并在该状态持续期间绘制不同的画面。

开始游戏只需按一次键,所以要从事件中读取按键。每次按键都会触发一次 KEYDOWN 事件,event.key 会指出按下的是哪个键:

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_RETURN and state == "menu":
        state = "play"

state == "menu" 这一部分很重要:只有在菜单中按 Enter 才会开始游戏。在其他画面中按 Enter 不会有任何作用。

现在,绘制内容也取决于状态:

screen.fill((30, 30, 46))
if state == "menu":
    # 标题和“按 Enter 开始游戏”提示
else:
    # 玩家、石头、分数和“游戏结束”提示

更新代码仍然放在 if state == "play": 下面,所以显示菜单时什么都不会移动。

challenge icon

挑战

简单

打开游戏后会显示一个菜单,按 Enter 键即可离开菜单。

  1. 从 state = "menu" 开始。
  2. 在事件循环中,在菜单界面按 Enter 键会将状态设为 "play"。
  3. 当状态为 "menu" 时,只在深色背景上绘制居中于 (240, 140) 的 Meteor Dodge 和居中于 (240, 200) 的 Press Enter to play;否则绘制游戏。

按“开始”:菜单会显示出来,按 Enter 键即可开始游戏。然后按“检查”。

亲手试试

import random
import pygame

pygame.init()
screen = pygame.display.set_mode((480, 360))
pygame.display.set_caption("Meteor Dodge")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 32)

player = pygame.Rect(220, 300, 40, 40)
rock = pygame.Rect(random.randint(0, 456), -24, 24, 24)
score = 0
state = "play"

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    if state == "play":
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            player.x -= 6
        if keys[pygame.K_RIGHT]:
            player.x += 6
        player.clamp_ip(screen.get_rect())

        rock.y += 4
        if rock.top > 360:
            rock.y = -24
            rock.x = random.randint(0, 456)
            score += 1
        if rock.colliderect(player):
            state = "over"

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (255, 196, 0), player)
    pygame.draw.rect(screen, (235, 80, 80), rock)
    score_text = font.render(f"Score: {score}", True, (240, 240, 240))
    screen.blit(score_text, (10, 10))
    if state == "over":
        message = font.render("Game over", True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(240, 160)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

游戏规则中的所有课

自己练习: Pygame 在线编辑器