使用 Pyxel 入门 2D 游戏(第4部分):显示文本
发布: (2026年1月7日 GMT+8 23:00)
2 min read
原文: Dev.to
Source: Dev.to
显示文本
在本章节中,我们将在游戏屏幕上显示分数。
文本渲染是 Pyxel 中最简单的功能之一。使用 pyxel.text() 方法并传入以下参数:
- X 坐标
- Y 坐标
- 要显示的文本字符串
- 文本颜色
简单文本示例
pyxel.text(10, 10, "HELLO, TEXT!!", 12)
显示分数
在显示分数时,对数值进行格式化非常方便。:04 格式说明符会在数字前填充零,使其为四位数。
# Draw the score
pyxel.text(
10, 10,
"SCORE:{:04}".format(self.score),
12
)
完整示例
下面是截至目前已实现的全部功能的完整代码。
import pyxel
import math
import random
W, H = 160, 120 # Game screen width and height
# Game
class Game:
def __init__(self):
"""Constructor"""
# Initialize score
self.score = 0
# Start Pyxel
pyxel.init(W, H, title="Hello, Pyxel!!")
pyxel.load("shooter.pyxres")
pyxel.run(self.update, self.draw)
def update(self):
"""Update logic"""
# Score test
self.score += 1
def draw(self):
"""Drawing logic"""
pyxel.cls(0)
# Draw the score
pyxel.text(
10, 10,
"SCORE:{:04}".format(self.score),
12
)
def main():
"""Main entry point"""
Game()
if __name__ == "__main__":
main()
运行此程序后,结果将如下所示:
感谢阅读本章节。
“使用类创建角色”。
下次见!!