0โšก
42

Keeping Score

You have built a bird that flies, falls, dodges pipes, and crashes. One thing is missing: how do you know if you are winning? Letโ€™s add a score that goes up every time you survive a pipe.

Keeping Track

A score is just a number that starts at 0 and goes up. The question is: when do we add a point?

๐Ÿง 

State = Memory

In programming, โ€œstateโ€ means the data your program remembers. The score is a piece of state: it persists across frames. We store it in a variable and update it at the right moment.

When a pipe resets to the right side, it means the bird survived. That is +1.

When should we add a point to the score?

Showing the Score

Pygame cannot just print text on screen like print(). We need to create a font, render the text as an image, then draw that image.

text rendering
1# Setup (before the game loop)
2score = 0
๐Ÿ”ข Start at zero
3font = pygame.font.SysFont("Arial", 32)
๐Ÿ”ค Load the Arial font at size 32
4
5# Inside the game loop, Drawing section:
6score_surface = font.render(f"Score: {score}", True, (255, 255, 255))
๐Ÿ–ผ๏ธ Turn the score text into a drawable image (white color)
7screen.blit(score_surface, (10, 10))
๐Ÿ“Œ Draw it at position (10, 10), top-left corner
๐Ÿ–ผ๏ธ

Why so many steps?

In Pygame, everything on screen is a โ€œsurfaceโ€, an image. Text is no different. We render the string into a surface, then blit() (draw) it onto the screen. It sounds complex, but it is just two lines.

The Full Picture

Here is how the score fits into the pipe-reset logic we built in the last level.

score + pipe reset
1score = 0
2
3# Inside game loop, Update section:
4pipe_x -= 4
5
6if pipe_x < -50:
โ™ป๏ธ Pipe went off-screen? Reset it...
7 pipe_x = 400
8 score += 1
๐ŸŽฏ ...and reward the player with a point
9
10# Drawing section:
11score_surface = font.render(f"Score: {score}", True, (255, 255, 255))
๐Ÿ–ผ๏ธ Render the updated score every frame
12screen.blit(score_surface, (10, 10))

Your Turn: Wire Up the Score

Fill in the blanks to increment the score when a pipe is passed.

๐ŸŽฏ
๐ŸŽฏ

Level Goal

Increase the score by 1 every time the bird successfully passes a pipe.

Logic Lab: python.py
0/3
12345678910
score = 0 # Inside the game loop for pipe in pipes: if pipe.centerx == bird_rect.centerx: score # Draw the score score_text = font.render(f"Score: {score}", , (255, 255, 255)) screen.blit(score_text, (10, 10))

Choose for blank #1

๐Ÿ†

You Built a Game

Window, bird, gravity, flapping, pipes, collisions, score. That is a complete Flappy Bird. Every game you will ever build uses these same building blocks. Now go make it your own.