Menu
CoddyTech

先に5点取る

Coddyの「Pygameでゲームを作ろう」コースのレッスン 37/40。

先に5点を取ったプレイヤーが勝ちです。勝者の名前を、最初は None、つまりPythonで「まだ何もない」を表す値が設定されている変数に保持します。

winner = None

if left_score == 5:
    winner = "Left player wins!"
elif right_score == 5:
    winner = "Right player wins!"

winner is None または winner is not None でテストします。誰かが勝った後は、ボールは待機し続けます。Spaceキーでサーブできるのは winner is None の間だけです。

サーブのメッセージの代わりに、勝者を (300, 120) の位置に中央揃えで表示します。

challenge icon

チャレンジ

中級
  1. ループの前に、winner = Noneを設定します。
  2. 得点処理の後、left_score == 5の場合はwinnerを"Left player wins!"に、right_score == 5の場合は"Right player wins!"に設定します。
  3. Spaceキーでサーブできるのは、winner is Noneの間だけです。
  4. 勝者がいる場合は、Press Space to serveの代わりに、(300, 120)を中心として勝者を表示します。

自分で試してみよう

import pygame

pygame.init()
screen = pygame.display.set_mode((600, 400))
pygame.display.set_caption("Pong")
clock = pygame.time.Clock()
font = pygame.font.Font(None, 36)

ball = pygame.Rect(293, 193, 14, 14)
vx, vy = 5, 4
left = pygame.Rect(20, 160, 12, 80)
right = pygame.Rect(568, 160, 12, 80)
left_score = 0
right_score = 0
waiting = False

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
            waiting = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_w]:
        left.y -= 6
    if keys[pygame.K_s]:
        left.y += 6
    if keys[pygame.K_UP]:
        right.y -= 6
    if keys[pygame.K_DOWN]:
        right.y += 6
    left.clamp_ip(screen.get_rect())
    right.clamp_ip(screen.get_rect())

    if not waiting:
        ball.x += vx
        ball.y += vy
        if ball.top <= 0 or ball.bottom >= 400:
            vy = -vy
        if ball.colliderect(left):
            vx = abs(vx)
            vy = (ball.centery - left.centery) // 6
        if ball.colliderect(right):
            vx = -abs(vx)
            vy = (ball.centery - right.centery) // 6
        if ball.left > 600:
            left_score += 1
            ball.center = (300, 200)
            vx = -vx
            waiting = True
        if ball.right < 0:
            right_score += 1
            ball.center = (300, 200)
            vx = -vx
            waiting = True

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (80, 160, 255), left)
    pygame.draw.rect(screen, (235, 80, 80), right)
    pygame.draw.rect(screen, (255, 196, 0), ball)
    score = font.render(f"{left_score} : {right_score}", True, (240, 240, 240))
    screen.blit(score, score.get_rect(center=(300, 30)))
    if waiting:
        message = font.render("Press Space to serve", True, (240, 240, 240))
        screen.blit(message, message.get_rect(center=(300, 360)))
    pygame.display.flip()
    clock.tick(60)

pygame.quit()
quiz icon腕試し

このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。

Pygameでゲームを作ろうのすべてのレッスン

自分で練習してみよう: Pygameプレイグラウンド