kobodl/tools/mock-leaderboard.py
Ville Lindholm 9238ce61c6
Add global leaderboard client (dormant by default)
End-of-game scores are POSTed to a configurable backend URL; the main menu
gains a "Global Leaderboard" entry that fetches and renders the top N for
the current board. Default `global_leaderboard=0` ships the code dormant
until the backend at leaderboard_url is live.

Architecture:
- httpclient.h: thin async interface. http_post_json / http_get fire and
  forget; the user callback runs from http_pump() (native) or the
  Emscripten runtime (web). No blocking calls.
- httpclient_native.cpp: libcurl-multi, polled per frame.
- httpclient_web.cpp: emscripten_fetch (-sFETCH=1 link option).
- leaderboard.{h,cpp}: portable game-side module. Hand-rolled JSON
  build/parse for the tiny fixed-shape wire format; no JSON dep.

Identity: player name + a player-typed "board name" (shared room code).
A per-install RFC-4122-v4 UUID `client_id` is auto-generated on first run
via SDL_rand_bits and stored in the config — server uses it for rate
limiting / dedup, not as a public identity.

Wire format (informational, server is out-of-tree):
  POST /api/scores  body: {board, name, client_id, score, skill,
                           gametype, end_scene, end_lives, end_health,
                           playtime, start_date, end_date}
                    resp: {rank, total}
  GET  /api/scores?board=&limit=50
                    resp: {board, total, scores:[{name,score,end_scene}]}

Hook points:
- manage.cpp game_start: populate hi.start_date; reset_submission().
- manage.cpp game_stop: populate hi.end_date and the profile name on hi,
  then leaderboard::submit_score after scorefile.record.
- kobo.cpp main: http_init/http_shutdown around the run; generate
  client_id on first run when empty.
- kobo.cpp kobo_gfxengine_t::frame: http_pump() before gsm.frame().
- states.cpp st_game_over post_render: renders "Submitting…" / "Rank #N of M"
  / "(offline)" under "GAME OVER".
- states.cpp main_menu: "Global Leaderboard" button (only when enabled
  + board name set).
- states.cpp st_global_leaderboard_t: new browser state listing top 16.
- options.cpp game_options: onoff toggle.

Out of scope for this commit (left as follow-ups):
- In-game text editor for board name / URL (form toolkit has no free-text
  widget; users edit via config file or CLI flags for now).
- Retry queue across sessions.
- Server implementation. tools/mock-leaderboard.py is a 100-line Python
  scratch server for local testing only.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2026-06-05 11:10:20 +03:00

99 lines
3.4 KiB
Python
Executable File

#!/usr/bin/env python3
"""Mock leaderboard server for local testing.
Stores submitted scores in memory, returns rank/total on POST, and serves
the top-N on GET. Sends permissive CORS so the web build can talk to it
from a different port.
Usage:
./tools/mock-leaderboard.py # listens on :8765
./tools/mock-leaderboard.py 8080 # custom port
"""
import json
import sys
from http.server import BaseHTTPRequestHandler, HTTPServer
from urllib.parse import urlparse, parse_qs
# In-memory store: {board_name: [score_record, ...]}
SCORES = {}
def _cors(handler):
handler.send_header("Access-Control-Allow-Origin", "*")
handler.send_header("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
handler.send_header("Access-Control-Allow-Headers", "Content-Type")
class Handler(BaseHTTPRequestHandler):
def do_OPTIONS(self):
self.send_response(204)
_cors(self)
self.end_headers()
def do_GET(self):
url = urlparse(self.path)
if url.path != "/api/scores":
self.send_response(404); _cors(self); self.end_headers(); return
q = parse_qs(url.query)
board = (q.get("board") or [""])[0]
limit = int((q.get("limit") or ["50"])[0])
rows = sorted(SCORES.get(board, []),
key=lambda r: r["score"], reverse=True)[:limit]
body = json.dumps({
"board": board,
"total": len(SCORES.get(board, [])),
"scores": [
{"name": r["name"], "score": r["score"],
"end_scene": r["end_scene"]}
for r in rows
],
}).encode()
self.send_response(200)
self.send_header("Content-Type", "application/json")
_cors(self)
self.end_headers()
self.wfile.write(body)
def do_POST(self):
if urlparse(self.path).path != "/api/scores":
self.send_response(404); _cors(self); self.end_headers(); return
length = int(self.headers.get("Content-Length", "0"))
try:
payload = json.loads(self.rfile.read(length))
except Exception as e:
self.send_response(400); _cors(self); self.end_headers()
self.wfile.write(f"bad json: {e}".encode())
return
board = payload.get("board", "")
SCORES.setdefault(board, []).append(payload)
# Rank: 1 = best. Sort descending, find position.
ranked = sorted(SCORES[board], key=lambda r: r["score"], reverse=True)
# Identify *this* submission by reference equality.
rank = next((i + 1 for i, r in enumerate(ranked) if r is payload), -1)
body = json.dumps({"rank": rank, "total": len(SCORES[board])}).encode()
print(f"[POST] board={board} name={payload.get('name')} "
f"score={payload.get('score')} -> #{rank}/{len(SCORES[board])}")
self.send_response(200)
self.send_header("Content-Type", "application/json")
_cors(self)
self.end_headers()
self.wfile.write(body)
def log_message(self, fmt, *args):
# Keep the noise down; we print our own line on POST.
return
def main():
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8765
srv = HTTPServer(("127.0.0.1", port), Handler)
print(f"mock-leaderboard listening on http://127.0.0.1:{port}")
try:
srv.serve_forever()
except KeyboardInterrupt:
pass
if __name__ == "__main__":
main()