"""Saving settings and progress to the right per-user folder, safely.""" import json import os import sys import tempfile from pathlib import Path import pygame APP_NAME = "MyPygameGame" DEFAULTS = {"version": 1, "volume": 0.8, "fullscreen": False, "best_score": 0, "unlocked_level": 1} def data_dir(): """A writable folder for this game's files on Windows, macOS and Linux.""" if sys.platform == "win32": base = Path(os.environ.get("APPDATA", Path.home() / "AppData" / "Roaming")) elif sys.platform == "darwin": base = Path.home() / "Library" / "Application Support" else: base = Path(os.environ.get("XDG_DATA_HOME", Path.home() / ".local" / "share")) folder = base / APP_NAME folder.mkdir(parents=True, exist_ok=True) return folder SAVE_PATH = data_dir() / "save.json" def load(): try: data = json.loads(SAVE_PATH.read_text(encoding="utf-8")) except (OSError, ValueError): return dict(DEFAULTS) # missing or corrupt: start fresh merged = dict(DEFAULTS) merged.update({k: v for k, v in data.items() if k in DEFAULTS}) # ignore unknown keys return merged def save(data): """Write to a temporary file first, then replace: a crash can't leave a half-written save.""" fd, tmp = tempfile.mkstemp(dir=SAVE_PATH.parent, suffix=".tmp") with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump(data, f, indent=2) os.replace(tmp, SAVE_PATH) pygame.init() screen = pygame.display.set_mode((640, 300)) clock = pygame.time.Clock() font = pygame.font.Font(None, 30) state = load() running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False elif event.type == pygame.KEYDOWN: if event.key == pygame.K_UP: state["volume"] = round(min(1.0, state["volume"] + 0.1), 1) elif event.key == pygame.K_DOWN: state["volume"] = round(max(0.0, state["volume"] - 0.1), 1) elif event.key == pygame.K_SPACE: state["best_score"] += 100 elif event.key == pygame.K_s: save(state) screen.fill((20, 26, 46)) lines = [f"Volume {state['volume']:.1f} (Up/Down)", f"Best score {state['best_score']} (Space)", "S saves, closing the window saves too", f"File: {SAVE_PATH}"] for i, line in enumerate(lines): screen.blit(font.render(line, True, (230, 236, 247)), (20, 30 + i * 40)) pygame.display.flip() clock.tick(30) save(state) pygame.quit()