Keeping Score

Now let's move onto tracking the game's score and displaying that score at the top of the screen.

Step 1: Define a score variable before our game loop and set it to an initial value of zero.

def main():   
	...   
	score = 0
	...

Step 2: We want the score to increment once a pipe passes the birds. A hacky way to do this is to increment once a Pipe has passed the middle of the screen. To do so, we’ll need to add an instance variable to our Pipe class to remember whether it’s already been counted in the score.

Let's add an instance variable to the Pipe class.

self.scored = 0
for pipe in Pipe.pipes:   
	if pipe.right_x() < SCREEN_WIDTH // 2 and not pipe.scored:       
		pipe.scored = 1       
		score += 1

Step 3: Now that we have a way of tracking the score, we want to display the score during every frame. We’ll create a display_score method that gets called each frame. Additionally, we’ll need a font for the text that we create, so let’s initialize that too.

SCREEN_WIDTH, SCREEN_HEIGHT = 500, 768
SCREEN = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
**FONT = pygame.font.Font('freesansbold.ttf', 72)**
pygame.display.set_caption("Codeology")

**def display_score(score):   
	score_img = FONT.render("{}".format(score), True, (255, 255, 255))   
	SCREEN.blit(score_img, (SCREEN_WIDTH // 2, 60))**

Step 4: Finally, let’s also increase the frequency at which the pipes are generated. Once the rightmost pipe on the screen is 300 pixels from the right side of the screen, we generate a new pipe.

if len(Pipe.pipes) == 0 or **Pipe.pipes[-1].right_x() < SCREEN_WIDTH - 300:**   
	bottom_y = random.randint(300, SCREEN_HEIGHT - 200)   
	top_y = random.randint(100, bottom_y - 200)   
	pipe = Pipe(SCREEN_WIDTH, bottom_y, top_y)

Sound Effects

To complete our game, let's add some sound effects to improve the game experience. We're going to be including a flapping sound whenever the player presses space and a ding sound effect whenever the player scores a point.

Step 1: All sound-related effects in Pygame are handled by a mixer. We can initialize the mixer just like we would the game itself.

pygame.mixer.init()

Step 2: Next, we define the sounds we're going to use. There should be a flap.mp3 and point.mp3 file in the starter code that we can use.

flap_sound = pygame.mixer.Sound("./assets/bird/wing.mp3")
point_sound = pygame.mixer.Sound("./assets/point.mp3")

Step 3: The last thing we need to do is play those sounds at the right time.

The flap sound gets played every time the player presses their space bar...