Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1

242 Chapter 10


The first step is putting
together the string of text that we
want to display. In a typical video
game, we’d see our points and how
many lives or turns we have left—
for example, Lives: 4, Points: 32.
We already have variables with the
number of lives (lives) and total
points (points). All we have to do is
use the str() function to turn those
numbers into their text equivalent
( 5 becomes "5") and add text to
indicate what the numbers mean in
each pass through our game loop:

draw_string = "Lives: " + str(lives) + " Points: " + str(points)

Our string variable will be called draw_string, and it contains
the text we’d like to draw on the screen to display to users as they
play. To draw that text on the screen, we need to have an object or
variable that is connected to the text-drawing module pygame.font.
A font is another name for a typeface, or the style characters are
drawn in, like Arial or Times New Roman. In the setup section of
your app, add the following line:

font = pygame.font.SysFont("Times", 24)

This creates a variable we’ll call font that will allow us to draw
on the Pygame display in 24-point Times. You can make your text
larger or smaller, but for now, 24 points will work. Next we’ll draw
the text; that should be added into the game loop, right after our
draw_string declaration. To draw the text on the window, we first
draw the string on a surface of its own with the render() command
on the font object we created:

text = font.render(draw_string, True, WHITE)

This creates a variable called text to store a surface that con-
tains the white pixels that make up all the letters, numbers, and
symbols of our string. The next step will get the dimensions (width
and height) of that surface. Longer strings will render or draw
wider, while shorter strings will take fewer pixels to draw. The
Free download pdf