[python] Pygame에서 캐릭터 애니메이션 처리하기

개요

Pygame은 파이썬에서 게임 개발을 위한 라이브러리로, 캐릭터 애니메이션 처리를 간단하게 구현할 수 있도록 도와줍니다. 이번 글에서는 Pygame을 사용하여 캐릭터 애니메이션을 처리하는 방법에 대해 알아보겠습니다.

애니메이션 이미지 준비하기

먼저, 애니메이션을 표현하기 위한 이미지를 준비해야 합니다. 캐릭터의 움직임에 따라 여러 개의 이미지 파일을 사용하면 됩니다. 이 때, 이미지 파일들은 모두 같은 크기로 준비해야 합니다.

Pygame 초기화하기

Pygame을 사용하기 위해 먼저 pygame 모듈을 import 해주고, 초기화를 해야 합니다.

import pygame
pygame.init()

게임 화면 설정하기

게임 화면을 설정하기 위해 pygame.display.set_mode() 함수를 사용합니다. 이 함수는 게임 창의 크기를 설정하는데 사용됩니다.

screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

애니메이션 클래스 만들기

class Animation():
    def __init__(self, images, frame_duration):
        self.images = images
        self.frame_duration = frame_duration
        self.current_frame = 0
        self.frame_counter = 0

    def update(self):
        self.frame_counter += 1
        
        if self.frame_counter >= self.frame_duration:
            self.current_frame = (self.current_frame + 1) % len(self.images)
            self.frame_counter = 0

    def draw(self, surface, x, y):
        surface.blit(self.images[self.current_frame], (x, y))

메인 루프 작성하기

Pygame을 사용하여 게임을 구현할 때는 메인 루프를 작성해야 합니다. 메인 루프는 게임 창이 열린 상태에서 동작하는 코드를 계속 실행시키는 역할을 합니다.

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    # 게임 화면 업데이트
    screen.fill((255, 255, 255))
    animation.update()
    animation.draw(screen, character_x, character_y)
    pygame.display.flip()

pygame.quit()

전체 코드

import pygame
pygame.init()

screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))

class Animation():
    def __init__(self, images, frame_duration):
        self.images = images
        self.frame_duration = frame_duration
        self.current_frame = 0
        self.frame_counter = 0

    def update(self):
        self.frame_counter += 1
        
        if self.frame_counter >= self.frame_duration:
            self.current_frame = (self.current_frame + 1) % len(self.images)
            self.frame_counter = 0

    def draw(self, surface, x, y):
        surface.blit(self.images[self.current_frame], (x, y))

running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    screen.fill((255, 255, 255))
    animation.update()
    animation.draw(screen, character_x, character_y)
    pygame.display.flip()

pygame.quit()

마치며

위의 코드를 기반으로 캐릭터 애니메이션을 처리하는 기능을 Pygame을 사용하여 구현할 수 있습니다. 캐릭터의 움직임에 따라 이미지를 변경하고 애니메이션을 보여주는 것은 게임 개발에서 중요한 부분이므로, Pygame을 사용하여 다양한 애니메이션 효과를 구현해보세요.