"""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()