Pyxel을 사용한 2D 게임 시작하기 (파트 5): 클래스로 캐릭터 만들기
Source: Dev.to
게임에 등장하는 캐릭터들은 일반적으로 스프라이트라고 부릅니다.
이 장에서는 클래스를 사용하여 스프라이트를 위한 공통 베이스 클래스를 준비합니다.
처음에는 “클래스는 어려워 보인다…” 라고 느낄 수도 있지만, 지금은 단순히 캐릭터를 재사용 가능한 하나의 컴포넌트로 다루는 것이 목표입니다.
전체 코드는 이 글의 마지막에 표시됩니다.
1. 스프라이트 모듈 준비하기
sprite.py라는 새 파일을 만들고 작업 폴더에 배치하세요.
폴더 구조는 다음과 같이 보입니다:
# Folder structure
working_folder/
├─ main.py
├─ sprite.py # sprite module
└─ shooter.pyxres
2. 공통 스프라이트 베이스 클래스 만들기
sprite.py에 BaseSprite라는 클래스를 정의합니다. 이 클래스는 모든 스프라이트의 공통 베이스 클래스로 사용됩니다.
# 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.py에 ShipSprite 클래스를 추가합니다. 이 클래스는 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.py의 Game 클래스에 플레이어 클래스를 세 단계에 걸쳐 통합할 것입니다.
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()
전체 코드
아래는 지금까지 구현된 모든 기능이 포함된 전체 코드입니다.
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()
프로그램을 실행하면 결과는 다음과 같이 나타납니다:
다음에 올 내용…
이 장을 읽어 주셔서 감사합니다. 다음 제목에서는 … (필요에 따라 계속) 다룰 예정입니다.
e는 “캐릭터를 움직이자.”
다음에 뵙겠습니다!
