Menu
CoddyTech

점수 기록하기

Coddy Pygame 여정의 게임 루프 섹션에 포함된 레슨. 32개 중 27번째.

pygame에서 텍스트는 단어를 그림으로 표현한 것입니다. pygame.font.Font는 문자열을 표면으로 바꾸고, screen.blit으로 그 표면을 그립니다.

font = pygame.font.Font(None, 32)

text = font.render(f"Score: {score}", True, (240, 240, 240))
screen.blit(text, (10, 10))

Font(None, 32)는 pygame에 내장된 글꼴이며 높이는 32픽셀입니다. 루프 전에 한 번 만드세요. render(text, True, color)는 단어를 그리며, True는 가장자리를 부드럽게 합니다. blit(surface, (x, y))는 그림의 왼쪽 위 모서리를 (x, y)에 놓고 화면에 복사합니다.

채우기 작업을 한 다음, 루프 안에서 텍스트를 렌더링하세요. 점수는 바뀌는데 그림을 한 번만 만들면 이전 숫자가 계속 표시됩니다.

challenge icon

챌린지

쉬움
  1. 루프 전에 font = pygame.font.Font(None, 32)와 score = 0을 만드세요.
  2. 바구니가 블록을 잡으면 score에 1을 더하세요.
  3. 블록을 그린 후, f"Score: {score}"를 (240, 240, 240) 색상으로 렌더링하고 (10, 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()

basket = pygame.Rect(200, 330, 80, 16)
block = pygame.Rect(220, 0, 20, 20)

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)

    screen.fill((30, 30, 46))
    pygame.draw.rect(screen, (80, 160, 255), basket)
    pygame.draw.rect(screen, (235, 80, 80), block)
    pygame.display.flip()
    clock.tick(60)

pygame.quit()

게임 루프의 모든 레슨

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