Menu
CoddyTech

승리 또는 패배

Coddy의 Pygame으로 게임 만들기 코스 레슨. 40개 중 15번째.

게임이 끝납니다. 여기서는 생명이 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를 기준으로 블리팅할 때는 왼쪽 위 모서리를 사용하므로 텍스트가 가운데에 배치됩니다.

challenge icon

챌린지

중급
  1. 움직이는 모든 항목(키 입력, 바구니, 블록, 잡기와 놓치기)을 if lives > 0 and score < 10: 아래로 들여쓰기하세요.
  2. 점수와 목숨을 그린 후, lives == 0일 때는 Game over를, score == 10일 때는 You win!를 (240, 160)을 중심으로 표시하세요.

직접 해보기

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()
quiz icon실력 점검

이 레슨에는 짧은 퀴즈가 포함되어 있습니다. 레슨을 시작해 문제를 풀고 진행 상황을 기록하세요.

Pygame으로 게임 만들기의 모든 레슨

직접 연습해 보세요: Pygame 플레이그라운드