256 Chapter 10
These lines will create our draw_string and show both the num-
ber of smiley bubbles created and the number popped.
Percentage of Smileys Popped
Add these three lines, right after the two draw_string statements:
if (count_smileys > 0):
draw_string += " - Percent: "
draw_string += str(round(count_popped/count_smileys*100, 1))
draw_string += "%"
To get the percentage of smileys popped out of all the smileys
that have been created, we divide count_popped by count_smileys
(count_popped/count_smileys), then multiply by 100 to get the percent
value (count_popped/count_smileys*100). But we’ll have two problems
if we try to show this number. First, when the program starts
and both values are zero, our percentage calculation will produce
a “division by zero” error. To fix this, we’ll show the percentage
popped only if count_smileys is greater than zero.
Second, if the user has created three smileys and popped one
of them—a ratio of one out of three, or 1/3—the percentage will be
33.33333333.... We don’t want the display to get really long every
time there’s a repeating decimal in the percentage calculation, so
let’s use the round() function to round the percentage to one deci-
mal place.
The last step is to draw the string in white pixels, center those
pixels on the screen near the top, and call screen.blit() to copy
those pixels to the game window’s drawing screen:
text = font.render(draw_string, True, WHITE)
text_rect = text.get_rect()
text_rect.centerx = screen.get_rect().centerx
text_rect.y = 10
screen.blit (text, text_rect)
You can see the effect of these changes in Figure 10-7.
The smaller smileys are more difficult to catch and pop,
especially when they’re moving fast, so it’s hard to pop more than
90 percent. That’s exactly what we want. We’ve used this feedback
and challenge/achievement component to make the app feel more
like a game we might play.