サーブ
Coddyの「Pygameでゲームを作ろう」コースのレッスン 35/40。
得点が入った後、プレイヤーの準備ができるまで、ボールは中央で待機するようにします。待機するかどうかをフラグで示します。
waiting = False
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
# パドルは常に動く
if not waiting:
# ボールは動き、跳ね返り、得点が入る。得点が入ると waiting = True に設定されるパドルはifの外にあるため、ボールが待機している間にプレイヤーは準備できます。Spaceキーは押すたびに1回だけ反応するため、KEYDOWNイベントから処理します。
ボールの待機中は、画面下部の(300, 360)を中心とする位置にPress Space to serveを表示します。
チャレンジ
中級- ループの前に、
waiting = Falseを設定します。 - ボールの移動、跳ね返り、得点処理を
if not waiting:の中に入れ、各得点の後にwaiting = Trueを設定します。 pygame.K_SPACEに対するKEYDOWNイベントで、waiting = Falseを設定します。- 待機中は、
Press Space to serveを(300, 360)を中心として表示します。
自分で試してみよう
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
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_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())
ball.x += vx
ball.y += vy
if ball.top <= 0 or ball.bottom >= 400:
vy = -vy
if ball.colliderect(left):
vx = abs(vx)
if ball.colliderect(right):
vx = -abs(vx)
if ball.left > 600:
left_score += 1
ball.center = (300, 200)
vx = -vx
if ball.right < 0:
right_score += 1
ball.center = (300, 200)
vx = -vx
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)))
pygame.display.flip()
clock.tick(60)
pygame.quit()
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Pygameでゲームを作ろうのすべてのレッスン
自分で練習してみよう: Pygameプレイグラウンド