0% found this document useful (0 votes)
10 views1 page

Python 025

Uploaded by

darkflux514
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views1 page

Python 025

Uploaded by

darkflux514
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 1

# Prepare the initial score image.

4 self.prep_score()

Because Scoreboard writes text to the screen, we begin by importing the


pygame.font module. Next, we give __init__() the ai_game parameter so it can
access the settings, screen, and stats objects, which it will need to report the
values we’re tracking 1. Then we set a text color 2 and instantiate a font
object 3.
To turn the text to be displayed into an image, we call prep_score() 4,
which we define here:

scoreboard.py def prep_score(self):


"""Turn the score into a rendered image."""
1 score_str = str(self.stats.score)
2 self.score_image = self.font.render(score_str, True,
self.text_color, self.settings.bg_color)

# Display the score at the top right of the screen.


3 self.score_rect = self.score_image.get_rect()
4 self.score_rect.right = self.screen_rect.right - 20
5 self.score_rect.top = 20

In prep_score(), we turn the numerical value stats.score into a string 1


and then pass this string to render(), which creates the image 2. To display
the score clearly onscreen, we pass the screen’s background color and the
text color to render().
We’ll position the score in the upper-right corner of the screen and
have it expand to the left as the score increases and the width of the num-
ber grows. To make sure the score always lines up with the right side of
the screen, we create a rect called score_rect 3 and set its right edge 20 pixels
from the right edge of the screen 4. We then place the top edge 20 pixels
down from the top of the screen 5.
Then we create a show_score() method to display the rendered score
image:

scoreboard.py def show_score(self):


"""Draw score to the screen."""
self.screen.blit(self.score_image, self.score_rect)

This method draws the score image onscreen at the location score_rect
specifies.

Making a Scoreboard
To display the score, we’ll create a Scoreboard instance in AlienInvasion. First,
let’s update the import statements:

alien_invasion.py --snip--
from game_stats import GameStats
from scoreboard import Scoreboard
--snip--

Scoring 287

You might also like