이기거나 지거나
Coddy Pygame 여정의 게임 루프 섹션에 포함된 레슨. 35개 중 32번째.
게임이 끝납니다. 여기서는 목숨이 0이 되면 지고 점수가 10이 되면 이깁니다. 둘 중 어느 일도 일어나지 않은 동안에는 게임이 진행 중입니다.
게임이 끝났을 때 멈추도록 움직이는 모든 것을 하나의 조건문 안에 넣으세요.
if lives > 0 and score < 10:
# 키, 바구니, 블록, 잡기와 놓치기그리기는 해당 if문 바깥에 둡니다. 화면에는 마지막 프레임이 계속 표시되고, 그 위에 결과가 표시됩니다.
if lives == 0:
message = font.render("Game over", True, (240, 240, 240))
screen.blit(message, message.get_rect(center=(240, 160)))message.get_rect(center=(240, 160))는 텍스트 이미지의 가운데가 (240, 160)에 오도록 배치한 Rect입니다. Rect를 기준으로 블리팅하면 왼쪽 위 모서리가 사용되므로 텍스트가 가운데에 놓입니다.
챌린지
중급승리하거나 패배하면 게임을 끝내세요.
- 움직이는 모든 것(키, 바구니, 블록, 잡기와 놓치기)을
if lives > 0 and score < 10:아래에 들여쓰기하세요. - 점수와 목숨을 표시한 다음,
lives == 0이면Game over를,score == 10이면You win!을(240, 160)에 가운데 정렬해 표시하세요.
‘플레이’를 누르고 블록 세 개를 놓치세요. Game over가 표시되고 게임이 멈춥니다. 그런 다음 ‘확인’을 누르세요.
직접 해보기
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
lives = 3
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)
lives -= 1
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))
lives_text = font.render(f"Lives: {lives}", True, (240, 240, 240))
screen.blit(lives_text, (370, 10))
pygame.display.flip()
clock.tick(60)
pygame.quit()
게임 루프의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드