Displaying Text
In this chapter, we will display a score on the game screen.
The complete code is shown at the end of this article.
1. Displaying Text
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
# main.py (excerpt)
pyxel.text(10, 10, "HELLO, TEXT!!", 12)
2. Formatting the Score Display
When displaying a score, formatting the value is very convenient.
The :04 part means the number will be zero-padded to 4 digits.
# main.py (excerpt)
# Draw the score
pyxel.text(
10, 10,
"SCORE:{:04}".format(self.score),
12
)
Complete Code
Below is the complete code with all features implemented so far.
# main.py
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:
Coming Up Next...
Thank you for reading this chapter.
The next title is “Creating Characters with Classes.”
See you next time!!

Top comments (0)