diff --git a/docs/leaderboard-backend.md b/docs/leaderboard-backend.md index 8164b89..64ac46d 100644 --- a/docs/leaderboard-backend.md +++ b/docs/leaderboard-backend.md @@ -251,17 +251,19 @@ Query: `limit` (1–100, default 10), `offset` (0–1000). Anything else → 400 ```json { - "scope": "weekly", "rulesVersion": "1.0.0", + "scope": "weekly", "rulesVersion": "1.1.0", "timeZone": "America/Halifax", "weekStart": "2026-10-19T03:00:00.000Z", "weekEnd": "2026-10-26T03:00:00.000Z", "limit": 10, "offset": 0, "total": 42, - "entries": [ { "id": "c649cb33-…", "rank": 1, "nickname": "Dave J", "score": 9114, "completedAt": "2026-10-22T15:03:11.204Z", "durationSeconds": 127.02 } ] + "entries": [ { "id": "c649cb33-…", "rank": 1, "nickname": "Dave J", "score": 13959, "rulesVersion": "1.1.0", "completedAt": "2026-10-22T15:03:11.204Z", "durationSeconds": 127.02 } ] } ``` ### `GET /scores/:id` → 200 `{ "score": {…}, "ranks": { "allTime": 3, "weekly": 1 } }` (404 if unknown **or hidden**) ### `GET /health` → `{ "ok": true, "rulesVersion": "1.0.0", "schemaVersion": 1, "maxTicks": 72000, "timeLimitSeconds": 1200, "time": "…" }` ### `POST /admin/scores/:id/visibility` — body `{"visible": false, "reason": "offensive"}`, `Authorization: Bearer `. The route does not exist (404) unless `ADMIN_TOKEN` (≥ 16 chars) is configured; never sends CORS headers; failed attempts are rate limited. -Public entries expose only `id, rank, nickname, score, completedAt, durationSeconds, endReason` (`game_over` or `time_limit`). +Public entries expose only `id, rank, nickname, score, rulesVersion, completedAt, durationSeconds, endReason` (`game_over` or `time_limit`). +`rulesVersion` on an entry is the stored rules version for that score, also included in score-detail and accepted-submission responses. +The page-level `rulesVersion` remains the server's current gameplay rules; all-time entries can belong to different versions. ## 7. Atomic, one-use submission @@ -276,17 +278,27 @@ Tested: 12 simultaneous identical submissions and 5 simultaneous *different* one ## 8. Scoring-version compatibility policy * `GAMEPLAY_RULES_VERSION` (`src/replay/constants.ts`) must change whenever physics, spawning, collision or scoring changes. The server only verifies the version it was built with, and the replay header and the run must both match it. -* Leaderboards **only rank scores of the current rules version**; older scores stay in the table (not deleted) but are not mixed in. +* Public display support is defined separately in `src/ranked/scoringEras.ts`: `1.0.0` = **V1**, `1.1.0` = **V2**. These are deliberate scoring eras, not software release numbers. Compatible technical versions can be explicitly added to an existing era; introduce a new era only for substantial scoring/difficulty changes. Unknown versions receive no invented label and are excluded from public boards. * A client built for different rules refuses to start ranked play (`update_required`) when the challenge's rules version differs from its own. * Deploy the new game and the new Worker together. Runs issued before a server upgrade can no longer be reproduced and are rejected with `rules_mismatch` (a player mid-game at deploy time loses that one run). ## 9. Weekly / all-time definitions -* **All-time:** visible scores > 0 under the current rules version. -* **Weekly:** the same, with `completed_at` in `[Monday 00:00, next Monday 00:00)` in **America/Halifax**, from the server's own completion timestamp. Window boundaries are computed with real zone offsets, so a DST week is 167 or 169 hours. Tested: ordinary week, the exact instants either side of Monday midnight, spring (2026-03-08) and autumn (2026-11-01) changes, the New Year week, and a year of random instants tiling without gaps or overlaps. -* **Order:** score descending, then earlier `completed_at`, then smaller `id`. Ranks are ordinal (no shared places). Hidden, zero-score, and other-version entries are excluded; ranks of lower entries shift when an entry is hidden. +* **All-time:** all visible scores > 0 across explicitly supported scoring eras (V1 and V2). Every row displays its era, with a note that scores from different versions may not be directly comparable. +* **Weekly:** visible scores > 0 from the current scoring era only (V2 for current rules `1.1.0`), with `completed_at` in `[Monday 00:00, next Monday 00:00)` in **America/Halifax**, from the server's own completion timestamp. Window boundaries are computed with real zone offsets, so a DST week is 167 or 169 hours. Tested: ordinary week, the exact instants either side of Monday midnight, spring (2026-03-08) and autumn (2026-11-01) changes, the New Year week, and a year of random instants tiling without gaps or overlaps. +* **Order:** score descending, then earlier `completed_at`, then smaller `id`. Ranks are ordinal (no shared places). Hidden, zero-score and unsupported-version entries are excluded; ranks of lower entries shift when an entry is hidden. Pages, totals, score details and post-submission ranks use the same eligibility rules. * Zero-score runs are accepted (the run is finished, one-use) but never listed. +Historical personal bests remain valid across eras, including when their weekly rank is null. This device's remembered score IDs +and highlights are preserved. Stored rules metadata is refreshed from score detail and cached for offline labels; legacy cached +records with no version show `VERSION UNKNOWN` until refreshed. Visible unknown-version score details retain their raw version +and have null ranks. No dates or current-version defaults are used to guess an era. + +The existing `scores.rules_version` column and indexes support these reads. No data rewrite, reset or migration is required. +After review and approval, the coordinated CI release on `main` deploys the Worker read/rank/API changes, verifies its health, +then publishes the frontend labels and personal-best handling. PR validation does not deploy either component. +The extra API field is additive; replay schema and gameplay rules remain unchanged. This does not enable V1 replay verification. + ## 10. Abuse prevention One-use run ids; CSPRNG tokens and seeds; expiry; atomic state transitions; per-client and global rate limits stored in the database (exact, shared by all instances); credentials and cheap checks before the body is read; strict size/encoding limits; validation before simulation; minimum-elapsed-time rule; rejection of non-approved configuration; an `Origin` allow-list for browser POSTs (hygiene, not authentication); nickname charset with no markup characters; admin routes disabled by default; no frontend API key (none would be secret). Rate limits (defaults, env-tunable): 30 run starts and 30 submissions per client-hash per hour; 3,000 starts and 1,200 submissions per hour globally. Client identity is a salted hash of `CF-Connecting-IP`, used only as one coarse layer; shared networks share a bucket, so limits are generous and nothing is *granted* based on an IP. Turnstile was not added: it adds friction and the main risk (bots playing well) is not something it fixes. diff --git a/phaser-asteroids/README.md b/phaser-asteroids/README.md index 810266b..91408cf 100644 --- a/phaser-asteroids/README.md +++ b/phaser-asteroids/README.md @@ -16,6 +16,9 @@ and runs only those suites. After changing test scripts alone, `npm run test:fea can reuse that build. Rebuild after source or asset changes. See [focused testing and timings](docs/test-performance.md). Minor cosmetic UI edits use the existing Vite server and only relevant focused checks; two minutes is the ceiling. +`npm run test:feature -- history` checks the V1/V2 boards, labels, legacy personal bests and a verified V2 submission +against a temporary local Worker/D1 database and Chromium. It does not access production data. + For physical Android ranked testing against local Worker/D1, use the opt-in [LAN startup and S25 checklist](../docs/android-lan-testing.md). Requires Node.js 20.19+ or 22.12+ (Vite 8's requirement; developed on Node 22.14). diff --git a/phaser-asteroids/docs/gameplay-experiment-a.md b/phaser-asteroids/docs/gameplay-experiment-a.md index ca17680..b7d6339 100644 --- a/phaser-asteroids/docs/gameplay-experiment-a.md +++ b/phaser-asteroids/docs/gameplay-experiment-a.md @@ -2,6 +2,8 @@ Historical record of the approved A baseline. Experiment B now adds explosions on top of these settings; see `gameplay-experiment-b.md` for current behavior and the combined ranked reference result. +The historical ranking policy below has since been replaced: ALL TIME now supports labeled V1/V2 scores, +while THIS WEEK uses the current era. See `../../docs/leaderboard-backend.md` for that policy. Rules `1.1.0`, replay schema still `1`. Initial values: diff --git a/phaser-asteroids/docs/test-performance.md b/phaser-asteroids/docs/test-performance.md index 4deafd2..427b577 100644 --- a/phaser-asteroids/docs/test-performance.md +++ b/phaser-asteroids/docs/test-performance.md @@ -21,7 +21,8 @@ It stops at the first failed suite. Each child command has a ten-minute limit; e Longer legacy suites can still use their existing commands. Run from `phaser-asteroids/`. Available names: `smoke`, `keyboard`, `combat`, `coop`, `gamepad`, `touch`, `music`, `menu`, -`mobile-entry`, `pages`, `replay`, `ranked`, `ranked-ui`, `ranked-input`, `worker`. +`mobile-entry`, `pages`, `replay`, `ranked`, `ranked-ui`, `ranked-input`, `history`, `worker`. +Use `history` for the V1/V2 board, label and personal-best regression against an isolated local Worker/D1. For a mobile-entry feature, select `mobile-entry`; this already covers PLAY, PRACTICE, touch readiness, error paths and desktop entry. It is unnecessary for a cosmetic label edit. diff --git a/phaser-asteroids/scripts/historical-leaderboard.mjs b/phaser-asteroids/scripts/historical-leaderboard.mjs new file mode 100644 index 0000000..946946c --- /dev/null +++ b/phaser-asteroids/scripts/historical-leaderboard.mjs @@ -0,0 +1,114 @@ +// Focused regression: production build + real local Worker/D1 + Chromium. No production data or services are used. +// Run after building: node scripts/historical-leaderboard.mjs +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { settleTitleInput } from './lib/menuWaits.mjs'; +import { clickItem, menuItems, openTitle, rankedState, requireBuild, sceneTexts, sleep, startGameAndBrowser, WorkerStack } from './lib/rankedStack.mjs'; + +const GAME_PORT = Number(process.env.HISTORY_GAME_PORT ?? 4420); +const worker = new WorkerStack({ port: Number(process.env.HISTORY_API_PORT ?? 8798), gamePort: GAME_PORT, vars: { RANKED_TIME_LIMIT_SECONDS: '8' } }); +const caption = 'SCORES FROM DIFFERENT VERSIONS MAY NOT BE DIRECTLY COMPARABLE.'; +const id = (i) => `00000000-0000-4000-8000-${String(i).padStart(12, '0')}`; +const api = async (path) => { + const res = await fetch(`${worker.API}/api/v1${path}`); + assert.equal(res.status, 200); + return res.json(); +}; +async function waitText(page, scene, text) { + await page.waitForFunction(([key, expected]) => { + const walk = (list) => list.some((o) => o.visible && (o.type === 'Container' ? walk(o.list) : o.type === 'Text' && o.text === expected)); + return walk(window.__game.scene.getScene(key).children.list); + }, [scene, text], { timeout: 15000 }); +} +async function allTime(page) { + const zone = (await menuItems(page)).items.find((i) => i.id === 'scope').zones.find((z) => z.name === 'ALL TIME'); + const point = await page.evaluate(([x, y]) => { + const c = document.querySelector('canvas').getBoundingClientRect(); + return { x: c.left + x * c.width / 1280, y: c.top + y * c.height / 720 }; + }, [zone.x + zone.w / 2, zone.y + zone.h / 2]); + await page.mouse.click(point.x, point.y); + await waitText(page, 'StartScene', 'Past Week'); +} + +requireBuild(); +let game; +process.on('exit', () => worker.cleanup()); +try { + const migration = worker.migrate(); + assert.ok(migration.ok, migration.output); + await worker.start(); + const now = Date.now(); + const rows = [ + ['Old Champ_99!', 20000, '1.0.0', now, 'visible'], // historical rules, inside the current week + ['Current Pilot', 1000, '1.1.0', now, 'visible'], + ['Past Week', 30000, '1.1.0', now - 9 * 86400000, 'visible'], + ['Hidden Pilot', 99999, '1.0.0', now, 'hidden'], + ['Unknown Pilot', 99998, '9.0.0', now, 'visible'], + ['Zero Pilot', 0, '1.0.0', now, 'visible'], + ]; + assert.ok(worker.exec(rows.map(([name, score, version, at, visibility], i) => { + const run = id(i + 100); + return `INSERT INTO runs (id, token_hash, seed, rules_version, config_json, created_at, expires_at, status, finished_at, score_id) + VALUES ('${run}', 'x', 1, '${version}', '{}', ${at - 60000}, ${at + 3600000}, 'accepted', ${at}, '${id(i)}'); + INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ticks, duration_ms, visibility) + VALUES ('${id(i)}', '${run}', ${score}, '${name}', ${at}, '${version}', 3600, 60000, '${visibility}');`; + }).join('\n'))); + const board = await api('/leaderboard/all-time'); + assert.equal(board.total, 3); + assert.deepEqual(board.entries.map((e) => [e.id, e.rank, e.rulesVersion]), [[id(2), 1, '1.1.0'], [id(0), 2, '1.0.0'], [id(1), 3, '1.1.0']]); + const weekly = await api('/leaderboard/weekly'); + assert.equal(weekly.total, 1); + assert.equal(weekly.entries[0].id, id(1)); + assert.deepEqual((await api(`/scores/${id(0)}`)).ranks, { allTime: 2, weekly: null }); + console.log('PASS real Worker: mixed-era ordering, counts, exclusions and historical detail ranks'); + + game = await startGameAndBrowser(GAME_PORT); + const context = await game.browser.newContext({ viewport: { width: 1280, height: 720 } }); + await context.addInitScript((best) => localStorage.setItem('asteroids.rankedScores', JSON.stringify([best])), { + id: id(0), score: 20000, at: new Date(now).toISOString(), nickname: 'Old Champ_99!', // legacy cache: no rulesVersion + }); + const page = await openTitle(context, game.GAME, { api: worker.API }); + await clickItem(page, 'scores'); + await waitText(page, 'StartScene', 'Current Pilot'); + const bestLine = 'YOUR BEST VERIFIED SCORE: 20,000 V1 (Old Champ_99!)'; + await waitText(page, 'StartScene', bestLine); + let texts = await sceneTexts(page, 'StartScene'); + assert.ok(!texts.includes('Old Champ_99!') && texts.includes('V2')); + await allTime(page); + texts = await sceneTexts(page, 'StartScene'); + assert.ok(texts.includes(caption) && texts.includes('V1') && texts.includes('V2') && texts.includes('YOU')); + const cached = await page.evaluate(() => JSON.parse(localStorage.getItem('asteroids.rankedScores'))); + assert.equal(cached[0].rulesVersion, '1.0.0'); + fs.mkdirSync('scripts/.smoke-output', { recursive: true }); + await page.screenshot({ path: 'scripts/.smoke-output/historical-leaderboard-desktop.png' }); + await page.setViewportSize({ width: 844, height: 390 }); + await page.screenshot({ path: 'scripts/.smoke-output/historical-leaderboard-phone.png' }); + console.log('PASS browser: weekly/current era, mixed labels, comparison note, YOU highlight and legacy personal-best refresh'); + + await page.setViewportSize({ width: 1280, height: 720 }); + await settleTitleInput(page); + await page.keyboard.press('Escape'); + await page.waitForFunction(() => window.__game.scene.getScene('StartScene').menuSnapshot()?.page === 'title'); + await settleTitleInput(page); + await clickItem(page, 'ranked'); + await page.waitForFunction(() => window.__game.scene.getScene('StartScene').menuSnapshot()?.page === 'ranked'); + await settleTitleInput(page); + await clickItem(page, 'start'); + await page.waitForFunction(() => window.__game.scene.getScene('GameScene').resultMenuSnapshot()?.page === 'result', null, { timeout: 30000 }); + await sleep(900); // the result menu ignores input briefly after the run ends + await page.locator('.nick-input').fill('New Pilot'); + await clickItem(page, 'submit', 'result'); + await waitText(page, 'GameScene', 'SCORE VERIFIED!'); + texts = await sceneTexts(page, 'GameScene'); + assert.ok(texts.includes('V2') && texts.includes('YOUR BEST: 20,000 V1') && !texts.includes('NEW PERSONAL BEST!')); + const accepted = (await rankedState(page)).outcome; + assert.equal(accepted.score.rulesVersion, '1.1.0'); + assert.deepEqual((await api(`/scores/${accepted.score.id}`)).ranks, accepted.ranks); + assert.equal((await page.evaluate(() => JSON.parse(localStorage.getItem('asteroids.rankedScores'))))[0].id, id(0)); + assert.deepEqual(page.problems, []); + console.log('PASS verified V2 submission: result labels, historical personal best and consistent server ranks'); + await context.close(); +} finally { + await game?.close(); + worker.cleanup(); +} diff --git a/phaser-asteroids/scripts/ranked-browser.mjs b/phaser-asteroids/scripts/ranked-browser.mjs index 613f1ce..826b48a 100644 --- a/phaser-asteroids/scripts/ranked-browser.mjs +++ b/phaser-asteroids/scripts/ranked-browser.mjs @@ -180,7 +180,7 @@ try { const allTime = scopeZones.find((z) => z.name === 'ALL TIME'); const cp = await page.evaluate(([x, y]) => { const c = document.querySelector('canvas').getBoundingClientRect(); return { x: c.left + (x * c.width) / 1280, y: c.top + (y * c.height) / 720 }; }, [allTime.x + allTime.w / 2, allTime.y + allTime.h / 2]); await page.mouse.click(cp.x, cp.y); - await waitText(page, 'GameScene', /^BEST VERIFIED SCORES OF ALL TIME$/); + await waitText(page, 'GameScene', /^SCORES FROM DIFFERENT VERSIONS MAY NOT BE DIRECTLY COMPARABLE\.$/); await waitText(page, 'GameScene', new RegExp(`^${NICK}$`)); check('switching to ALL TIME shows the same entry', true); check('the player\'s best verified score is shown under the table', (await sceneTexts(page, 'GameScene')).some((t) => t.startsWith('YOUR BEST VERIFIED SCORE:'))); diff --git a/phaser-asteroids/scripts/ranked-ui.mjs b/phaser-asteroids/scripts/ranked-ui.mjs index e2dca87..9ae250b 100644 --- a/phaser-asteroids/scripts/ranked-ui.mjs +++ b/phaser-asteroids/scripts/ranked-ui.mjs @@ -152,7 +152,7 @@ INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ti await waitText(page, 'StartScene', /^Old 4$/); texts = await sceneTexts(page, 'StartScene'); check('ALL TIME includes last week\'s scores and ranks them above (24 scores = 3 pages)', texts.includes('Old 4') && texts.includes('PAGE 1 / 3') && texts.indexOf('Old 4') < texts.indexOf('Week 01')); - check('...with a caption that is not a week', texts.includes('BEST VERIFIED SCORES OF ALL TIME') && !texts.some((t) => t.startsWith('WEEK OF'))); + check('...with a caption that is not a week', texts.includes('SCORES FROM DIFFERENT VERSIONS MAY NOT BE DIRECTLY COMPARABLE.') && !texts.some((t) => t.startsWith('WEEK OF'))); await page.keyboard.press('Escape'); await ctx.close(); } @@ -195,7 +195,7 @@ INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ti await tap(BTN.UP); check('D-pad Up reaches the board tabs', (await focus()) === 'scope', await focus()); await tap(BTN.RIGHT); - await waitText(page, 'StartScene', /^BEST VERIFIED SCORES OF ALL TIME$/); + await waitText(page, 'StartScene', /^SCORES FROM DIFFERENT VERSIONS MAY NOT BE DIRECTLY COMPARABLE\.$/); check('D-pad Right switches THIS WEEK to ALL TIME', true); await tap(BTN.LEFT); await waitText(page, 'StartScene', /^WEEK OF /); @@ -455,7 +455,7 @@ INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ti const k = scale; const c = await centre('canvas'); await finger.tap(c.left + (tab.x + tab.w / 2) * k, c.top + (tab.y + tab.h / 2) * k); - await waitText(page, 'StartScene', /^BEST VERIFIED SCORES OF ALL TIME$/); + await waitText(page, 'StartScene', /^SCORES FROM DIFFERENT VERSIONS MAY NOT BE DIRECTLY COMPARABLE\.$/); check('a finger switches THIS WEEK / ALL TIME', true); await tapItem('back', 'title'); await tapItem('ranked', 'title'); diff --git a/phaser-asteroids/scripts/test-feature.mjs b/phaser-asteroids/scripts/test-feature.mjs index d13a516..179df34 100644 --- a/phaser-asteroids/scripts/test-feature.mjs +++ b/phaser-asteroids/scripts/test-feature.mjs @@ -14,6 +14,7 @@ const suites = { 'mobile-entry': 'scripts/mobile-entry.mjs', pages: 'scripts/pages-check.mjs', replay: 'scripts/replay-browser.mjs', ranked: 'scripts/ranked-browser.mjs', 'ranked-ui': 'scripts/ranked-ui.mjs', 'ranked-input': 'scripts/ranked-input.mjs', + history: 'scripts/historical-leaderboard.mjs', worker: 'server/scripts/worker-e2e.mjs', }; const args = process.argv.slice(2).filter((arg) => arg !== '--'); diff --git a/phaser-asteroids/server/src/leaderboard.ts b/phaser-asteroids/server/src/leaderboard.ts index efe7ae7..b68ad64 100644 --- a/phaser-asteroids/server/src/leaderboard.ts +++ b/phaser-asteroids/server/src/leaderboard.ts @@ -1,5 +1,6 @@ import type { Db, SqlValue } from './db'; import type { ServerSettings } from './config'; +import { rulesInScoringEra, SCORING_ERAS } from '../../src/ranked/scoringEras'; import { weekWindow, type WeekWindow } from './week'; /** @@ -11,6 +12,7 @@ export interface PublicScore { rank: number; nickname: string; score: number; + rulesVersion: string; completedAt: string; durationSeconds: number; /** Verified by the server: the ship ran out of lives, or was still alive when the ranked time limit ended the run. */ @@ -43,16 +45,17 @@ export interface LeaderboardPage { /** * Ranking: highest verified score first; ties go to whoever finished first, then to the smaller id so the order is total and - * stable. Ranks are therefore ordinal (1, 2, 3 ...) with no shared places. Only visible, positive, current-rules scores count. + * stable. Ranks are therefore ordinal (1, 2, 3 ...) with no shared places. Only visible, positive, supported-era scores count. */ const ORDER = 'score DESC, completed_at ASC, id ASC'; -const ELIGIBLE = "visibility = 'visible' AND score > 0 AND rules_version = ?"; +const ELIGIBLE = "visibility = 'visible' AND score > 0"; const toPublic = (row: ScoreRow, rank: number): PublicScore => ({ id: row.id, rank, nickname: row.nickname, score: row.score, + rulesVersion: row.rules_version, completedAt: new Date(row.completed_at).toISOString(), durationSeconds: Math.round(row.duration_ms / 10) / 100, endReason: row.end_reason, @@ -63,6 +66,20 @@ function windowFilter(scope: Scope, window: WeekWindow | null): { sql: string; p return { sql: '', params: [] }; } +function boardVersions(scope: Scope, currentRules: string): string[] { + return scope === 'weekly' ? rulesInScoringEra(currentRules) : Object.keys(SCORING_ERAS); +} + +/** Shared by page totals, page entries and rank counts so pagination and detail/submission ranks agree. */ +function boardFilter(scope: Scope, currentRules: string, window: WeekWindow | null): { sql: string; params: SqlValue[] } { + const versions = boardVersions(scope, currentRules); + const f = windowFilter(scope, window); + return { + sql: `${ELIGIBLE} AND ${versions.length ? `rules_version IN (${versions.map(() => '?').join(', ')})` : '0'}${f.sql}`, + params: [...versions, ...f.params], + }; +} + export async function getLeaderboard( db: Db, settings: ServerSettings, @@ -72,15 +89,14 @@ export async function getLeaderboard( offset: number, ): Promise { const window = scope === 'weekly' ? weekWindow(now, settings.timeZone) : null; - const f = windowFilter(scope, window); - const base: SqlValue[] = [settings.rulesVersion, ...f.params]; + const f = boardFilter(scope, settings.rulesVersion, window); const rows = await db.all( `SELECT id, nickname, score, completed_at, duration_ms, rules_version, end_reason FROM scores - WHERE ${ELIGIBLE}${f.sql} ORDER BY ${ORDER} LIMIT ? OFFSET ?`, - [...base, limit, offset], + WHERE ${f.sql} ORDER BY ${ORDER} LIMIT ? OFFSET ?`, + [...f.params, limit, offset], ); - const total = (await db.first<{ n: number }>(`SELECT COUNT(*) AS n FROM scores WHERE ${ELIGIBLE}${f.sql}`, base))?.n ?? 0; + const total = (await db.first<{ n: number }>(`SELECT COUNT(*) AS n FROM scores WHERE ${f.sql}`, f.params))?.n ?? 0; return { scope, @@ -93,16 +109,16 @@ export async function getLeaderboard( }; } -/** 1-based ordinal rank of one score on a board, or null if it is not on that board (hidden, zero, other rules, other week). */ -export async function rankOf(db: Db, settings: ServerSettings, now: number, scope: Scope, row: ScoreRow): Promise { - if (row.rules_version !== settings.rulesVersion || row.score <= 0) return null; +/** 1-based ordinal rank, or null for hidden, zero, unsupported-era or out-of-scope scores. */ +export async function rankOf(db: Db, settings: ServerSettings, now: number, scope: Scope, row: ScoreRow & { visibility: string }): Promise { + if (row.visibility !== 'visible' || row.score <= 0 || !boardVersions(scope, settings.rulesVersion).includes(row.rules_version)) return null; const window = scope === 'weekly' ? weekWindow(now, settings.timeZone) : null; if (window && (row.completed_at < window.startMs || row.completed_at >= window.endMs)) return null; - const f = windowFilter(scope, window); + const f = boardFilter(scope, settings.rulesVersion, window); const better = await db.first<{ n: number }>( - `SELECT COUNT(*) AS n FROM scores WHERE ${ELIGIBLE}${f.sql} + `SELECT COUNT(*) AS n FROM scores WHERE ${f.sql} AND (score > ? OR (score = ? AND (completed_at < ? OR (completed_at = ? AND id < ?))))`, - [settings.rulesVersion, ...f.params, row.score, row.score, row.completed_at, row.completed_at, row.id], + [...f.params, row.score, row.score, row.completed_at, row.completed_at, row.id], ); return (better?.n ?? 0) + 1; } diff --git a/phaser-asteroids/server/src/runs.ts b/phaser-asteroids/server/src/runs.ts index fd31f52..4ea65b2 100644 --- a/phaser-asteroids/server/src/runs.ts +++ b/phaser-asteroids/server/src/runs.ts @@ -278,6 +278,7 @@ async function buildAccepted(deps: ServiceDeps, scoreId: string, replayed: boole id: row.id, nickname: row.nickname, score: row.score, + rulesVersion: row.rules_version, completedAt: new Date(row.completed_at).toISOString(), durationSeconds: Math.round(row.duration_ms / 10) / 100, endReason: row.end_reason, diff --git a/phaser-asteroids/server/tests/leaderboard.test.ts b/phaser-asteroids/server/tests/leaderboard.test.ts index 88236c1..060b3f2 100644 --- a/phaser-asteroids/server/tests/leaderboard.test.ts +++ b/phaser-asteroids/server/tests/leaderboard.test.ts @@ -4,39 +4,45 @@ import { weekWindow } from '../src/week'; import { botRun, insertScore, makeClock, makeHarness, REFERENCE_SEED, T0 } from './harness'; const HOUR = 3_600_000; -const DAY = 24 * HOUR; type Entry = { id: string; rank: number; nickname: string; score: number }; const scores = (b: { entries: Entry[] }) => b.entries.map((e) => e.score); describe('leaderboard ordering', () => { it('sorts highest first, ties go to the earlier finisher, then to the smaller id; ranks are ordinal', async () => { const h = makeHarness(); - await insertScore(h.db, { id: 'b', score: 500, completedAt: T0 - 5 * HOUR }); + await insertScore(h.db, { id: 'b', score: 500, completedAt: T0 - 5 * HOUR, rules: '1.0.0' }); await insertScore(h.db, { id: 'a', score: 500, completedAt: T0 - 5 * HOUR }); // same score, same instant: id decides - await insertScore(h.db, { id: 'c', score: 500, completedAt: T0 - 9 * HOUR }); // earlier: first among the 500s + await insertScore(h.db, { id: 'c', score: 500, completedAt: T0 - 9 * HOUR, rules: '1.0.0' }); // earlier: first among the 500s await insertScore(h.db, { id: 'd', score: 900, completedAt: T0 }); await insertScore(h.db, { id: 'e', score: 100, completedAt: T0 }); const res = await h.call('GET', '/api/v1/leaderboard/all-time'); expect(res.body.entries.map((e: Entry) => [e.id, e.rank])).toEqual([['d', 1], ['c', 2], ['a', 3], ['b', 4], ['e', 5]]); expect(res.body.total).toBe(5); + expect(res.body.entries.map((e: { rulesVersion: string }) => e.rulesVersion)).toEqual(['1.1.0', '1.0.0', '1.1.0', '1.0.0', '1.1.0']); + const detail = await h.call('GET', '/api/v1/scores/b'); + expect(detail.body).toMatchObject({ score: { rank: 4, rulesVersion: '1.0.0' }, ranks: { allTime: 4, weekly: null } }); }); - it('excludes hidden, zero-score and other-rules entries', async () => { + it('excludes hidden, zero-score and unsupported-rules entries', async () => { const h = makeHarness(); await insertScore(h.db, { score: 300, completedAt: T0 }); - await insertScore(h.db, { score: 9999, completedAt: T0, visibility: 'hidden' }); + const hidden = await insertScore(h.db, { score: 9999, completedAt: T0, visibility: 'hidden', rules: '1.0.0' }); await insertScore(h.db, { score: 0, completedAt: T0 }); await insertScore(h.db, { score: 8888, completedAt: T0, rules: '0.9.0' }); + const unknown = await insertScore(h.db, { score: 99999, completedAt: T0, rules: '9.0.0' }); const res = await h.call('GET', '/api/v1/leaderboard/all-time'); expect(scores(res.body)).toEqual([300]); expect(res.body.total).toBe(1); + expect((await h.call('GET', `/api/v1/scores/${hidden}`)).status).toBe(404); + const detail = await h.call('GET', `/api/v1/scores/${unknown}`); + expect(detail.body).toMatchObject({ score: { rulesVersion: '9.0.0', rank: null }, ranks: { allTime: null, weekly: null } }); }); it('exposes only public display fields', async () => { const h = makeHarness(); await insertScore(h.db, { score: 300, completedAt: T0, nickname: 'Pilot One' }); const entry = (await h.call('GET', '/api/v1/leaderboard/all-time')).body.entries[0]; - expect(Object.keys(entry).sort()).toEqual(['completedAt', 'durationSeconds', 'endReason', 'id', 'nickname', 'rank', 'score']); + expect(Object.keys(entry).sort()).toEqual(['completedAt', 'durationSeconds', 'endReason', 'id', 'nickname', 'rank', 'rulesVersion', 'score']); }); it('rejected and unsubmitted runs never appear', async () => { @@ -53,7 +59,7 @@ describe('leaderboard ordering', () => { describe('pagination is bounded', () => { it('defaults to 10, honours limit/offset and reports total', async () => { const h = makeHarness(); - for (let i = 1; i <= 25; i++) await insertScore(h.db, { score: i * 10, completedAt: T0 }); + for (let i = 1; i <= 25; i++) await insertScore(h.db, { score: i * 10, completedAt: T0, rules: i % 2 ? '1.0.0' : '1.1.0' }); const first = await h.call('GET', '/api/v1/leaderboard/all-time'); expect(first.body.entries).toHaveLength(10); expect(first.body.entries[0].score).toBe(250); @@ -61,6 +67,7 @@ describe('pagination is bounded', () => { expect(scores(page.body)).toEqual([150, 140, 130, 120, 110]); expect(page.body.entries[0].rank).toBe(11); expect(page.body.total).toBe(25); + expect((await h.call('GET', `/api/v1/scores/${page.body.entries[0].id}`)).body.ranks.allTime).toBe(11); expect((await h.call('GET', '/api/v1/leaderboard/all-time?limit=100')).body.entries).toHaveLength(25); }); @@ -82,11 +89,13 @@ describe('weekly leaderboard', () => { await insertScore(h.db, { id: 'in-end', score: 200, completedAt: w.endMs - 1 }); await insertScore(h.db, { id: 'before', score: 9000, completedAt: w.startMs - 1 }); await insertScore(h.db, { id: 'after', score: 9001, completedAt: w.endMs }); + await insertScore(h.db, { id: 'historical', score: 9999, completedAt: T0, rules: '1.0.0' }); const res = await h.call('GET', '/api/v1/leaderboard/weekly'); expect(res.body.entries.map((e: Entry) => e.id)).toEqual(['in-end', 'in-start']); expect(res.body).toMatchObject({ timeZone: 'America/Halifax', weekStart: '2026-10-19T03:00:00.000Z', weekEnd: '2026-10-26T03:00:00.000Z' }); const all = await h.call('GET', '/api/v1/leaderboard/all-time'); - expect(all.body.total).toBe(4); + expect(all.body.total).toBe(5); + expect(all.body.entries[0]).toMatchObject({ id: 'historical', rulesVersion: '1.0.0' }); }); it('rolls over at Halifax Monday midnight', async () => { @@ -101,7 +110,7 @@ describe('weekly leaderboard', () => { it('a verified run lands on both boards with consistent ranks', async () => { const h = makeHarness(); - await insertScore(h.db, { score: 20000, completedAt: T0 - 30 * DAY, nickname: 'Old Champ' }); // all-time only + await insertScore(h.db, { score: 20000, completedAt: T0 - HOUR, nickname: 'Old Champ', rules: '1.0.0' }); // all-time only, despite being this week await insertScore(h.db, { score: 100, completedAt: T0 - HOUR }); const run = await h.start({ seed: REFERENCE_SEED }); const res = await h.playAndSubmit(run, botRun(REFERENCE_SEED).replay); @@ -109,6 +118,18 @@ describe('weekly leaderboard', () => { const detail = await h.call('GET', `/api/v1/scores/${res.body.score.id}`); expect(detail.body.ranks).toEqual({ allTime: 2, weekly: 1 }); expect(detail.body.score.score).toBe(13959); + expect(res.body.score.rulesVersion).toBe('1.1.0'); + expect(detail.body.score.rulesVersion).toBe('1.1.0'); + }); + + it('selects the weekly era from the active rules and excludes unmapped future rules safely', async () => { + const h = makeHarness({ settings: { rulesVersion: '1.0.0' } }); + await insertScore(h.db, { id: 'v1', score: 200, completedAt: T0, rules: '1.0.0' }); + await insertScore(h.db, { id: 'v2', score: 300, completedAt: T0 }); + expect((await h.call('GET', '/api/v1/leaderboard/weekly')).body.entries.map((e: Entry) => e.id)).toEqual(['v1']); + h.settings.rulesVersion = '9.0.0'; + expect((await h.call('GET', '/api/v1/leaderboard/weekly')).body.total).toBe(0); + expect((await h.call('GET', '/api/v1/scores/v2')).body.ranks).toEqual({ allTime: 1, weekly: null }); }); }); diff --git a/phaser-asteroids/server/tests/lifecycle.test.ts b/phaser-asteroids/server/tests/lifecycle.test.ts index 2e2e853..dfdd6a1 100644 --- a/phaser-asteroids/server/tests/lifecycle.test.ts +++ b/phaser-asteroids/server/tests/lifecycle.test.ts @@ -2,7 +2,7 @@ import { gzipSync } from 'node:zlib'; import { describe, expect, it, vi } from 'vitest'; import type { ReplayRecord } from '../../src/replay'; import { faultyDb, openSqliteDb } from '../testing/sqliteDb'; -import { botRun, count, makeClock, makeHarness, REFERENCE_SEED, T0 } from './harness'; +import { botRun, count, insertScore, makeClock, makeHarness, REFERENCE_SEED, T0 } from './harness'; // Replaying real games is CPU-heavy; do not let a busy machine turn that into a spurious timeout. vi.setConfig({ testTimeout: 60_000 }); @@ -117,6 +117,8 @@ describe('forged and invalid recordings are rejected', () => { it('extra config keys', () => rejectedWith((r) => void ((r.header.config as unknown as Record).godMode = true), 'config_mismatch')); it('speed handicap config', () => rejectedWith((r) => void (r.header.config = { ...r.header.config, speed: [2, 1] }), 'config_mismatch')); it('unsupported rules version', () => rejectedWith((r) => void (r.header.rulesVersion = '0.9.0'), 'rules_mismatch')); + it('historical display support does not allow a V1 replay on a current challenge', () => + rejectedWith((r) => void (r.header.rulesVersion = '1.0.0'), 'rules_mismatch')); it('a run issued under older rules, after the server moved on, is rejected with a clear reason', async () => { const h = makeHarness(); const run = await h.start({ seed: REFERENCE_SEED }); @@ -248,6 +250,7 @@ describe('credentials, ownership and expiry', () => { describe('one-use runs', () => { it('re-sending the identical body after success is idempotent: same score, no second row', async () => { const h = makeHarness(); + await insertScore(h.db, { score: 20000, completedAt: T0, rules: '1.0.0' }); const run = await h.start({ seed: REFERENCE_SEED }); const bot = reference(); const first = await h.playAndSubmit(run, bot.replay, { nickname: 'Dave J' }); @@ -255,7 +258,11 @@ describe('one-use runs', () => { expect(again.status).toBe(200); expect(again.body.replayed).toBe(true); expect(again.body.score.id).toBe(first.body.score.id); - expect(await count(h.db, 'scores')).toBe(1); + expect(again.body.score.rulesVersion).toBe('1.1.0'); + expect(again.body.ranks).toEqual({ allTime: 2, weekly: 1 }); + expect(first.body.ranks).toEqual(again.body.ranks); + expect((await h.call('GET', `/api/v1/scores/${again.body.score.id}`)).body.ranks).toEqual(again.body.ranks); + expect(await count(h.db, 'scores')).toBe(2); }); it('a different body for an accepted run is refused (409) and cannot change the stored score', async () => { diff --git a/phaser-asteroids/src/ranked/api.ts b/phaser-asteroids/src/ranked/api.ts index 30bbfdd..5b05579 100644 --- a/phaser-asteroids/src/ranked/api.ts +++ b/phaser-asteroids/src/ranked/api.ts @@ -27,6 +27,8 @@ export interface VerifiedScore { id: string; nickname: string; score: number; + /** Stored gameplay rules. Absent on older API responses; never infer an era from that absence. */ + rulesVersion?: string; completedAt: string; durationSeconds: number; endReason?: ReplayEndReason; @@ -266,6 +268,7 @@ function parseAccepted(data: Record): SubmitResult | null { id: s.id, nickname: s.nickname, score: s.score, + ...(typeof s.rulesVersion === 'string' ? { rulesVersion: s.rulesVersion } : {}), completedAt: s.completedAt, durationSeconds: finiteNumber(s.durationSeconds) ? s.durationSeconds : 0, ...(s.endReason === 'game_over' || s.endReason === 'time_limit' ? { endReason: s.endReason } : {}), @@ -336,6 +339,7 @@ export interface BoardEntry { rank: number; nickname: string; score: number; + rulesVersion?: string; completedAt: string; durationSeconds: number; } @@ -370,6 +374,7 @@ function parseEntry(v: unknown): BoardEntry | null { rank: v.rank as number, nickname: v.nickname, score: v.score, + ...(typeof v.rulesVersion === 'string' ? { rulesVersion: v.rulesVersion } : {}), completedAt: typeof v.completedAt === 'string' ? v.completedAt : '', durationSeconds: finiteNumber(v.durationSeconds) ? v.durationSeconds : 0, }; diff --git a/phaser-asteroids/src/ranked/localScores.ts b/phaser-asteroids/src/ranked/localScores.ts index ad45e54..0fe5413 100644 --- a/phaser-asteroids/src/ranked/localScores.ts +++ b/phaser-asteroids/src/ranked/localScores.ts @@ -14,6 +14,8 @@ export interface LocalScore { at: string; /** The nickname the server stored with it. Several can exist on one device; none identifies a person. */ nickname?: string; + /** Absent on legacy cached records until refreshed from the server. */ + rulesVersion?: string; } export const LOCAL_SCORES_KEY = 'asteroids.rankedScores'; @@ -26,7 +28,11 @@ export function readLocalScores(storage: StorageLike | undefined = safeStorage() if (!Array.isArray(parsed)) return []; return parsed .filter((s): s is LocalScore => !!s && typeof s.id === 'string' && Number.isFinite(s.score) && typeof s.at === 'string') - .map((s) => ({ id: s.id, score: s.score, at: s.at, ...(typeof s.nickname === 'string' ? { nickname: s.nickname } : {}) })); + .map((s) => ({ + id: s.id, score: s.score, at: s.at, + ...(typeof s.nickname === 'string' ? { nickname: s.nickname } : {}), + ...(typeof s.rulesVersion === 'string' ? { rulesVersion: s.rulesVersion } : {}), + })); } catch { return []; } diff --git a/phaser-asteroids/src/ranked/personalBest.ts b/phaser-asteroids/src/ranked/personalBest.ts index 377536b..a94c137 100644 --- a/phaser-asteroids/src/ranked/personalBest.ts +++ b/phaser-asteroids/src/ranked/personalBest.ts @@ -29,8 +29,8 @@ export async function refreshPersonalBest( forgetScore(best.id, storage); continue; } - const confirmed = { ...best, score: detail.score.score, nickname: detail.score.nickname }; - if (confirmed.score !== best.score || confirmed.nickname !== best.nickname) rememberScore(confirmed, storage); + const confirmed = { ...best, score: detail.score.score, nickname: detail.score.nickname, rulesVersion: detail.score.rulesVersion ?? best.rulesVersion }; + if (confirmed.score !== best.score || confirmed.nickname !== best.nickname || confirmed.rulesVersion !== best.rulesVersion) rememberScore(confirmed, storage); return { best: confirmed, ranks: detail.ranks }; } catch { return { best, ranks: null }; diff --git a/phaser-asteroids/src/ranked/scoresModel.ts b/phaser-asteroids/src/ranked/scoresModel.ts index 5e8c712..b98827b 100644 --- a/phaser-asteroids/src/ranked/scoresModel.ts +++ b/phaser-asteroids/src/ranked/scoresModel.ts @@ -1,4 +1,5 @@ import { fetchLeaderboard, type BoardPage, type BoardScope } from './api'; +import { scoringEraLabel } from './scoringEras'; /** Entries per screen: a classic arcade table. The server allows up to 100 per request and offsets up to 1000; this never asks for more than one screen. */ export const BOARD_PAGE_SIZE = 10; @@ -116,3 +117,7 @@ export function formatScore(score: number): string { .toString() .replace(/\B(?=(\d{3})+(?!\d))/g, ','); } + +export function formatEraScore(score: number, rulesVersion: string | undefined): string { + return `${formatScore(score)} ${scoringEraLabel(rulesVersion)}`; +} diff --git a/phaser-asteroids/src/ranked/scoringEras.ts b/phaser-asteroids/src/ranked/scoringEras.ts new file mode 100644 index 0000000..df75fd6 --- /dev/null +++ b/phaser-asteroids/src/ranked/scoringEras.ts @@ -0,0 +1,25 @@ +/** Scoring eras are deliberate gameplay decisions, independent of ordinary software releases. + * Add compatible technical versions to an existing era explicitly; introduce V3 only for meaningful scoring changes. + * This map controls public boards/labels only. It never grants replay compatibility. + */ +export const SCORING_ERAS = Object.freeze({ + '1.0.0': 'V1', + '1.1.0': 'V2', +} as const); + +export type ScoringEra = (typeof SCORING_ERAS)[keyof typeof SCORING_ERAS]; + +export function scoringEra(rulesVersion: string | undefined): ScoringEra | null { + return rulesVersion && Object.hasOwn(SCORING_ERAS, rulesVersion) + ? SCORING_ERAS[rulesVersion as keyof typeof SCORING_ERAS] + : null; +} + +export function scoringEraLabel(rulesVersion: string | undefined): string { + return scoringEra(rulesVersion) ?? 'VERSION UNKNOWN'; +} + +export function rulesInScoringEra(rulesVersion: string): string[] { + const era = scoringEra(rulesVersion); + return era ? Object.keys(SCORING_ERAS).filter((version) => scoringEra(version) === era) : []; +} diff --git a/phaser-asteroids/src/ranked/submission.ts b/phaser-asteroids/src/ranked/submission.ts index 2f7864a..426e4db 100644 --- a/phaser-asteroids/src/ranked/submission.ts +++ b/phaser-asteroids/src/ranked/submission.ts @@ -144,7 +144,7 @@ export class SubmissionFlow { switch (result.kind) { case 'accepted': - rememberScore({ id: result.score.id, score: result.score.score, at: result.score.completedAt, nickname: result.score.nickname }, this.deps.storage); + rememberScore({ id: result.score.id, score: result.score.score, at: result.score.completedAt, nickname: result.score.nickname, rulesVersion: result.score.rulesVersion }, this.deps.storage); if (prepared.nickname) rememberNickname(prepared.nickname, this.deps.storage); return this.set({ kind: 'accepted', score: result.score, ranks: result.ranks, replayed: result.replayed }); case 'rejected': diff --git a/phaser-asteroids/src/scenes/GameScene.ts b/phaser-asteroids/src/scenes/GameScene.ts index 2a4b4f9..758bd39 100644 --- a/phaser-asteroids/src/scenes/GameScene.ts +++ b/phaser-asteroids/src/scenes/GameScene.ts @@ -25,7 +25,7 @@ import { keySchemesFor, readPlayerInput, type KeyScheme } from '../input/keyboar import { readPlayerInputs } from '../input/playerInputs'; import { getApiBase, type RankedChallenge } from '../ranked/api'; import { ControlTracker } from '../ranked/controls'; -import { localBest, readLocalScores, startingNickname } from '../ranked/localScores'; +import { localBest, readLocalScores, startingNickname, type LocalScore } from '../ranked/localScores'; import { refreshPersonalBest, type PersonalBest } from '../ranked/personalBest'; import { ScoresModel } from '../ranked/scoresModel'; import { rankedSession } from '../ranked/session'; @@ -161,7 +161,7 @@ export class GameScene extends Phaser.Scene { private scoresModel!: ScoresModel; private personalBest: PersonalBest | null = null; /** The best verified score before this run, fixed when the run ends (for the "new personal best" line). */ - private priorBest: number | null = null; + private priorBest: LocalScore | null = null; private resultOpenedAt = 0; private rankedLabel: Phaser.GameObjects.Text | null = null; private rankedClock: Phaser.GameObjects.Text | null = null; @@ -474,6 +474,7 @@ export class GameScene extends Phaser.Scene { const flow = this.rankedFlow as SubmissionFlow; const input = this.nicknameInput as NicknameInput; const challenge = this.rankedChallenge as RankedChallenge; + const bestBeforeRun = () => this.priorBest; return { inputMode: getInputMode(this), flow, @@ -481,7 +482,8 @@ export class GameScene extends Phaser.Scene { runScore: this.sim.totalScore, endReason: this.timeUp ? 'time_limit' : 'game_over', timeLimitLabel: formatClock(challenge.timeLimitTicks / FIXED_TICK_RATE), - priorBest: this.priorBest, + priorBest: this.priorBest?.score ?? null, + get priorBestRulesVersion() { return bestBeforeRun()?.rulesVersion; }, actions: { playAgain: () => this.playAgain(), toMenu: () => this.toMenu(), @@ -493,6 +495,9 @@ export class GameScene extends Phaser.Scene { private refreshBest(): void { void refreshPersonalBest(getApiBase()).then((best) => { this.personalBest = best; + if (best && this.priorBest && best.best.id === this.priorBest.id) { + this.priorBest = { ...this.priorBest, rulesVersion: best.best.rulesVersion }; + } }); } @@ -513,7 +518,7 @@ export class GameScene extends Phaser.Scene { expired: () => this.rankedExpired || Date.now() >= this.rankedExpiresAt, }); rankedSession.attach(challenge.runId, this.rankedFlow); - this.priorBest = localBest()?.score ?? null; + this.priorBest = localBest(); this.refreshBest(); const search = typeof window !== 'undefined' ? window.location.search : ''; this.nicknameInput = new NicknameInput( diff --git a/phaser-asteroids/src/ui/menu/pages/ranked.ts b/phaser-asteroids/src/ui/menu/pages/ranked.ts index 79a4c54..3a4f41a 100644 --- a/phaser-asteroids/src/ui/menu/pages/ranked.ts +++ b/phaser-asteroids/src/ui/menu/pages/ranked.ts @@ -1,5 +1,5 @@ import type { PersonalBest } from '../../../ranked/personalBest'; -import { formatScore } from '../../../ranked/scoresModel'; +import { formatEraScore } from '../../../ranked/scoresModel'; import { COLORS } from '../../text'; import type { MenuContext, PageNav } from '../context'; import type { PageDef } from '../menuView'; @@ -102,7 +102,7 @@ export function buildRankedPage(kit: PageKit, ctx: RankedMenuContext, nav: PageN const best = ctx.best(); if (best) { const who = best.best.nickname ? ` (${best.best.nickname})` : ''; - const bestLabel = kit.text(CENTER_X, 318, `YOUR BEST VERIFIED SCORE: ${formatScore(best.best.score)}${who}`, { size: TEXT.body, originX: 0.5, originY: 0.5, color: COLORS.white }); + const bestLabel = kit.text(CENTER_X, 318, `YOUR BEST VERIFIED SCORE: ${formatEraScore(best.best.score, best.best.rulesVersion)}${who}`, { size: TEXT.body, originX: 0.5, originY: 0.5, color: COLORS.white }); if (bestLabel.width > 1120) bestLabel.setScale(1120 / bestLabel.width); } @@ -136,6 +136,6 @@ export function buildRankedPage(kit: PageKit, ctx: RankedMenuContext, nav: PageN if (connecting) ctx.actions.cancel(); return false; }, - signature: () => `${ctx.inputAvailable()}|${ctx.status().kind}|${ctx.best()?.best.id ?? ''}`, + signature: () => `${ctx.inputAvailable()}|${ctx.status().kind}|${ctx.best()?.best.id ?? ''}|${ctx.best()?.best.rulesVersion ?? ''}`, }; } diff --git a/phaser-asteroids/src/ui/menu/pages/rankedResult.ts b/phaser-asteroids/src/ui/menu/pages/rankedResult.ts index a0da749..fd02d13 100644 --- a/phaser-asteroids/src/ui/menu/pages/rankedResult.ts +++ b/phaser-asteroids/src/ui/menu/pages/rankedResult.ts @@ -1,5 +1,6 @@ import { NICKNAME_HELP, nicknameFeedback } from '../../../ranked/nickname'; -import { formatScore } from '../../../ranked/scoresModel'; +import { formatEraScore, formatScore } from '../../../ranked/scoresModel'; +import { scoringEraLabel } from '../../../ranked/scoringEras'; import type { SubmissionFlow } from '../../../ranked/submission'; import { COLORS } from '../../text'; import type { MenuContext, PageNav } from '../context'; @@ -26,6 +27,7 @@ export interface RankedResultContext { readonly timeLimitLabel: string; /** This device's best verified score from before this run (null: none yet), for the "new personal best" line. */ readonly priorBest: number | null; + readonly priorBestRulesVersion?: string; readonly actions: { /** Another ranked run: back to the title screen, which asks the server for a new challenge. */ playAgain(): void; @@ -89,7 +91,7 @@ export function buildRankedResultPage(kit: PageKit, ctx: RankedResultContext, _n const again: ButtonSpec = { id: 'play-again', label: 'PLAY AGAIN', onTap: actions.playAgain }; const menu: ButtonSpec = { id: 'menu', label: 'MAIN MENU', onTap: actions.toMenu }; const scores: ButtonSpec = { id: 'scores', label: 'HIGH SCORES', onTap: actions.openScores }; - const signature = (): string => `${flow.version}|${ctx.inputMode.isTouch}`; + const signature = (): string => `${flow.version}|${ctx.inputMode.isTouch}|${ctx.priorBestRulesVersion ?? ''}`; // The name field exists only while it can be edited; every other state hides it (and with it the phone keyboard). if (state.kind !== 'ready') ctx.input.hide(); @@ -145,7 +147,8 @@ export function buildRankedResultPage(kit: PageKit, ctx: RankedResultContext, _n case 'accepted': { const { score, ranks, replayed } = state; heading(kit, 'SCORE VERIFIED!', GOOD, 52); - kit.text(CENTER_X, 132, formatScore(score.score), { size: 80, originX: 0.5, originY: 0.5 }); + const verifiedScore = kit.text(CENTER_X, 132, formatScore(score.score), { size: 80, originX: 0.5, originY: 0.5 }); + kit.text(CENTER_X + verifiedScore.width / 2 + 16, 132, scoringEraLabel(score.rulesVersion), { size: TEXT.hint, originX: 0, originY: 0.5, color: COLORS.dim }); const name = kit.text(CENTER_X, 200, score.nickname, { size: 34, originX: 0.5, originY: 0.5, color: COLORS.player1 }).setPadding(0, 0, 0, 8); if (name.width > 700) name.setScale(700 / name.width); const rankLines: string[] = []; @@ -158,7 +161,7 @@ export function buildRankedResultPage(kit: PageKit, ctx: RankedResultContext, _n if (rankLines[1]) kit.text(CENTER_X, 306, rankLines[1], { size: 28, originX: 0.5, originY: 0.5, color: COLORS.hint }); } const best = ctx.priorBest === null || score.score > ctx.priorBest; - kit.text(CENTER_X, 350, best ? 'NEW PERSONAL BEST!' : `YOUR BEST: ${formatScore(ctx.priorBest ?? 0)}`, { size: TEXT.small + 2, originX: 0.5, originY: 0.5, color: best ? GOOD : COLORS.hint }); + kit.text(CENTER_X, 350, best ? 'NEW PERSONAL BEST!' : `YOUR BEST: ${formatEraScore(ctx.priorBest ?? 0, ctx.priorBestRulesVersion)}`, { size: TEXT.small + 2, originX: 0.5, originY: 0.5, color: best ? GOOD : COLORS.hint }); const note = replayed ? 'THIS SCORE WAS ALREADY RECORDED.' : score.endReason === 'time_limit' || timed ? `YOU SURVIVED THE FULL ${ctx.timeLimitLabel}!` : ''; if (note) kit.text(CENTER_X, 384, note, { size: TEXT.hint + 2, originX: 0.5, originY: 0.5, color: COLORS.dim }); buttonGrid(kit, 420, [{ ...scores, label: 'VIEW HIGH SCORES', primary: true }, again, menu]); diff --git a/phaser-asteroids/src/ui/menu/pages/scores.ts b/phaser-asteroids/src/ui/menu/pages/scores.ts index 2a27661..4122716 100644 --- a/phaser-asteroids/src/ui/menu/pages/scores.ts +++ b/phaser-asteroids/src/ui/menu/pages/scores.ts @@ -1,5 +1,6 @@ import type { PersonalBest } from '../../../ranked/personalBest'; -import { formatScore, weekLabel, BOARD_PAGE_SIZE, type ScoresModel } from '../../../ranked/scoresModel'; +import { formatEraScore, formatScore, weekLabel, BOARD_PAGE_SIZE, type ScoresModel } from '../../../ranked/scoresModel'; +import { scoringEra } from '../../../ranked/scoringEras'; import { COLORS } from '../../text'; import type { MenuContext, PageNav } from '../context'; import type { PageDef } from '../menuView'; @@ -21,7 +22,8 @@ const RANK_X = 236; const NAME_X = 276; const NAME_MAX_W = 470; const SCORE_X = 1010; -const TAG_X = 1046; +const ERA_X = 1032; +const TAG_X = 1090; const FOOT_Y = 548; const NAV_Y = 596; const NAV_W = 280; @@ -50,7 +52,7 @@ export function buildScoresPage(kit: PageKit, ctx: ScoresContext, nav: PageNav): }); const week = model.scope === 'weekly' && model.page ? weekLabel(model.page) : null; - const caption = model.scope === 'weekly' ? (week ? `WEEK OF ${week} (ATLANTIC TIME)` : 'THIS WEEK') : 'BEST VERIFIED SCORES OF ALL TIME'; + const caption = model.scope === 'weekly' ? (week ? `WEEK OF ${week} (ATLANTIC TIME)` : 'THIS WEEK') : 'SCORES FROM DIFFERENT VERSIONS MAY NOT BE DIRECTLY COMPARABLE.'; kit.text(CENTER_X, 184, caption, { size: TEXT.hint, originX: 0.5, originY: 0.5, color: COLORS.dim, bold: false }); drawBody(kit, ctx); @@ -63,7 +65,7 @@ export function buildScoresPage(kit: PageKit, ctx: ScoresContext, nav: PageNav): const best = ctx.best(); if (best) { const who = best.best.nickname ? ` (${best.best.nickname})` : ''; - const bestLabel = kit.text(CENTER_X, FOOT_Y + 28, `YOUR BEST VERIFIED SCORE: ${formatScore(best.best.score)}${who}`, { size: TEXT.hint + 2, originX: 0.5, originY: 0.5, color: COLORS.heading }); + const bestLabel = kit.text(CENTER_X, FOOT_Y + 28, `YOUR BEST VERIFIED SCORE: ${formatEraScore(best.best.score, best.best.rulesVersion)}${who}`, { size: TEXT.hint + 2, originX: 0.5, originY: 0.5, color: COLORS.heading }); if (bestLabel.width > 1120) bestLabel.setScale(1120 / bestLabel.width); } @@ -80,7 +82,7 @@ export function buildScoresPage(kit: PageKit, ctx: ScoresContext, nav: PageNav): keyHint(kit, ctx, 'LEFT / RIGHT: THIS WEEK / ALL TIME UP / DOWN: CHOOSE ESC: BACK'); return { defaultFocus: 'back', - signature: () => `${model.version}|${touch}|${ctx.highlightIds().size}|${ctx.best()?.best.id ?? ''}`, + signature: () => `${model.version}|${touch}|${ctx.highlightIds().size}|${ctx.best()?.best.id ?? ''}|${ctx.best()?.best.rulesVersion ?? ''}`, }; } @@ -111,13 +113,14 @@ function drawBody(kit: PageKit, ctx: ScoresContext): void { const isMine = mine.has(entry.id); if (isMine) { g.fillStyle(PALETTE.gold, 0.16); - g.fillRect(RANK_X - 70, y - ROW_STEP / 2 + 2, SCORE_X - RANK_X + 190, ROW_STEP - 4); + g.fillRect(RANK_X - 70, y - ROW_STEP / 2 + 2, SCORE_X - RANK_X + 220, ROW_STEP - 4); } const color = isMine ? COLORS.heading : entry.rank <= 3 ? COLORS.white : COLORS.hint; kit.text(RANK_X, y, `#${entry.rank}`, { size: TEXT.body, originX: 1, originY: 0.5, color }); const name = kit.text(NAME_X, y, entry.nickname, { size: TEXT.body, originX: 0, originY: 0.5, color }).setPadding(0, 0, 0, 6); // room for an underscore's tail if (name.width > NAME_MAX_W) name.setScale(NAME_MAX_W / name.width); kit.text(SCORE_X, y, formatScore(entry.score), { size: TEXT.body, originX: 1, originY: 0.5, color }); + kit.text(ERA_X, y, scoringEra(entry.rulesVersion) ?? '?', { size: TEXT.hint, originX: 0, originY: 0.5, color: COLORS.dim }); if (isMine) kit.text(TAG_X, y, 'YOU', { size: TEXT.hint, originX: 0, originY: 0.5, color: COLORS.heading }); }); } diff --git a/phaser-asteroids/tests/ranked.test.ts b/phaser-asteroids/tests/ranked.test.ts index 2846fb4..d4a8899 100644 --- a/phaser-asteroids/tests/ranked.test.ts +++ b/phaser-asteroids/tests/ranked.test.ts @@ -20,7 +20,8 @@ import { ControlTracker } from '../src/ranked/controls'; import { forgetScore, lastNickname, localBest, readLocalScores, rememberNickname, rememberScore, startingNickname, type StorageLike } from '../src/ranked/localScores'; import { NICKNAME_HELP, nicknameFeedback, sanitizeNickname } from '../src/ranked/nickname'; import { refreshPersonalBest } from '../src/ranked/personalBest'; -import { BOARD_PAGE_SIZE, formatScore, ScoresModel, weekLabel } from '../src/ranked/scoresModel'; +import { BOARD_PAGE_SIZE, formatEraScore, formatScore, ScoresModel, weekLabel } from '../src/ranked/scoresModel'; +import { rulesInScoringEra, scoringEra, scoringEraLabel } from '../src/ranked/scoringEras'; import { rankedSession } from '../src/ranked/session'; import { SubmissionFlow } from '../src/ranked/submission'; import type { ReplayRecord } from '../src/replay'; @@ -42,7 +43,7 @@ const reply = (status: number, body: unknown) => new Response(JSON.stringify(bod const acceptedBody = { status: 'accepted', replayed: false, - score: { id: 's1', nickname: 'Ace', score: 1250, completedAt: '2026-10-22T15:01:00.000Z', durationSeconds: 25, endReason: 'game_over' }, + score: { id: 's1', nickname: 'Ace', score: 1250, rulesVersion: '1.1.0', completedAt: '2026-10-22T15:01:00.000Z', durationSeconds: 25, endReason: 'game_over' }, ranks: { allTime: 3, weekly: 1 }, }; const ok = (body: unknown = acceptedBody): HttpResponse => ({ status: 200, body }); @@ -217,7 +218,7 @@ describe('SubmissionFlow', () => { await done; expect(states).toEqual(['uploading', 'verifying']); expect(made.flow.state).toMatchObject({ kind: 'accepted', score: { score: 1250 }, ranks: { weekly: 1 } }); - expect(readLocalScores(storage)).toEqual([{ id: 's1', score: 1250, at: '2026-10-22T15:01:00.000Z', nickname: 'Ace' }]); + expect(readLocalScores(storage)).toEqual([{ id: 's1', score: 1250, at: '2026-10-22T15:01:00.000Z', nickname: 'Ace', rulesVersion: '1.1.0' }]); expect(lastNickname(storage)).toBe('Ace'); }); @@ -372,6 +373,18 @@ describe('rankedSession', () => { }); describe('local score memory and personal best', () => { + it('keeps a historical personal best and upgrades legacy cache metadata from the server', async () => { + const s = memory(); + rememberScore({ id: 'v1', score: 5000, at: 'old', nickname: 'Old Champ' }, s); + rememberScore({ id: 'v2', score: 800, at: 'new', nickname: 'Ace', rulesVersion: '1.1.0' }, s); + const detail = { score: { id: 'v1', rank: 2, nickname: 'Old Champ', score: 5000, completedAt: '', durationSeconds: 60, rulesVersion: '1.0.0' }, ranks: { allTime: 2, weekly: null } }; + const best = await refreshPersonalBest('http://x', s, async () => detail); + expect(best).toMatchObject({ best: { id: 'v1', score: 5000, rulesVersion: '1.0.0' }, ranks: { allTime: 2, weekly: null } }); + expect(formatEraScore(best!.best.score, best!.best.rulesVersion)).toBe('5,000 V1'); + expect(localBest(s)?.rulesVersion).toBe('1.0.0'); + expect(readLocalScores(s)).toHaveLength(2); + expect(await refreshPersonalBest(null, s)).toMatchObject({ best: { id: 'v1', rulesVersion: '1.0.0' }, ranks: null }); + }); it('keeps this device\'s best server-confirmed scores and survives corrupt or blocked storage', () => { const s = memory(); rememberScore({ id: 'a', score: 100, at: 'x', nickname: 'One' }, s); @@ -414,7 +427,7 @@ describe('local score memory and personal best', () => { }); describe('leaderboard client and ScoresModel', () => { - const entry = (rank: number) => ({ id: `id${rank}`, rank, nickname: `Pilot ${rank}`, score: 1000 - rank, completedAt: '2026-10-22T15:00:00.000Z', durationSeconds: 60, endReason: 'game_over' }); + const entry = (rank: number) => ({ id: `id${rank}`, rank, nickname: `Pilot ${rank}`, score: 1000 - rank, rulesVersion: '1.1.0', completedAt: '2026-10-22T15:00:00.000Z', durationSeconds: 60, endReason: 'game_over' }); const page = (over: Record = {}) => ({ scope: 'weekly', rulesVersion: '1.1.0', limit: 10, offset: 0, total: 25, timeZone: 'America/Halifax', weekStart: '2026-10-19T03:00:00.000Z', weekEnd: '2026-10-26T03:00:00.000Z', entries: [1, 2, 3].map(entry), ...over }); it('asks for one screen at a time and parses the answer', async () => { @@ -422,7 +435,30 @@ describe('leaderboard client and ScoresModel', () => { const p = await fetchLeaderboard('http://x', 'weekly', { limit: 10, offset: 20 }, async (u) => ((url = u), reply(200, page({ offset: 20 })))); expect(url).toBe('http://x/api/v1/leaderboard/weekly?limit=10&offset=20'); expect(p).toMatchObject({ total: 25, offset: 20, timeZone: 'America/Halifax' }); - expect(p.entries[0]).toMatchObject({ rank: 1, nickname: 'Pilot 1' }); + expect(p.entries[0]).toMatchObject({ rank: 1, nickname: 'Pilot 1', rulesVersion: '1.1.0' }); + }); + it('preserves each stored rules version in mixed pages, score details and accepted submissions', async () => { + const historical = { ...entry(1), rulesVersion: '1.0.0' }; + const future = { ...entry(3), rulesVersion: '9.0.0' }; + const p = await fetchLeaderboard('http://x', 'all-time', { limit: 10, offset: 0 }, async () => reply(200, page({ entries: [historical, entry(2), future] }))); + expect(p.entries.map((e) => scoringEraLabel(e.rulesVersion))).toEqual(['V1', 'V2', 'VERSION UNKNOWN']); + const detail = await fetchScoreDetail('http://x', historical.id, async () => reply(200, { score: historical, ranks: { allTime: 1, weekly: null } })); + expect(detail?.score.rulesVersion).toBe('1.0.0'); + const accepted = classifySubmitResponse(ok()); + expect(accepted).toMatchObject({ kind: 'accepted', score: { rulesVersion: '1.1.0' } }); + const s = memory(); + const flow = new SubmissionFlow({ base: 'http://x', challenge, replay, controls: 'keyboard', storage: s, send: { transport: scripted([ok()]), ...noWait } }); + await flow.submit('Ace'); + expect(localBest(s)?.rulesVersion).toBe('1.1.0'); + }); + + it('uses explicit scoring eras without guessing from unknown or missing technical versions', () => { + expect(scoringEra('1.0.0')).toBe('V1'); + expect(scoringEra('1.1.0')).toBe('V2'); + expect(rulesInScoringEra('1.1.0')).toEqual(['1.1.0']); + for (const version of ['1.1.1', '2.0.0', 'constructor', undefined]) expect(scoringEra(version)).toBeNull(); + expect(rulesInScoringEra('9.0.0')).toEqual([]); + expect(formatEraScore(900, undefined)).toBe('900 VERSION UNKNOWN'); }); it('errors are typed, never a half-parsed page', async () => { await expect(fetchLeaderboard('http://x', 'weekly', { limit: 10, offset: 0 }, async () => Promise.reject(new Error('x')))).rejects.toMatchObject({ code: 'network' });