[python] Pygame에서 텍스트와 UI 요소 다루기

Pygame은 Python에서 2D 게임 및 멀티미디어 애플리케이션을 개발하기 위한 라이브러리입니다. 이에 따라 Pygame을 사용하면 사용자 인터페이스(UI) 요소와 텍스트를 쉽게 다룰 수 있습니다. 이번 블로그 포스트에서는 Pygame에서 텍스트와 UI 요소를 생성하고 다루는 방법을 알아보겠습니다.

1. 텍스트 생성하기

Pygame에서 텍스트를 생성하려면 다음과 같은 단계를 따르면 됩니다:

import pygame
from pygame.locals import *

pygame.init()

# 화면 생성
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Text Example")

# 폰트 설정
font = pygame.font.Font(None, 36)

# 텍스트 생성
text = font.render("Hello, Pygame!", True, (255, 255, 255))

# 텍스트 위치 설정
text_rect = text.get_rect(center=(400, 300))

# 화면에 텍스트 그리기
screen.blit(text, text_rect)

# 화면 업데이트
pygame.display.flip()

# 이벤트 루프
running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False

pygame.quit()

위 코드에서는 Pygame을 초기화한 다음, 화면을 생성하고 폰트를 설정합니다. font.render() 함수를 사용하여 텍스트를 생성한 후, 텍스트가 화면에 표시될 좌표를 설정합니다. 마지막으로 screen.blit() 함수를 사용하여 화면에 텍스트를 그립니다.

2. 버튼 생성하기

Pygame에서 버튼을 생성하려면 다음과 같은 클래스를 정의하면 됩니다:

import pygame
from pygame.locals import *

class Button:
    def __init__(self, x, y, width, height, text, text_color, background_color, font_size):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.text_color = text_color
        self.background_color = background_color
        self.font = pygame.font.Font(None, font_size)
        self.clicked = False

    def draw(self, surface):
        pygame.draw.rect(surface, self.background_color, self.rect)
        text_surface = self.font.render(self.text, True, self.text_color)
        text_rect = text_surface.get_rect(center=self.rect.center)
        surface.blit(text_surface, text_rect)

    def handle_event(self, event):
        if event.type == MOUSEBUTTONDOWN:
            if self.rect.collidepoint(event.pos):
                self.clicked = True
        elif event.type == MOUSEBUTTONUP:
            self.clicked = False

# 버튼 생성
button = Button(350, 250, 100, 50, "Click Me!", (255, 255, 255), (0, 0, 255), 24)

# 이벤트 루프
running = True
while running:
    for event in pygame.event.get():
        if event.type == QUIT:
            running = False
        button.handle_event(event)

    # 버튼 그리기
    button.draw(screen)
    pygame.display.flip()

pygame.quit()

위 코드에서는 Button 클래스를 정의하여 버튼을 생성하고 그리는 기능을 구현합니다. 버튼은 사각형 형태로 그리며, 이벤트를 처리하여 클릭 여부를 판단합니다. 버튼을 클릭하면 self.clicked 속성이 True가 되며, 이를 활용하여 다른 동작을 수행할 수 있습니다.

결론

Pygame을 사용하면 텍스트와 UI 요소를 쉽게 다룰 수 있습니다. 이번 블로그 포스트에서는 텍스트 생성 및 버튼 생성에 대한 예제 코드를 살펴보았습니다. Pygame을 활용하여 다양한 UI 요소를 구현해보세요!