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 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.
# Setup (before the game loop)score = 0font = pygame.font.SysFont("Arial", 32) # Inside the game loop, Drawing section:score_surface = font.render(f"Score: {score}", True, (255, 255, 255))screen.blit(score_surface, (10, 10))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 = 0 # Inside game loop, Update section:pipe_x -= 4 if pipe_x < -50: pipe_x = 400 score += 1 # Drawing section:score_surface = font.render(f"Score: {score}", True, (255, 255, 255))screen.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.
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.