勝ち負け
CoddyのPygameジャーニー「ゲームループ」セクションの一部。レッスン 32/35。
ゲームは終了します。ここでは、残機が0になると負け、スコアが10に達すると勝ちです。どちらも起きていない間は、ゲームは進行中です。
動くものはすべて1つの条件の中に入れ、ゲームが終了したら止まるようにします。
if lives > 0 and score < 10:
# キー、バスケット、ブロック、キャッチとミス描画はそのifの外に置きます。画面には最後のフレームが表示されたままになり、その上に結果が表示されます。
if lives == 0:
message = font.render("Game over", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(240, 160)))message.get_rect(center=(240, 160))は、中央が (240, 160) に配置されたテキスト画像の Rect です。Rect を使って blit すると左上の角が基準になるため、テキストは中央に配置されます。
チャレンジ
中級勝利または敗北でゲームを終了します。
- 動くものすべて(キー、バスケット、ブロック、キャッチとミス)を
if lives > 0 and score < 10:の下にインデントします。 - スコアと残りライフの後に、
lives == 0の場合はGame overを、score == 10の場合はYou win!を(240, 160)の位置に中央揃えで表示します。
「プレイ」を押して、ブロックを3回取り逃がします。Game overが表示され、ゲームが停止します。その後、「確認」を押します。
自分で試してみよう
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
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))
pygame.display.flip()
clock.tick(60)
pygame.quit()
ゲームループのすべてのレッスン
自分で練習してみよう: Pygameプレイグラウンド