목숨
Coddy의 Pygame으로 게임 만들기 코스 레슨. 40개 중 14번째.
놓치면 대가가 있어야 합니다. 플레이어에게 목숨 3개를 주고, 블록이 바닥 아래로 떨어질 때마다 하나씩 줄이세요. 코드에는 이미 그런 일이 일어나는 부분이 있습니다. 바로 block.top > 360 분기입니다.
if block.top > 360:
block.y = -20
block.x = random.randint(0, 460)
lives -= 1점수를 표시하는 것처럼 목숨도 표시하세요. 매 프레임 f"Lives: {lives}"를 렌더링하고 오른쪽 위 모서리의 (370, 10) 위치에 블릿하세요.
챌린지
쉬움- 루프 전에
lives = 3으로 설정합니다. - 블록이 아래쪽을 지나 떨어지면 하나를 줄입니다.
f"Lives: {lives}"를(240, 240, 240)색상으로 렌더링하고(370, 10)위치에 블릿합니다.
직접 해보기
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 플레이그라운드