Score and high score system
Track a score, reward streaks with combos, show floating "+10" popups, and save the high score to a file so it survives restarts.
On this page
What you'll learn
- Displaying a score efficiently
- Combo multipliers with a timer
- Floating, fading score popups
- Saving and loading a high score safely
Prerequisites: Build your first game.
The example#
"""A score with combos, on-screen popups and a high score saved to a JSON file."""
import json
import random
from pathlib import Path
import pygame
WIDTH, HEIGHT = 640, 480
SAVE_FILE = Path.home() / ".pygame_net_demo_scores.json" # outside the game folder
def load_best():
try:
return int(json.loads(SAVE_FILE.read_text())["best"])
except (OSError, ValueError, KeyError, TypeError):
return 0 # first run or damaged file
def save_best(value):
try:
SAVE_FILE.write_text(json.dumps({"best": value}))
except OSError:
pass # read-only folders shouldn't crash the game
class Popup:
def __init__(self, text, pos):
self.text, self.pos, self.life = text, pygame.Vector2(pos), 0.8
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
font = pygame.font.Font(None, 34)
small = pygame.font.Font(None, 26)
rng = random.Random()
score, best, combo, combo_timer = 0, load_best(), 0, 0.0
target = pygame.Rect(300, 220, 44, 44)
popups = []
running = True
while running:
dt = clock.tick(60) / 1000
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
if target.collidepoint(event.pos):
combo = combo + 1 if combo_timer > 0 else 1 # quick hits build a combo
combo_timer = 1.2
points = 10 * combo
score += points
popups.append(Popup(f"+{points}", target.center))
target.topleft = (rng.randint(20, WIDTH - 64), rng.randint(70, HEIGHT - 64))
if score > best:
best = score
else:
combo = 0
elif event.type == pygame.KEYDOWN and event.key == pygame.K_r:
score, combo = 0, 0
combo_timer = max(0.0, combo_timer - dt)
if combo_timer == 0:
combo = 0
for p in popups:
p.life -= dt
p.pos.y -= 60 * dt
popups = [p for p in popups if p.life > 0]
screen.fill((20, 26, 46))
pygame.draw.rect(screen, (244, 197, 49), target, border_radius=8)
screen.blit(font.render(f"Score {score:,}", True, (230, 236, 247)), (16, 12))
hs = font.render(f"Best {best:,}", True, (157, 194, 255))
screen.blit(hs, (WIDTH - hs.get_width() - 16, 12))
if combo > 1:
screen.blit(small.render(f"Combo x{combo}", True, (244, 197, 49)), (16, 44))
for p in popups:
surf = small.render(p.text, True, (255, 255, 255))
surf.set_alpha(int(255 * p.life / 0.8)) # fade out
screen.blit(surf, surf.get_rect(center=p.pos))
screen.blit(small.render("Click the square quickly to build a combo. R resets.", True, (150, 165, 195)), (16, HEIGHT - 30))
pygame.display.flip()
save_best(best)
pygame.quit()Showing the score#
f"Score {score:,}" formats numbers with thousands separators (12,500 instead of 12500). Rendering text each frame is fine for one or two labels; when you have many, cache the rendered Surface and re-render only when the value changes, as shown in the font reference.
Combos#
A combo rewards quick successive hits. Each hit sets combo_timer to 1.2 seconds; if the next hit lands before the timer runs out, the combo grows and multiplies the points. The timer counts down by dt every frame, so the window is the same on every computer.
Floating popups#
Each popup is a tiny object with text, a position and a remaining life. Every frame it moves up and its life shrinks; surf.set_alpha(...) fades it out as life approaches zero, and expired popups are filtered out of the list. The same pattern works for damage numbers, particles and short messages.
Saving the high score#
SAVE_FILE = Path.home() / ".pygame_net_demo_scores.json"Things to get right:
- Where to save: the game folder may be read-only once installed or packaged. A file in the user's home folder (or a platform data directory) is safer. Saving game data covers proper locations on each operating system.
- First run: the file doesn't exist yet.
load_best()returns 0 instead of crashing. - Damaged data: catching
ValueError,KeyErrorandTypeErrorhandles a corrupted or hand-edited file. - When to save: saving once when the game closes is simple; saving whenever a new best is reached protects against crashes.
JSON is human-readable, which also means players can edit it. That's acceptable for a local high score. Online leaderboards need server-side validation, which is beyond Pygame itself.
Common mistakes#
- Saving next to the script with a relative path writes to whatever folder the game was launched from.
- Rendering score text before updating the score shows last frame's value. Update first, draw last.
- Using
picklefor save files you didn't create: loading untrusted pickle data can run code. Stick to JSON for data players can share.
Practice exercises#
- Keep a top-five table of scores with names instead of a single best score.
- Show "NEW HIGH SCORE!" for two seconds when the best is beaten.
- Award a bonus every 1,000 points with a sound and a large popup.
- Add the score system to Snake and save its best score.