목숨
Coddy Pygame 여정의 게임 루프 섹션에 포함된 레슨. 35개 중 31번째.
빗나가면 대가가 따르도록 하세요. 플레이어에게 생명 3개를 주고, 블록이 바닥 아래로 떨어질 때마다 생명 하나를 빼세요. 코드에서 이미 해당 동작이 일어나는 부분을 찾을 수 있습니다. 바로 block.top > 360 분기입니다.
if block.top > 360:
block.y = -20
block.x = random.randint(0, 460)
lives -= 1점수를 표시하는 방식으로 생명도 표시하세요. 매 프레임마다 f"Lives: {lives}"를 렌더링하고, 오른쪽 상단 모서리의 (370, 10) 위치에 블릿하세요.
챌린지
쉬움플레이어에게 생명 3개를 주세요.
- 반복문 전에
lives = 3을 설정하세요. - 블록이 바닥을 지나 떨어지면 생명을 하나 줄이세요.
f"Lives: {lives}"를(240, 240, 240)색상으로 렌더링하고(370, 10)위치에 블릿하세요.
‘플레이’를 누르고 블록을 놓쳐 보세요. Lives: 2가 표시됩니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
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 플레이그라운드