점수 기록하기
Coddy의 Pygame으로 게임 만들기 코스 레슨. 40개 중 13번째.
pygame에서 텍스트는 단어를 그림으로 나타낸 것입니다. pygame.font.Font는 문자열을 surface로 바꾸고, 그 surface를 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)에 오도록 화면에 복사합니다.
채우기 작업을 마친 뒤, 반복문 안에서 텍스트를 렌더링하세요. 점수는 바뀌므로, 한 번 만든 그림은 이전 숫자를 계속 보여 줍니다.
챌린지
쉬움- 루프 전에
font = pygame.font.Font(None, 32)와score = 0을 만드세요. - 바구니가 블록을 잡으면
score에 1을 더하세요. - 블록을 그린 후
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으로 게임 만들기의 모든 레슨
직접 연습해 보세요: Pygame 플레이그라운드