ライフ
Coddyの「Pygameでゲームを作ろう」コースのレッスン 14/40。
ミスをすると何かを失うようにしましょう。プレイヤーに3つのライフを与え、ブロックが画面の下端を通過するたびに1つ減らします。その処理を行うコードの場所はすでにあります。block.top > 360の分岐です。
if block.top > 360:
block.y = -20
block.x = random.randint(0, 460)
lives -= 1スコアと同じようにライフを表示します。毎フレームf"Lives: {lives}"を描画し、右上隅の(370, 10)にblitします。
チャレンジ
簡単- ループの前に、
lives = 3を設定します。 - ブロックが画面の下端を通り過ぎたら、1つ減らします。
f"Lives: {lives}"を(240, 240, 240)で描画し、(370, 10)に blit します。
自分で試してみよう
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
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)
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))
pygame.display.flip()
clock.tick(60)
pygame.quit()
このレッスンには短いクイズがあります。レッスンを始めて解答し、進捗を記録しましょう。
Pygameでゲームを作ろうのすべてのレッスン
自分で練習してみよう: Pygameプレイグラウンド