使用 Pyxel 入门 2D 游戏(第 2 部分):创建游戏屏幕

发布: (2026年1月6日 GMT+8 08:21)
2 min read
原文: Dev.to

Source: Dev.to

创建游戏屏幕

在本章节中,我们使用 Pyxel 创建一个基本的游戏屏幕。

首先,创建一个工作文件夹并添加一个名为 main.py 的文件。
你的文件夹结构应如下所示:

working_folder/
 └ main.py  # File where we write the program

所有代码都将在 main.py 中编写。首先导入 Pyxel 引擎以及任何所需的模块。

import pyxel   # Pyxel game engine
import math    # Math module
import random  # Random number module

W, H = 160, 120  # Game screen width and height

Game 类

# Game
class Game:
    def __init__(self):
        """Constructor"""
        # Start Pyxel
        pyxel.init(W, H, title="Hello, Pyxel!!")
        pyxel.run(self.update, self.draw)

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

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

构造函数通过调用 pyxel.init() 并传入屏幕宽度、高度和窗口标题来初始化游戏屏幕,然后使用 pyxel.run(self.update, self.draw) 启动主循环。

  • self.update() 将处理角色移动和碰撞检测。
  • self.draw() 将处理角色和图形的渲染。

背景颜色

draw() 方法的开头,我们使用单一颜色清除屏幕。
pyxel.cls() 传入 015 之间的数字即可用该颜色填充整个屏幕。

def draw(self):
    """Drawing logic"""
    pyxel.cls(0)   # Fill screen with color 0

请参阅 Pyxel 颜色调色板以获取对应的颜色编号。

完整代码

import pyxel   # Pyxel game engine
import math    # Math module
import random  # Random number module

W, H = 160, 120  # Game screen width and height

# Game
class Game:
    def __init__(self):
        """Constructor"""
        # Start Pyxel
        pyxel.init(W, H, title="Hello, Pyxel!!")
        pyxel.run(self.update, self.draw)

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

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

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

if __name__ == "__main__":
    main()

运行此程序会显示一个已用颜色 0 清除的空白屏幕。

感谢阅读本章节。下章节见!

Back to Blog

相关文章

阅读更多 »