목숨
Coddy Pygame 여정의 게임 루프 섹션에 포함된 레슨. 32개 중 28번째.
빗나가면 대가를 치러야 합니다. 플레이어에게 생명 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 플레이그라운드