Getting Started with 2D Games Using Pyxel (Part 4): Displaying Text
Source: Dev.to
Displaying Text
In this chapter we will display a score on the game screen.
Text rendering is one of the simplest features in Pyxel. Use the pyxel.text() method with the following arguments:
- X coordinate
- Y coordinate
- Text string to display
- Text color
Simple Text Example
pyxel.text(10, 10, "HELLO, TEXT!!", 12)
Displaying a Score
When displaying a score, formatting the value is very convenient. The :04 format specifier zero‑pads the number to four digits.
# Draw the score
pyxel.text(
10, 10,
"SCORE:{:04}".format(self.score),
12
)
Complete Example
Below is the full code with all features implemented so far.
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()
When you run this program, the result will look like this:
Thank you for reading this chapter.
“Creating Characters with Classes.”
See you next time!!