按 R 再玩一次
本课属于 Coddy Pygame 学习旅程的“游戏规则”单元。第 3 课,共 30 课。
游戏结束后,玩家希望不用重新启动程序就能再玩一次。在游戏结束画面中添加一行提示,并设置一个可以开始新游戏的按键:
if event.key == pygame.K_r and state == "over":
player.x = 220
rock.y = -24
rock.x = random.randint(0, 456)
state = "play"仅仅把状态设回 "play" 还不够。岩石仍然碰着玩家,所以游戏会在下一帧再次结束。把移动过的物体放回新游戏开始时的位置。
这和菜单使用的是同一种模式:一个按键、一次对当前状态的检查,以及一个新状态。
挑战
简单让玩家在游戏结束后重新开始。
- 在
Game over下方,将Press R to play again居中显示在 (240, 200)。 - 按下 R 且状态为
"over"时:将玩家移回 x 220 处,将岩石移回 y -24 处,并将 x 设为 0 到 456 之间的随机值,然后将状态设为"play"。
按“开始”,输掉游戏,然后按 R:新游戏就会开始。接着按“检查”。
亲手试试
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 = "menu"
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RETURN and state == "menu":
state = "play"
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))
if state == "menu":
title = font.render("Meteor Dodge", True, (240, 240, 240))
screen.blit(title, title.get_rect(center=(240, 140)))
hint = font.render("Press Enter to play", True, (240, 240, 240))
screen.blit(hint, hint.get_rect(center=(240, 200)))
else:
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 在线编辑器