Pyxel을 사용한 2D 게임 시작하기 (파트 5): 클래스와 함께 캐릭터 만들기

발행: (2026년 1월 9일 오전 12:00 GMT+9)
5 min read
원문: Dev.to

Source: Dev.to

Kajiru

게임에 등장하는 캐릭터는 일반적으로 스프라이트라고 불립니다.
이 장에서는 클래스를 사용하여 스프라이트의 공통 베이스 클래스를 준비합니다.

처음에 “클래스는 어려워 보인다…” 라고 느낄 수도 있지만, 지금은 캐릭터를 재사용 가능한 단일 컴포넌트로 다루는 것이 목표입니다.

전체 코드는 이 글의 마지막에 표시됩니다.

1. 스프라이트 모듈 준비

새 파일을 sprite.py 라는 이름으로 만들고 작업 폴더에 넣으세요.
폴더 구조는 다음과 같이 보입니다:

# Folder structure
working_folder/
 ├─ main.py
 ├─ sprite.py   # sprite module
 └─ shooter.pyxres

2. 공통 스프라이트 베이스 클래스 만들기

# sprite.py (excerpt)

import pyxel
import math
import random

class BaseSprite:
    def __init__(self, x, y, w=8, h=8):
        """Constructor"""
        self.x = x          # X coordinate
        self.y = y          # Y coordinate
        self.w = w          # Image width
        self.h = h          # Image height

    def update(self):
        """Update logic"""
        pass

    def draw(self):
        """Drawing logic (implemented in subclasses)"""
        pass

3. 플레이어 클래스 만들기

sprite.pyShipSprite 클래스를 추가합니다. 이 클래스는 BaseSprite를 상속하며 플레이어 캐릭터를 만들 때 사용됩니다.

# sprite.py (excerpt)

# …previous code…

class ShipSprite(BaseSprite):
    def __init__(self, x, y):
        """Constructor"""
        super().__init__(x, y)

    def draw(self):
        """Drawing logic"""
        pyxel.blt(
            self.x, self.y, 0,
            0, 0,
            self.w, self.h, 0
        )  # Ship

4. 플레이어 클래스 사용

main.pyGame 클래스에 플레이어 클래스를 통합합니다. 총 세 단계로 진행합니다.

4‑1. 플레이어 초기화

Game 클래스의 생성자에서 플레이어 객체를 생성합니다.

# main.py (excerpt)

# Initialize the player (placed near the bottom‑center of the screen)
self.ship = sprite.ShipSprite(W / 2, H - 40)

4‑2. 플레이어 업데이트

Game 클래스의 update() 메서드에서 플레이어 객체를 업데이트합니다.
(이 단계에서는 아직 플레이어가 움직이지 않습니다.)

# main.py (excerpt)

# Update the player
self.ship.update()

4‑3. 플레이어 그리기

Game 클래스의 draw() 메서드에서 플레이어 객체를 그립니다.

# main.py (excerpt)

# Draw the player
self.ship.draw()

Complete Code

아래는 지금까지 구현된 모든 기능을 포함한 전체 코드입니다.

sprite.py

import pyxel
import math
import random

class BaseSprite:
    def __init__(self, x, y, w=8, h=8):
        """Constructor"""
        self.x = x          # X coordinate
        self.y = y          # Y coordinate
        self.w = w          # Image width
        self.h = h          # Image height
        self.vx = 0         # Velocity (X direction)
        self.vy = 0         # Velocity (Y direction)

    def update(self):
        """Update logic"""
        self.x += self.vx   # Move in X direction
        self.y += self.vy   # Move in Y direction

    def draw(self):
        """Drawing logic (implemented in subclasses)"""
        pass

class ShipSprite(BaseSprite):
    def __init__(self, x, y):
        """Constructor"""
        super().__init__(x, y)

    def draw(self):
        """Drawing logic"""
        pyxel.blt(
            self.x, self.y, 0,
            0, 0,
            self.w, self.h, 0
        )  # Ship

main.py

import pyxel
import math
import random
import sprite   # Import the sprite module

W, H = 160, 120

# Game
class Game:
    def __init__(self):
        """Constructor"""

        # Initialize score
        self.score = 0

        # Initialize player
        self.ship = sprite.ShipSprite(W / 2, H - 40)

        # Start Pyxel
        pyxel.init(W, H, title="Hello, Pyxel!!")
        pyxel.load("shooter.pyxres")
        pyxel.run(self.update, self.draw)

    def update(self):
        """Update logic"""

        # Update player
        self.ship.update()

    def draw(self):
        """Drawing logic"""
        pyxel.cls(0)

        # Draw score
        pyxel.text(
            10, 10,
            "SCORE:{:04}".format(self.score),
            12
        )

        # Draw player
        self.ship.draw()

def main():
    """Main entry point"""
    Game()

if __name__ == "__main__":
    main()

프로그램을 실행하면 결과는 다음과 같이 표시됩니다:

Game screenshot

다음에 올 내용…

이 장을 읽어 주셔서 감사합니다. 다음 제목에서는 … (필요에 따라 계속).

e is **“Let’s Move the Character.”**

See you next time!
Back to Blog

관련 글

더 보기 »