メニュー画面
CoddyのPygameジャーニー「ゲームのルール」セクションの一部。レッスン 2/30。
多くのゲームはメニューから始まります。タイトルと、開始方法を伝える一文が表示されます。メニューももう1つの状態です。state = "menu"から始め、メニューが表示されている間は別の画面を描画します。
ゲームの開始はキーを1回押すだけなので、イベントから読み取ります。KEYDOWNイベントはキーを押すたびに1回発生し、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":
# タイトルと「Press Enter to play」
else:
# プレイヤー、岩、スコア、「Game over」更新処理は引き続きif state == "play":の中にあるので、メニューが表示されている間は何も動きません。
チャレンジ
簡単Enterキーで抜けるメニュー画面からゲームを開始します。
state = "menu"から始めます。- イベントループで、メニュー画面でEnterキーを押すと、状態が
"play"になります。 - 状態が
"menu"の間は、暗い背景にMeteor Dodgeを(240, 140)の位置に、Press Enter to playを(240, 200)の位置に中央揃えで描画します。それ以外の場合はゲームを描画します。
「プレイ」を押します。メニューが表示され、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プレイグラウンド