Displaying Text to the Player
00:00 In the previous lesson, you went all “Pew, pew!” and I went, “Whoa!” Your game now has sound! In this lesson, I’ll show you how to display text messages to the user informing them whether they won or lost.
00:32 When you code, you don’t think about how the letters are displayed—just that they’re letters. This is a convenient abstraction, but at the heart of your computer’s display is still pixels, and something somewhere has to know what pixels to turn on and off to show that letter A.
print_text() function takes a surface to write to, a string to write, a font to use, and an optional color. The first step is to use the
.render() method, which renders the text into a new surface.
True parameter here turns anti-aliasing on. This smooths the edges of the text, making it look less ragged. With a text surface in hand, you now want to blit that to the target surface. As you’ve seen before, blitting something requires a bounding rectangle specifying the size of the item being blitted.
The new value for
.center is set to the center of the target surface, which will be the screen. The result of this line is that the text message will be printed at the center of the screen. If you were building a more general utility method, you might want to put extra parameters in to control where the text goes.
02:24 For our simple purposes, the center of the screen will do. Finally, with the math done and the bounding box and blit positions known, the target surface’s blit method is called to actually display the text.
I’m going to add some code to detect win and loss conditions, then show a message. You’ll recall from the
utils.py file, the
print_text() method needs a font. Here, I load that font. By loading
None, the default font will be used.
64 here is the size of the font. The
.message attribute is where I store the message being displayed. As nothing is being displayed right now, it is the empty string. Let me scroll down a bit.
This is inside of the
._game_logic() method in the area that detects when the ship is destroyed. Here, I modify the
.message attribute to inform the user that they lost. A little further down, and here I’m detecting the win condition.
04:25 I’m the king of the rock breakers! There it is, I win! No cheating involved, honest. You’ve built an Asteroids clone, congratulations! In the last lesson, I’ll summarize, suggest some changes you can try out, and point you at a couple of places where you can get more information.
Become a Member to join the conversation.