状態ごとに関数を用意
CoddyのPygameジャーニー「ゲームのルール」セクションの一部。レッスン 5/30。
ループには3つの画面が混在しており、新しい状態を追加するたびに、描画処理と更新処理の中にifがさらに重なっていきます。スターターでは、代わりに各状態に専用の関数を用意し、ループでいずれかを選びます。
if state == "menu":
draw_menu()
elif state == "play":
play_frame()
else:
draw_over()play_frame()はオブジェクトを動かし、衝突判定を行い、描画します。draw_menu()とdraw_over()は描画のみを行います。ゲームオーバー画面では、メッセージの下に停止したゲーム画面が表示されるため、どちらもプレイヤー、岩、スコアを描画する共通のdraw_game()を使います。
状態やスコアを変更する関数では、globalの後にそれらを指定する必要があります。
def play_frame():
global score, stateplayer.xを変更するのにglobalは必要ありません。新しいRectを代入するのではなく、Rectを変更するためです。
この構成なら、新しい状態の追加は関数1つとelif1つで済みます。同じ方法で一時停止画面を追加しましょう。
チャレンジ
中級ゲームに一時停止機能を追加します。
- 状態
"paused"を追加します。プレイ中に P を押すと一時停止し、もう一度 P を押すとプレイに戻ります。 draw_paused()を書きます。一時停止中のゲームを表示し、(240, 160) にPausedを中央揃えで表示します。- 状態が
"paused"のときにループから呼び出すため、elifをもう1つ追加します。
「プレイ」を押し、ゲーム中に P を押します。ゲームが停止し、Paused と表示されます。その後、「確認」を押します。
自分で試してみよう
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)
WHITE = (240, 240, 240)
def reset():
global player, rock, score
player = pygame.Rect(220, 300, 40, 40)
rock = pygame.Rect(random.randint(0, 456), -24, 24, 24)
score = 0
def draw_menu():
screen.fill((30, 30, 46))
title = font.render("Meteor Dodge", True, WHITE)
screen.blit(title, title.get_rect(center=(240, 140)))
hint = font.render("Press Enter to play", True, WHITE)
screen.blit(hint, hint.get_rect(center=(240, 200)))
def draw_game():
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, WHITE)
screen.blit(score_text, (10, 10))
def play_frame():
global score, state
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"
draw_game()
def draw_over():
draw_game()
message = font.render("Game over", True, WHITE)
screen.blit(message, message.get_rect(center=(240, 160)))
hint = font.render("Press R to play again", True, WHITE)
screen.blit(hint, hint.get_rect(center=(240, 200)))
reset()
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"
elif event.key == pygame.K_r and state == "over":
reset()
state = "play"
if state == "menu":
draw_menu()
elif state == "play":
play_frame()
else:
draw_over()
pygame.display.flip()
clock.tick(60)
pygame.quit()
ゲームのルールのすべてのレッスン
自分で練習してみよう: Pygameプレイグラウンド