使用 Pyxel 入门 2D 游戏(第5部分):使用类创建角色
发布: (2026年1月8日 GMT+8 23:00)
4 min read
原文: Dev.to
Source: Dev.to
游戏中出现的角色通常被称为 sprites。
在本章节中,我们将使用类来为 sprites 准备一个通用的基类。
你可能会觉得 “类听起来很难……”,但目前的目标只是把角色视为 单一可复用的组件。
完整代码展示在本文末尾。
1. 准备 Sprite 模块
创建一个名为 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 是 “让我们移动角色。”
下次见!
