From ccce3cecefe9223a723f99386036e459b3ae7dd1 Mon Sep 17 00:00:00 2001 From: djblackett <49618491+djblackett@users.noreply.github.com> Date: Fri, 23 Oct 2026 21:51:00 -0300 Subject: [PATCH 1/2] feat: implement Chain Lightning power-up and associated mechanics - Updated gameplay rules version to 1.2.0 in volatileExplosion tests. - Added documentation for Experiment C: Chain Lightning, detailing playtest instructions and rules. - Introduced new audio asset for lightning sound effects and a script to generate it. - Created lightningTrial module for dynamic import in development, allowing for isolated testing of Chain Lightning mechanics. - Added comprehensive tests for Chain Lightning power-up, covering collection, interaction with other power-ups, respawn behavior, and chaining mechanics. --- .../docs/gameplay-experiment-c.md | 80 ++++++ .../public/audio/sfx/lightning.wav | Bin 0 -> 4894 bytes .../scripts/generate-lightning-sfx.py | 26 ++ .../scripts/historical-leaderboard.mjs | 16 +- phaser-asteroids/scripts/ranked-ui.mjs | 4 +- phaser-asteroids/server/tests/harness.ts | 6 +- .../server/tests/leaderboard.test.ts | 24 +- .../server/tests/lifecycle.test.ts | 20 +- phaser-asteroids/src/audio/audioConfig.ts | 7 +- phaser-asteroids/src/audio/sfxPlayer.ts | 6 + phaser-asteroids/src/core/constants.ts | 5 + phaser-asteroids/src/core/game.ts | 50 +++- phaser-asteroids/src/core/player.ts | 15 +- phaser-asteroids/src/core/powerup.ts | 10 +- phaser-asteroids/src/core/shot.ts | 5 +- phaser-asteroids/src/dev/lightningTrial.ts | 57 ++++ phaser-asteroids/src/ranked/env.d.ts | 1 + phaser-asteroids/src/ranked/scoringEras.ts | 3 +- phaser-asteroids/src/render/powerupIcons.ts | 16 ++ phaser-asteroids/src/render/worldRenderer.ts | 45 ++- phaser-asteroids/src/replay/constants.ts | 2 +- phaser-asteroids/src/replay/snapshot.ts | 6 + phaser-asteroids/src/scenes/GameScene.ts | 7 + phaser-asteroids/src/ui/hud.ts | 4 +- phaser-asteroids/src/ui/menu/pages/title.ts | 4 +- phaser-asteroids/src/ui/menu/powerupInfo.ts | 17 +- phaser-asteroids/tests/audioMix.test.ts | 1 + phaser-asteroids/tests/chainLightning.test.ts | 268 ++++++++++++++++++ phaser-asteroids/tests/menuContent.test.ts | 10 +- phaser-asteroids/tests/powerup.test.ts | 10 +- phaser-asteroids/tests/ranked.test.ts | 28 +- .../tests/volatileExplosion.test.ts | 4 +- 32 files changed, 685 insertions(+), 72 deletions(-) create mode 100644 phaser-asteroids/docs/gameplay-experiment-c.md create mode 100644 phaser-asteroids/public/audio/sfx/lightning.wav create mode 100644 phaser-asteroids/scripts/generate-lightning-sfx.py create mode 100644 phaser-asteroids/src/dev/lightningTrial.ts create mode 100644 phaser-asteroids/tests/chainLightning.test.ts diff --git a/phaser-asteroids/docs/gameplay-experiment-c.md b/phaser-asteroids/docs/gameplay-experiment-c.md new file mode 100644 index 0000000..d3fa5f0 --- /dev/null +++ b/phaser-asteroids/docs/gameplay-experiment-c.md @@ -0,0 +1,80 @@ +# Experiment C: Chain Lightning (local, awaiting playtest) + +Implemented locally. Do not commit, push, merge or deploy until Dave has playtested and approved it. + +## Playtest + +From `phaser-asteroids`, run `npm run dev`, then open: + + + +On desktop choose **PLAY** (Space). On mobile choose **PRACTICE** (then **START PRACTICE** if shown). +The trial is deliberately unavailable in ranked and `?verified` / `?seed` recordings. + +The ship starts facing a fixed row of standard, armoured and volatile rocks. A real Lightning pickup +is collected immediately. Hold the normal fire control: the first bullet kills the first rock, +strips one armour hit, then jumps to a volatile rock whose explosion propagates normally. +Tap **RESET LIGHTNING TRIAL** to restore the layout and collect a fresh 7-second pickup. +Select two players on the desktop title screen to get a separate row and pickup for each ship. +Reset clears other power-ups; collect natural drops during regular play to try combined effects. + +The reset button and fixture module are dynamically imported only in Vite development, only in +casual play. The production build contains neither the helper import nor its reset UI. +Remove the query parameter and start a new game for ordinary play with random drops. +For a phone, the existing `npm run dev:lan` workflow also accepts `?lightningtrial=1` on its local game URL. + +## Rules and presentation + +- `CHAIN_LIGHTNING_DURATION = 7`, `CHAIN_LIGHTNING_MAX_TARGETS = 2` additional targets, + `CHAIN_LIGHTNING_RANGE = 160` in `src/core/constants.ts`. +- The existing ordinary 12% roll now chooses uniformly among five types. Mega retains its separate + first 1.5% roll: the unconditional ordinary chance remains 0.985 × 12% = 11.82%, + about 2.364% per ordinary type. Revive keeps its existing co-op replacement policy. +- Collection refreshes the collector's timer. Charge is captured separately on every bullet at firing + time, including Multi-Shot bullets. Rapid Fire keeps its normal cadence. Mega neither grants Lightning + nor pauses its timer; independently collected Lightning can coexist with Mega. +- Each jump uses centre-to-centre squared distance, includes the exact 160px boundary, and does not wrap. + Equal distances keep asteroid-list order. Dead, dying and previously lightning-struck rocks are ineligible. + A surviving armoured initial hit can start a chain. The consumed bullet can start only one chain. +- Every hit uses the existing asteroid-hit path: one armour HP, or a normal kill with the existing combo, + scoring and drop roll. All credit goes to the original bullet owner, including volatile blast kills. + Blasts resolve synchronously before the next target is chosen, so blast-killed rocks cannot be paid again. + Surviving armour can still take normal damage from distinct volatile blasts, as in Experiment B. +- Lightning never targets ships, UFOs, pickups or lasers. Original bullet collisions, including friendly + fire and UFO damage, retain their existing rules. No chains originate from blast kills or laser hits. +- Cyan bolt pickup, cyan bullet halo/trail with the owner-coloured core retained in co-op, jagged blue-white + links, six small procedural sparks per impact, and a 160ms glow/fade. A cyan `LIGHTNING: Ns` countdown + uses the existing per-player ability HUD, including when Mega is active. +- The original 110ms synthesized zap uses the existing audio asset/mix infrastructure, SFX volume and + mute controls. At most one electrical voice plays at once, with a 90ms minimum start interval. + Regenerate its small WAV with `python scripts/generate-lightning-sfx.py`. +- Decoration is capped at 24 simultaneous chains. Neither procedural rendering nor the audio RNG + consumes simulation RNG. Dropping presentation state cannot change damage, drops or replay outcomes. + +## Validation and remaining judgement + +518 focused tests passed across 16 files: Lightning, power-ups, armour/volatile interactions, co-op +combat, players, lasers, audio, menu text, replay determinism/validation, ranked clients and server +lifecycle/leaderboards/time limits. Frontend/server TypeScript checks and the production build passed. +The trial page, module and audio asset returned HTTP 200; the production bundle excludes the helper. + +The genuine existing seed-54321 reference game naturally collects and discharges Lightning. Its entire +event sequence, including destruction order, is identical when replayed by the authoritative ranked +verifier, with score **34735** under `1.2.0` (Experiment B's reference was 13959 under `1.1.0`). +This one changed trajectory is a regression fixture, not a balance estimate. + +No browser was available through this session's UI tools, so the visual, audible and subjective gameplay +playtest remains for Dave. No full browser suites or extended automated playthroughs were run. +Watch the strength of Rapid Fire + Multi-Shot + Lightning, volatile chain density, whether 160px produces +enough visible jumps in early play, and cyan readability beside Shield/on phones. + +## Version and release boundary + +The local client and authoritative server share rules **1.2.0**; replay schema remains **1**. +The explicit scoring map preserves **1.0.0 → V1**, **1.1.0 → V2**, and adds **1.2.0 → V3**. +ALL TIME includes all supported eras with stored labels, THIS WEEK uses the current era, and historical +personal bests remain available. No migration or rewriting of stored historical scores is required. +Verification remains strict for current rules; historical leaderboard support does not grant replay compatibility. + +After approval, coordinate client/server rules cutover and allow active old-rules runs to drain first. +The experimental client will reject a production V2 challenge. Nothing has been deployed by this work. diff --git a/phaser-asteroids/public/audio/sfx/lightning.wav b/phaser-asteroids/public/audio/sfx/lightning.wav new file mode 100644 index 0000000000000000000000000000000000000000..b9144a9811e179a20df0ee59f001fe1e26088e43 GIT binary patch literal 4894 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 AxBvhE literal 0 HcmV?d00001 diff --git a/phaser-asteroids/scripts/generate-lightning-sfx.py b/phaser-asteroids/scripts/generate-lightning-sfx.py new file mode 100644 index 0000000..4fbe01e --- /dev/null +++ b/phaser-asteroids/scripts/generate-lightning-sfx.py @@ -0,0 +1,26 @@ +"""Regenerate the original, procedural 110 ms electrical zap; no external audio source needed.""" +import math +import random +import struct +import wave +from pathlib import Path + +rate = 22050 +rng = random.Random(724) +phase = 0.0 +samples = [] +for i in range(int(rate * 0.11)): + t = i / rate + u = t / 0.11 + phase += 2 * math.pi * (2600 * (1 - u) ** 2 + 260) / rate + envelope = min(1, t / 0.003) * (1 - u) ** 2 + crackle = rng.uniform(-1, 1) * (0.22 + 0.12 * math.sin(t * 720)) + value = envelope * (0.52 * math.sin(phase) + 0.17 * math.sin(phase * 2.07) + crackle) + samples.append(struct.pack(' [e.id, e.rank, e.rulesVersion]), [[id(2), 1, '1.1.0'], [id(0), 2, '1.0.0'], [id(1), 3, '1.1.0']]); + assert.deepEqual(board.entries.map((e) => [e.id, e.rank, e.rulesVersion]), [[id(2), 1, '1.2.0'], [id(0), 2, '1.0.0'], [id(1), 3, '1.2.0']]); const weekly = await api('/leaderboard/weekly'); assert.equal(weekly.total, 1); assert.equal(weekly.entries[0].id, id(1)); @@ -73,10 +73,10 @@ try { 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')); + assert.ok(!texts.includes('Old Champ_99!') && texts.includes('V3')); await allTime(page); texts = await sceneTexts(page, 'StartScene'); - assert.ok(texts.includes(caption) && texts.includes('V1') && texts.includes('V2') && texts.includes('YOU')); + assert.ok(texts.includes(caption) && texts.includes('V1') && texts.includes('V3') && 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 }); @@ -100,13 +100,13 @@ try { 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!')); + assert.ok(texts.includes('V3') && 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.equal(accepted.score.rulesVersion, '1.2.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'); + console.log('PASS verified V3 submission: result labels, historical personal best and consistent server ranks'); await context.close(); } finally { await game?.close(); diff --git a/phaser-asteroids/scripts/ranked-ui.mjs b/phaser-asteroids/scripts/ranked-ui.mjs index 9ae250b..9864b83 100644 --- a/phaser-asteroids/scripts/ranked-ui.mjs +++ b/phaser-asteroids/scripts/ranked-ui.mjs @@ -114,8 +114,8 @@ try { .map((r, i) => { const id = `00000000-0000-4000-8000-${String(i + 1).padStart(12, '0')}`; const run = `00000000-0000-4000-9000-${String(i + 1).padStart(12, '0')}`; - 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, '1.1.0', '{}', ${r.at - 60000}, ${r.at + 3600000}, 'accepted', ${r.at}, '${id}'); -INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ticks, duration_ms) VALUES ('${id}', '${run}', ${r.score}, '${r.nick}', ${r.at}, '1.1.0', 3600, 60000);`; + 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, '1.2.0', '{}', ${r.at - 60000}, ${r.at + 3600000}, 'accepted', ${r.at}, '${id}'); +INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ticks, duration_ms) VALUES ('${id}', '${run}', ${r.score}, '${r.nick}', ${r.at}, '1.2.0', 3600, 60000);`; }) .join('\n'); check('seeded 24 verified scores (20 this week, 4 from last week) straight into D1', B.exec(sql)); diff --git a/phaser-asteroids/server/tests/harness.ts b/phaser-asteroids/server/tests/harness.ts index 646901d..4c32ce3 100644 --- a/phaser-asteroids/server/tests/harness.ts +++ b/phaser-asteroids/server/tests/harness.ts @@ -34,7 +34,7 @@ export function botRun(seed: number, opts: Omit = {}): BotRu return structuredClone(run); } -/** Genuine reference game; combined experiments A+B under rules 1.1.0 produce 13959 points for this seed. */ +/** Genuine reference game; experiments A+B+C under rules 1.2.0 produce 34735 points for this seed. */ export const REFERENCE_SEED = 54321; export interface Harness { @@ -148,12 +148,12 @@ export async function insertScore( { sql: `INSERT INTO runs (id, token_hash, seed, rules_version, config_json, created_at, expires_at, status, finished_at, score_id) VALUES (?, 'x', 1, ?, '{}', ?, ?, 'accepted', ?, ?)`, - params: [runId, s.rules ?? '1.1.0', s.completedAt - 60_000, s.completedAt + 3_600_000, s.completedAt, id], + params: [runId, s.rules ?? '1.2.0', s.completedAt - 60_000, s.completedAt + 3_600_000, s.completedAt, id], }, { sql: `INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ticks, duration_ms, visibility) VALUES (?, ?, ?, ?, ?, ?, 3600, 60000, ?)`, - params: [id, runId, s.score, s.nickname ?? 'Tester', s.completedAt, s.rules ?? '1.1.0', s.visibility ?? 'visible'], + params: [id, runId, s.score, s.nickname ?? 'Tester', s.completedAt, s.rules ?? '1.2.0', s.visibility ?? 'visible'], }, ]); return id; diff --git a/phaser-asteroids/server/tests/leaderboard.test.ts b/phaser-asteroids/server/tests/leaderboard.test.ts index 060b3f2..e8c7dee 100644 --- a/phaser-asteroids/server/tests/leaderboard.test.ts +++ b/phaser-asteroids/server/tests/leaderboard.test.ts @@ -18,7 +18,7 @@ describe('leaderboard ordering', () => { 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']); + expect(res.body.entries.map((e: { rulesVersion: string }) => e.rulesVersion)).toEqual(['1.2.0', '1.0.0', '1.2.0', '1.0.0', '1.2.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 } }); }); @@ -59,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, rules: i % 2 ? '1.0.0' : '1.1.0' }); + for (let i = 1; i <= 25; i++) await insertScore(h.db, { score: i * 10, completedAt: T0, rules: i % 2 ? '1.0.0' : '1.2.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); @@ -81,6 +81,16 @@ describe('pagination is bounded', () => { }); describe('weekly leaderboard', () => { + it('keeps V1 and V2 on ALL TIME and in personal history while THIS WEEK uses V3', async () => { + const h = makeHarness(); + await insertScore(h.db, { id: 'v1-history', score: 900, completedAt: T0, rules: '1.0.0' }); + await insertScore(h.db, { id: 'v2-history', score: 800, completedAt: T0, rules: '1.1.0' }); + await insertScore(h.db, { id: 'v3-current', score: 700, completedAt: T0, rules: '1.2.0' }); + const all = await h.call('GET', '/api/v1/leaderboard/all-time'); + expect(all.body.entries.map((e: { rulesVersion: string }) => e.rulesVersion)).toEqual(['1.0.0', '1.1.0', '1.2.0']); + expect((await h.call('GET', '/api/v1/leaderboard/weekly')).body.entries.map((e: Entry) => e.id)).toEqual(['v3-current']); + expect((await h.call('GET', '/api/v1/scores/v2-history')).body).toMatchObject({ score: { score: 800, rulesVersion: '1.1.0' }, ranks: { allTime: 2, weekly: null } }); + }); it('only counts scores completed inside the current Halifax week, using the server timestamp', async () => { const clock = makeClock(Date.UTC(2026, 9, 22, 15, 0, 0)); // Thursday const h = makeHarness({ clock }); @@ -110,16 +120,16 @@ 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 - HOUR, nickname: 'Old Champ', rules: '1.0.0' }); // all-time only, despite being this week + await insertScore(h.db, { score: 50000, 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); expect(res.body.ranks).toEqual({ allTime: 2, weekly: 1 }); 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'); + expect(detail.body.score.score).toBe(34735); + expect(res.body.score.rulesVersion).toBe('1.2.0'); + expect(detail.body.score.rulesVersion).toBe('1.2.0'); }); it('selects the weekly era from the active rules and excludes unmapped future rules safely', async () => { @@ -219,7 +229,7 @@ describe('routing hygiene', () => { it('health reports the supported rules version', async () => { const h = makeHarness(); const res = await h.call('GET', '/api/v1/health'); - expect(res.body).toMatchObject({ ok: true, rulesVersion: '1.1.0', schemaVersion: 1 }); + expect(res.body).toMatchObject({ ok: true, rulesVersion: '1.2.0', schemaVersion: 1 }); }); it('wrong methods and unknown paths get JSON errors', async () => { const h = makeHarness(); diff --git a/phaser-asteroids/server/tests/lifecycle.test.ts b/phaser-asteroids/server/tests/lifecycle.test.ts index dfdd6a1..14fc8fd 100644 --- a/phaser-asteroids/server/tests/lifecycle.test.ts +++ b/phaser-asteroids/server/tests/lifecycle.test.ts @@ -16,7 +16,7 @@ describe('starting a ranked run', () => { expect(run.runId).toMatch(/^[0-9a-f-]{36}$/); expect(run.token.length).toBeGreaterThanOrEqual(40); expect(Number.isInteger(run.seed) && run.seed >= 0 && run.seed <= 0xffffffff).toBe(true); - expect(run.rulesVersion).toBe('1.1.0'); + expect(run.rulesVersion).toBe('1.2.0'); expect(run.tickRate).toBe(60); expect(run.config).toEqual({ playerCount: 1, livesMode: 'independent', friendlyFire: false, speed: [1, 1] }); expect(Date.parse(run.expiresAt) - Date.parse(run.issuedAt)).toBe(h.settings.runTtlMs); @@ -40,7 +40,7 @@ describe('starting a ranked run', () => { expect(res.status).toBe(201); expect(res.body.seed).not.toBe(1); expect(res.body.config.playerCount).toBe(1); - expect(res.body.rulesVersion).toBe('1.1.0'); + expect(res.body.rulesVersion).toBe('1.2.0'); }); it('issues unique ids, tokens and (practically) unique seeds', async () => { @@ -63,17 +63,17 @@ describe('submitting a legitimate run', () => { expect(res.status).toBe(200); expect(res.body.status).toBe('accepted'); expect(res.body.replayed).toBe(false); - expect(res.body.score.score).toBe(13959); + expect(res.body.score.score).toBe(34735); expect(res.body.score.nickname).toBe('Dave J'); expect(res.body.ranks).toEqual({ allTime: 1, weekly: 1 }); const row = await h.db.first>('SELECT * FROM scores'); - expect(row).toMatchObject({ score: 13959, ticks: bot.ticks, reported_controls: 'keyboard', visibility: 'visible', rules_version: '1.1.0' }); + expect(row).toMatchObject({ score: 34735, ticks: bot.ticks, reported_controls: 'keyboard', visibility: 'visible', rules_version: '1.2.0' }); expect(await count(h.db, 'runs', "status = 'accepted'")).toBe(1); expect(await count(h.db, 'scores')).toBe(1); const board = await h.call('GET', '/api/v1/leaderboard/all-time'); - expect(board.body.entries.map((e: { score: number }) => e.score)).toEqual([13959]); + expect(board.body.entries.map((e: { score: number }) => e.score)).toEqual([34735]); }); it('ignores the score the client claims when it is not consistent, and never takes it as the score', async () => { @@ -84,7 +84,7 @@ describe('submitting a legitimate run', () => { delete (bot.replay as { claimedResult?: unknown }).claimedResult; const res = await h.playAndSubmit(run, bot.replay); expect(res.status).toBe(200); - expect(res.body.score.score).toBe(13959); + expect(res.body.score.score).toBe(34735); }); }); @@ -250,7 +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' }); + await insertScore(h.db, { score: 50000, 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' }); @@ -258,7 +258,7 @@ 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(again.body.score.rulesVersion).toBe('1.1.0'); + expect(again.body.score.rulesVersion).toBe('1.2.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); @@ -341,7 +341,7 @@ describe('one-use runs', () => { const run = await h.start({ seed: REFERENCE_SEED }); await h.playAndSubmit(run, reference().replay); await expect( - h.db.run(`INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ticks, duration_ms) VALUES ('dup', ?, 1, 'Dup Dup', 1, '1.1.0', 1, 1)`, [run.runId]), + h.db.run(`INSERT INTO scores (id, run_id, score, nickname, completed_at, rules_version, ticks, duration_ms) VALUES ('dup', ?, 1, 'Dup Dup', 1, '1.2.0', 1, 1)`, [run.runId]), ).rejects.toThrow(); }); }); @@ -388,7 +388,7 @@ describe('request size and encoding limits', () => { const run = await h.start({ seed: REFERENCE_SEED }); const res = await h.playAndSubmit(run, reference().replay, { gzip: true }); expect(res.status).toBe(200); - expect(res.body.score.score).toBe(13959); + expect(res.body.score.score).toBe(34735); }); it('truncated gzip and corrupt gzip -> 400, run not consumed', async () => { diff --git a/phaser-asteroids/src/audio/audioConfig.ts b/phaser-asteroids/src/audio/audioConfig.ts index 83ad9fb..434d319 100644 --- a/phaser-asteroids/src/audio/audioConfig.ts +++ b/phaser-asteroids/src/audio/audioConfig.ts @@ -15,6 +15,7 @@ export type SfxKey = | 'explosion_medium' | 'explosion_large' | 'laser' + | 'lightning' | 'boost' | 'player_death'; @@ -72,6 +73,7 @@ export const SFX_ASSETS: ReadonlyArray = [ ['explosion_medium', 'audio/sfx/explosion_medium.ogg'], ['explosion_large', 'audio/sfx/explosion_large.ogg'], ['laser', 'audio/sfx/laser.ogg'], + ['lightning', 'audio/sfx/lightning.wav'], ['boost', 'audio/sfx/boost-woosh.ogg'], ['player_death', 'audio/sfx/player-death.ogg'], ]; @@ -100,7 +102,7 @@ export const DEFAULT_SFX_VOLUME = 0.8; /** The pause-screen controls move a setting in steps of this size. */ export const VOLUME_STEP = 0.1; -export type SfxGroup = 'shoot' | 'explosion' | 'laser' | 'boost' | 'death'; +export type SfxGroup = 'shoot' | 'explosion' | 'laser' | 'lightning' | 'boost' | 'death'; export const SFX_GROUP: Readonly> = { shoot_low: 'shoot', @@ -110,6 +112,7 @@ export const SFX_GROUP: Readonly> = { explosion_medium: 'explosion', explosion_large: 'explosion', laser: 'laser', + lightning: 'lightning', boost: 'boost', player_death: 'death', }; @@ -143,6 +146,7 @@ export const SFX_GAIN: Readonly> = { explosion_medium: explosionGain('medium'), explosion_large: explosionGain('large'), laser: 0.5, + lightning: 0.4, boost: 0.6, player_death: 0.8, }; @@ -164,6 +168,7 @@ export const OVERLAP_FALLOFF: Readonly> = { shoot: 0.65, explosion: 0.65, laser: 0.7, + lightning: 0.65, boost: 1, death: 1, }; diff --git a/phaser-asteroids/src/audio/sfxPlayer.ts b/phaser-asteroids/src/audio/sfxPlayer.ts index 83b53c6..cb3fcce 100644 --- a/phaser-asteroids/src/audio/sfxPlayer.ts +++ b/phaser-asteroids/src/audio/sfxPlayer.ts @@ -51,6 +51,8 @@ export function cueForEvent(event: SimEvent, rng: Rng): SoundCue | null { case 'volatile_exploded': // A deeper boom even for small volatile rocks; rising pitch separates successive links in a chain. return { key: 'explosion_large', volume: SFX_GAIN.explosion_large, rate: 0.8 + Math.min(event.depth, 4) * 0.06 }; + case 'lightning_discharged': + return { key: 'lightning', volume: SFX_GAIN.lightning }; case 'ufo_destroyed': { const key = explosionKey(event.radius); return { key, volume: SFX_GAIN[key] * UFO_EXPLOSION_GAIN_SCALE }; @@ -98,6 +100,7 @@ export class SfxPlayer { private volume: number; private readonly onVolumeChanged: ((volume: number) => void) | undefined; private readonly clock: () => number; + private lastLightningAt = -Infinity; /** Total cues actually started (useful for tests and diagnostics). */ played = 0; @@ -176,6 +179,8 @@ export class SfxPlayer { if (this.volume <= 0) return; const group = SFX_GROUP[cue.key]; const now = this.clock(); + // Multi-Shot and dense chains share one short zap; no burst of overlapping electrical sounds. + if (cue.key === 'lightning' && (now - this.lastLightningAt < 0.09 || this.playingCount('lightning') > 0)) return; const voices = this.active.get(cue.key) ?? new Map(); this.active.set(cue.key, voices); if ( @@ -194,6 +199,7 @@ export class SfxPlayer { if (handle) voices.delete(handle); }, cue.rate); if (!handle) return; + if (cue.key === 'lightning') this.lastLightningAt = now; this.played++; if (!finished) voices.set(handle, now); } diff --git a/phaser-asteroids/src/core/constants.ts b/phaser-asteroids/src/core/constants.ts index 282ef6d..98c1d69 100644 --- a/phaser-asteroids/src/core/constants.ts +++ b/phaser-asteroids/src/core/constants.ts @@ -17,6 +17,11 @@ export const ASTEROID_SPAWN_RATE = 0.5; // seconds between spawn attempts export type AsteroidArchetype = 'standard' | 'armored' | 'volatile'; +// Experiment C: ordinary bullets carry this effect at firing time; Mega Power does not grant it. +export const CHAIN_LIGHTNING_DURATION = 7; +export const CHAIN_LIGHTNING_MAX_TARGETS = 2; // additional asteroids after the bullet's own hit +export const CHAIN_LIGHTNING_RANGE = 160; // centre-to-centre world pixels, no edge wrapping + export interface ArchetypeConfig { hitPoints: number; pointsMultiplier: number; diff --git a/phaser-asteroids/src/core/game.ts b/phaser-asteroids/src/core/game.ts index d3e61f0..dcd9b6b 100644 --- a/phaser-asteroids/src/core/game.ts +++ b/phaser-asteroids/src/core/game.ts @@ -3,6 +3,8 @@ import { BOUNDARY_PARTICLE_COUNT, BOUNDARY_SHAKE_AMOUNT, BOUNDARY_SPARK_INTERVAL, + CHAIN_LIGHTNING_MAX_TARGETS, + CHAIN_LIGHTNING_RANGE, DIFFICULTY_INCREASE_INTERVAL, DIFFICULTY_SPAWN_RATE_INCREMENT, DIFFICULTY_SPAWN_RATE_MIN, @@ -46,6 +48,7 @@ import { circlesOverlap, rotateVec, type Circle, type Vec2 } from './math'; import { emitBurst, ParticleSystem } from './particles'; import { activateMegaPower, + activateChainLightning, activateMultiShot, activateRapidFire, activateShield, @@ -111,6 +114,7 @@ export type SimEvent = */ | { type: 'asteroid_destroyed'; radius: number; points: number; combo?: number; multiplier?: number; player?: number; volatile?: boolean } | { type: 'volatile_exploded'; position: Vec2; radius: number; depth: number } + | { type: 'lightning_discharged'; player: number } | { type: 'asteroid_hit'; position: Vec2 } | { type: 'powerup_dropped'; powerType: PowerUpType } | { type: 'powerup_collected'; powerType: PowerUpType; player?: number } @@ -151,6 +155,14 @@ export interface VolatileFlash { export const VOLATILE_FLASH_DURATION = 0.32; export const VOLATILE_FLASH_LIMIT = 32; +/** Copied impact positions only: rendering and expiry never change gameplay or consume RNG. */ +export interface LightningFlash { + points: Vec2[]; + age: number; +} +export const LIGHTNING_FLASH_DURATION = 0.16; +export const LIGHTNING_FLASH_LIMIT = 24; + interface VolatileBlast { position: Vec2; scorer: PlayerState | null; @@ -198,6 +210,7 @@ export class GameSim { lasers: LaserBeam[] = []; pickupFlashes: PickupFlash[] = []; volatileFlashes: VolatileFlash[] = []; + lightningFlashes: LightningFlash[] = []; readonly particles = new ParticleSystem(); readonly starfield: Starfield; readonly spawner: SpawnerState = createSpawner(); @@ -587,8 +600,10 @@ export class GameSim { for (const asteroid of this.asteroids) { if (!asteroid.alive || asteroid.dying) continue; if (!circlesOverlap(shot, asteroid)) continue; - this.hitAsteroid(asteroid, this.playerByNumber(shot.owner)); shot.alive = false; + const owner = this.playerByNumber(shot.owner); + this.hitAsteroid(asteroid, owner); + if (shot.charged) this.chainLightning(asteroid, owner); break; } } @@ -703,6 +718,9 @@ export class GameSim { private applyPowerUp(type: PowerUpType, player: PlayerState): void { switch (type) { + case 'chain_lightning': + activateChainLightning(player); + break; case 'mega_power': activateMegaPower(player); // Python sets (not extends) Slow Motion to the mega duration. @@ -869,7 +887,37 @@ export class GameSim { } } + /** One chain per consumed bullet. Explosions resolve normally before choosing the next living target. */ + private chainLightning(source: Asteroid, scorer: PlayerState): void { + const visited = new Set([source]); + const points = [{ ...source.position }]; + let previous = source; + for (let jump = 0; jump < CHAIN_LIGHTNING_MAX_TARGETS; jump++) { + let nearest: Asteroid | null = null; + let bestDistance = Infinity; + for (const target of this.asteroids) { + if (!target.alive || target.dying || visited.has(target)) continue; + const distance = (target.position.x - previous.position.x) ** 2 + (target.position.y - previous.position.y) ** 2; + // Strict improvement retains asteroid-list order for ties; include the exact range boundary. + if (distance <= CHAIN_LIGHTNING_RANGE ** 2 && distance < bestDistance) { + nearest = target; + bestDistance = distance; + } + } + if (!nearest) break; + visited.add(nearest); + points.push({ ...nearest.position }); + this.hitAsteroid(nearest, scorer); + previous = nearest; + } + this.lightningFlashes.push({ points, age: 0 }); + if (this.lightningFlashes.length > LIGHTNING_FLASH_LIMIT) this.lightningFlashes.shift(); + this.events.push({ type: 'lightning_discharged', player: scorer.playerNumber }); + } + private updateVolatileFlashes(dt: number): void { + for (const flash of this.lightningFlashes) flash.age += dt; + this.lightningFlashes = this.lightningFlashes.filter((flash) => flash.age < LIGHTNING_FLASH_DURATION); for (const flash of this.volatileFlashes) flash.age += dt; this.volatileFlashes = this.volatileFlashes.filter((flash) => flash.age < VOLATILE_FLASH_DURATION); } diff --git a/phaser-asteroids/src/core/player.ts b/phaser-asteroids/src/core/player.ts index aff4f60..ab4dee8 100644 --- a/phaser-asteroids/src/core/player.ts +++ b/phaser-asteroids/src/core/player.ts @@ -1,5 +1,6 @@ import { ASSIST_TRAVEL_TURN_SPEED, + CHAIN_LIGHTNING_DURATION, BOOST_COOLDOWN, BOOST_DURATION, BOOST_SPEED_MULTIPLIER, @@ -95,6 +96,7 @@ export interface PlayerState { rapidFire: TimedEffect; multiShot: TimedEffect; + chainLightning: TimedEffect; /** While active, Rapid Fire and Multi-Shot are held on by it and their own timers are paused. */ megaPower: TimedEffect; /** Absorbs exactly one hit; has no duration. */ @@ -148,6 +150,7 @@ export function createPlayer(x: number, y: number, playerNumber = 1, speedMultip travelHeading: null, rapidFire: { active: false, timer: 0 }, multiShot: { active: false, timer: 0 }, + chainLightning: { active: false, timer: 0 }, megaPower: { active: false, timer: 0 }, shieldActive: false, boost: { active: false, timer: 0, cooldown: 0, keyHeld: false }, @@ -220,7 +223,7 @@ function tryShoot(p: PlayerState): Shot[] { if (p.boost.active) return []; // no shooting while boosting // Python spawns shots at the ship's centre, not its nose. const shots = shotAngleOffsets(p.multiShot.active).map((offset) => - createShot(p.position, p.rotation + offset, p.playerNumber), + createShot(p.position, p.rotation + offset, p.playerNumber, p.chainLightning.active), ); p.shootTimer = p.rapidFire.active ? RAPID_FIRE_COOLDOWN : p.shootCooldown; return shots; @@ -238,6 +241,10 @@ export function activateShield(p: PlayerState): void { p.shieldActive = true; } +export function activateChainLightning(p: PlayerState): void { + p.chainLightning = { active: true, timer: CHAIN_LIGHTNING_DURATION }; +} + /** MEGA POWER: Rapid Fire + Multi-Shot + Shield, all for the mega duration. (The caller adds Slow Motion.) */ export function activateMegaPower(p: PlayerState): void { p.megaPower = { active: true, timer: MEGA_POWER_DURATION }; @@ -318,6 +325,10 @@ export function updatePlayer(p: PlayerState, input: PlayerInput, dt: number): Pl p.multiShot.timer -= dt; if (p.multiShot.timer <= 0) p.multiShot.active = false; } + if (p.chainLightning.active) { + p.chainLightning.timer = Math.max(0, p.chainLightning.timer - dt); + if (p.chainLightning.timer <= 0) p.chainLightning.active = false; + } p.isMoving = false; @@ -408,6 +419,7 @@ export function respawnPlayer(p: PlayerState, x: number, y: number): void { p.rapidFire = { active: false, timer: 0 }; p.multiShot = { active: false, timer: 0 }; + p.chainLightning = { active: false, timer: 0 }; p.megaPower = { active: false, timer: 0 }; p.shieldActive = false; // Boost stops but its cooldown keeps running; laser charges are not refilled. @@ -429,6 +441,7 @@ export function eliminatePlayer(p: PlayerState): void { p.isMoving = false; p.rapidFire = { active: false, timer: 0 }; p.multiShot = { active: false, timer: 0 }; + p.chainLightning = { active: false, timer: 0 }; p.megaPower = { active: false, timer: 0 }; p.shieldActive = false; p.boost.active = false; diff --git a/phaser-asteroids/src/core/powerup.ts b/phaser-asteroids/src/core/powerup.ts index 03b5a25..ade23c2 100644 --- a/phaser-asteroids/src/core/powerup.ts +++ b/phaser-asteroids/src/core/powerup.ts @@ -12,13 +12,13 @@ import { import { getForwardVector, type Vec2 } from './math'; import { pick, uniform, type Rng } from './rng'; -export type PowerUpType = 'rapid_fire' | 'shield' | 'multi_shot' | 'slow_motion' | 'mega_power' | 'revive'; +export type PowerUpType = 'rapid_fire' | 'shield' | 'multi_shot' | 'slow_motion' | 'chain_lightning' | 'mega_power' | 'revive'; /** - * The four ordinary drops. MEGA POWER has its own, rarer roll. REVIVE never dropped in the Python game (its spawn chance + * The five ordinary drops. MEGA POWER has its own, rarer roll. REVIVE never dropped in the Python game (its spawn chance * constant is unused); here it replaces an ordinary drop only while a player is out of lives (see `chooseOrdinaryDrop`). */ -export const ORDINARY_POWERUPS: readonly PowerUpType[] = ['rapid_fire', 'shield', 'multi_shot', 'slow_motion']; +export const ORDINARY_POWERUPS: readonly PowerUpType[] = ['rapid_fire', 'shield', 'multi_shot', 'slow_motion', 'chain_lightning']; export interface PowerUp { position: Vec2; @@ -44,7 +44,7 @@ export function createPowerUp(x: number, y: number, type: PowerUpType, rng: Rng, /** * Drop roll for a destroyed asteroid (Python `maybe_spawn_powerup`): first a 1.5 % chance of MEGA POWER, - * otherwise a 12 % chance of one of the four ordinary power-ups, chosen uniformly (~13.3 % overall). + * otherwise a 12 % chance of one of the five ordinary power-ups, chosen uniformly (~13.3 % overall). */ export function maybeSpawnPowerUp(x: number, y: number, rng: Rng, reviveEligible = false): PowerUp | null { if (rng() < MEGA_POWER_SPAWN_CHANCE) return createPowerUp(x, y, 'mega_power', rng); @@ -53,7 +53,7 @@ export function maybeSpawnPowerUp(x: number, y: number, rng: Rng, reviveEligible } /** - * The type of an ordinary drop (an asteroid's ordinary roll, or the guaranteed UFO drop): one of the four ordinary + * The type of an ordinary drop (an asteroid's ordinary roll, or the guaranteed UFO drop): one of the five ordinary * power-ups, or, while a Revive is useful (`reviveEligible`), a Revive in `REVIVE_SPAWN_CHANCE` of the cases. Nothing * extra is drawn from `rng` when it is not eligible, so single-player games and two-player games with nobody down play * out exactly as before. diff --git a/phaser-asteroids/src/core/shot.ts b/phaser-asteroids/src/core/shot.ts index 30f4844..de1759b 100644 --- a/phaser-asteroids/src/core/shot.ts +++ b/phaser-asteroids/src/core/shot.ts @@ -7,17 +7,20 @@ export interface Shot { radius: number; /** Player number that fired the shot. UFO shots are a separate type (`UfoShot`) kept in their own list. */ owner: number; + /** Frozen at firing time. Absent on legacy/test projectiles means an ordinary bullet. */ + charged?: boolean; alive: boolean; } /** `rotationDegrees` uses the Pygame convention (0 = Down). */ -export function createShot(origin: Vec2, rotationDegrees: number, owner: number): Shot { +export function createShot(origin: Vec2, rotationDegrees: number, owner: number, charged = false): Shot { const dir = getForwardVector(rotationDegrees); return { position: { x: origin.x, y: origin.y }, velocity: { x: dir.x * PLAYER_SHOOT_SPEED, y: dir.y * PLAYER_SHOOT_SPEED }, radius: SHOT_RADIUS, owner, + charged, alive: true, }; } diff --git a/phaser-asteroids/src/dev/lightningTrial.ts b/phaser-asteroids/src/dev/lightningTrial.ts new file mode 100644 index 0000000..3986838 --- /dev/null +++ b/phaser-asteroids/src/dev/lightningTrial.ts @@ -0,0 +1,57 @@ +import type Phaser from 'phaser'; +import { createAsteroid } from '../core/asteroid'; +import type { GameSim } from '../core/game'; +import { createPowerUp } from '../core/powerup'; +import { respawnPlayer } from '../core/player'; +import { seededRng } from '../core/rng'; +import { addText } from '../ui/text'; + +/** Only dynamically imported by a DEV, casual GameScene. Reset uses a fresh isolated trial RNG for pickups. */ +export function installLightningTrial(scene: Phaser.Scene, sim: GameSim): void { + const reset = (): void => { + sim.phase = 'playing'; + sim.gameOverReason = null; + sim.spawner.spawnTimer = -1e9; + sim.ufoSpawner.enabled = false; + sim.asteroids = []; + sim.shots = []; + sim.ufoShots = []; + sim.ufos = []; + sim.powerups = []; + sim.lasers = []; + sim.lightningFlashes = []; + sim.volatileFlashes = []; + sim.pickupFlashes = []; + sim.combo.count = 0; + sim.combo.timer = 0; + sim.streakBanner = null; + sim.startCooldown = 0; + sim.slowMotion = { active: false, timer: 0 }; + sim.players.forEach((player, index) => { + const y = index === 0 ? 300 : 540; + player.lives = 3; + player.score = 0; + respawnPlayer(player, 220, y); + player.isRespawning = false; + player.rotation = 270; // point toward the trial rocks + player.shootTimer = 0; + const pickup = createPowerUp(220, y, 'chain_lightning', seededRng(7)); + pickup.velocity = { x: 0, y: 0 }; + sim.powerups.push(pickup); + sim.asteroids.push( + createAsteroid(400, y, 20), + createAsteroid(530, y - 25, 20, 'armored'), + createAsteroid(675, y, 20, 'volatile'), + createAsteroid(775, y, 20, 'volatile'), + createAsteroid(875, y, 20), + ); + }); + }; + reset(); + const button = addText(scene, 640, 165, 'RESET LIGHTNING TRIAL', { size: 24, originX: 0.5, color: '#39cfff' }) + .setDepth(12).setPadding(14, 10).setBackgroundColor('#102331').setInteractive({ useHandCursor: true }); + button.on('pointerdown', reset); + addText(scene, 640, 220, 'Hold FIRE: armour takes a hit, then orange rocks chain-react.\nTap RESET to repeat the 7-second pickup.', { + size: 18, originX: 0.5, color: '#a7dfff', + }).setDepth(12); +} diff --git a/phaser-asteroids/src/ranked/env.d.ts b/phaser-asteroids/src/ranked/env.d.ts index c9d2ce5..f54ffdb 100644 --- a/phaser-asteroids/src/ranked/env.d.ts +++ b/phaser-asteroids/src/ranked/env.d.ts @@ -1,5 +1,6 @@ // The project deliberately has no vite/client types; this declares the one build-time variable the ranked client reads. interface ImportMetaEnv { + readonly DEV: boolean; /** Base URL of the leaderboard API baked into a production build, e.g. https://asteroids-leaderboard.example.workers.dev */ readonly VITE_LEADERBOARD_API_URL?: string; } diff --git a/phaser-asteroids/src/ranked/scoringEras.ts b/phaser-asteroids/src/ranked/scoringEras.ts index df75fd6..c4af68b 100644 --- a/phaser-asteroids/src/ranked/scoringEras.ts +++ b/phaser-asteroids/src/ranked/scoringEras.ts @@ -1,10 +1,11 @@ /** 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. + * Add compatible technical versions to an existing era explicitly; introduce a new era 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', + '1.2.0': 'V3', } as const); export type ScoringEra = (typeof SCORING_ERAS)[keyof typeof SCORING_ERAS]; diff --git a/phaser-asteroids/src/render/powerupIcons.ts b/phaser-asteroids/src/render/powerupIcons.ts index 2f6e15b..70b4af0 100644 --- a/phaser-asteroids/src/render/powerupIcons.ts +++ b/phaser-asteroids/src/render/powerupIcons.ts @@ -11,6 +11,7 @@ export const POWERUP_COLOR: Record = { shield: 0x00ffff, multi_shot: 0xffa500, slow_motion: 0xff00ff, + chain_lightning: 0x39cfff, mega_power: 0xff64ff, revive: 0x00ff64, }; @@ -37,6 +38,21 @@ export function drawPowerUpIcon( const radius = Math.trunc(baseRadius * (0.8 + 0.4 * pulse)); switch (type) { + case 'chain_lightning': { + g.lineStyle(1.5, POWERUP_COLOR.chain_lightning, 0.7); + g.strokeCircle(cx, cy, radius); + g.fillStyle(POWERUP_COLOR.chain_lightning, 1); + g.beginPath(); + g.moveTo(cx + radius * 0.45, cy - radius * 0.95); + g.lineTo(cx - radius * 0.6, cy + radius * 0.12); + g.lineTo(cx - radius * 0.05, cy + radius * 0.12); + g.lineTo(cx - radius * 0.4, cy + radius * 0.95); + g.lineTo(cx + radius * 0.65, cy - radius * 0.2); + g.lineTo(cx + radius * 0.1, cy - radius * 0.2); + g.closePath(); + g.fillPath(); + break; + } case 'rapid_fire': { const color = POWERUP_COLOR.rapid_fire; g.lineStyle(3, color, 1); diff --git a/phaser-asteroids/src/render/worldRenderer.ts b/phaser-asteroids/src/render/worldRenderer.ts index 8503100..dc6738a 100644 --- a/phaser-asteroids/src/render/worldRenderer.ts +++ b/phaser-asteroids/src/render/worldRenderer.ts @@ -1,7 +1,7 @@ import type Phaser from 'phaser'; import { archetypeConfig, type Asteroid } from '../core/asteroid'; import { BOOST_FLASH_COUNT, BOOST_FLASH_PERIOD, BOOST_WARNING_TIME } from '../core/constants'; -import { PICKUP_FLASH_DURATION, VOLATILE_FLASH_DURATION, type GameSim } from '../core/game'; +import { LIGHTNING_FLASH_DURATION, PICKUP_FLASH_DURATION, VOLATILE_FLASH_DURATION, type GameSim } from '../core/game'; import type { LaserBeam } from '../core/laser'; import { getForwardVector } from '../core/math'; import { shipTriangle, type PlayerState } from '../core/player'; @@ -195,6 +195,15 @@ export function drawWorld(g: Graphics, sim: GameSim, timeMs: number): void { if (!s.alive) continue; g.lineStyle(2, coop ? (PLAYER_BASE_COLOR[s.owner - 1] ?? WHITE) : WHITE, 1); g.strokeCircle(s.position.x, s.position.y, s.radius); + if (s.charged) { + // Keep the owner-coloured centre visible in co-op; the cyan halo and tail identify charge. + const speed = Math.hypot(s.velocity.x, s.velocity.y) || 1; + const dx = s.velocity.x / speed; + const dy = s.velocity.y / speed; + g.lineStyle(2, POWERUP_COLOR.chain_lightning, 0.9); + g.strokeCircle(s.position.x, s.position.y, s.radius + 3); + g.lineBetween(s.position.x - dx * 5, s.position.y - dy * 5, s.position.x - dx * 14 + dy * 3, s.position.y - dy * 14 - dx * 3); + } } for (const u of sim.ufos) if (u.alive) drawUfo(g, u); @@ -241,5 +250,39 @@ export function drawWorld(g: Graphics, sim: GameSim, timeMs: number): void { } } + for (const flash of sim.lightningFlashes) { + const t = flash.age / LIGHTNING_FLASH_DURATION; + const fade = 1 - t; + for (let link = 1; link < flash.points.length; link++) { + const from = flash.points[link - 1]!; + const to = flash.points[link]!; + const dx = to.x - from.x; + const dy = to.y - from.y; + const length = Math.hypot(dx, dy) || 1; + // Fixed jagged geometry: no rendering randomness ever touches the simulation RNG. + for (const [width, color, alpha] of [[7, 0x168dff, 0.25], [3, 0x39cfff, 0.85], [1, 0xeeffff, 1]] as const) { + g.lineStyle(width, color, fade * alpha); + g.beginPath(); + g.moveTo(from.x, from.y); + for (let segment = 1; segment <= 7; segment++) { + const fraction = segment / 7; + const offset = segment === 7 ? 0 : Math.sin(segment * 7.3 + link * 2.1) * Math.min(8, length * 0.12); + g.lineTo(from.x + dx * fraction - dy / length * offset, from.y + dy * fraction + dx / length * offset); + } + g.strokePath(); + } + } + for (const point of flash.points) { + for (let spark = 0; spark < 6; spark++) { + const angle = spark * Math.PI / 3 + point.x * 0.03; + const distance = 4 + t * 28; + const dx = Math.cos(angle); + const dy = Math.sin(angle); + g.lineStyle(2, spark % 2 ? 0xeeffff : 0x39cfff, fade * fade); + g.lineBetween(point.x + dx * distance, point.y + dy * distance, point.x + dx * (distance + 7 * fade), point.y + dy * (distance + 7 * fade)); + } + } + } + if (!sim.isGameOver) for (const laser of sim.lasers) drawLaser(g, laser, coop); } diff --git a/phaser-asteroids/src/replay/constants.ts b/phaser-asteroids/src/replay/constants.ts index a9c7c9a..bf215cc 100644 --- a/phaser-asteroids/src/replay/constants.ts +++ b/phaser-asteroids/src/replay/constants.ts @@ -5,7 +5,7 @@ export const REPLAY_SCHEMA_VERSION = 1; /** Semantic rules version defining simulation outcomes, including spawn/drop balance. */ -export const GAMEPLAY_RULES_VERSION = '1.1.0'; +export const GAMEPLAY_RULES_VERSION = '1.2.0'; /** Authoritative simulation tick rate in Hz. */ export const FIXED_TICK_RATE = 60; diff --git a/phaser-asteroids/src/replay/snapshot.ts b/phaser-asteroids/src/replay/snapshot.ts index b8d4113..39e07bb 100644 --- a/phaser-asteroids/src/replay/snapshot.ts +++ b/phaser-asteroids/src/replay/snapshot.ts @@ -18,6 +18,7 @@ export interface PlayerSnapshot { travelHeading: number | null; rapidFire: { active: boolean; timer: number }; multiShot: { active: boolean; timer: number }; + chainLightning: { active: boolean; timer: number }; megaPower: { active: boolean; timer: number }; shieldActive: boolean; boost: { active: boolean; timer: number; cooldown: number; keyHeld: boolean }; @@ -52,6 +53,7 @@ export interface ProjectileSnapshot { vx: number; vy: number; owner?: number; + charged?: boolean; } export interface PowerUpSnapshot { @@ -109,6 +111,7 @@ function capturePlayerSnapshot(p: GameSim['player']): PlayerSnapshot { travelHeading: p.travelHeading === null ? null : round(p.travelHeading, 3), rapidFire: { active: p.rapidFire.active, timer: round(p.rapidFire.timer, 3) }, multiShot: { active: p.multiShot.active, timer: round(p.multiShot.timer, 3) }, + chainLightning: { active: p.chainLightning.active, timer: round(p.chainLightning.timer, 3) }, megaPower: { active: p.megaPower.active, timer: round(p.megaPower.timer, 3) }, shieldActive: p.shieldActive, boost: { @@ -166,6 +169,7 @@ export function captureSimSnapshot(sim: GameSim, tick = 0): SimSnapshot { vx: round(s.velocity.x), vy: round(s.velocity.y), owner: s.owner, + charged: !!s.charged, })), ufoShots: sim.ufoShots.map((s) => ({ x: round(s.position.x), @@ -211,6 +215,8 @@ export function compareSnapshots(a: SimSnapshot, b: SimSnapshot): SnapshotDiff { check('player.velocity', a.player.velocity, b.player.velocity); check('player.travelHeading', a.player.travelHeading, b.player.travelHeading); check('player.shieldActive', a.player.shieldActive, b.player.shieldActive); + check('player.chainLightning', a.player.chainLightning, b.player.chainLightning); + check('player2', a.player2, b.player2); check('player.boost', a.player.boost, b.player.boost); check('player.laser', a.player.laser, b.player.laser); check('combo', a.combo, b.combo); diff --git a/phaser-asteroids/src/scenes/GameScene.ts b/phaser-asteroids/src/scenes/GameScene.ts index 758bd39..cc47186 100644 --- a/phaser-asteroids/src/scenes/GameScene.ts +++ b/phaser-asteroids/src/scenes/GameScene.ts @@ -285,6 +285,13 @@ export class GameScene extends Phaser.Scene { this.setupInput(); this.setupLifecycle(); + // Tree-shaken from production, and never injected into any recorded or ranked simulation. + if (import.meta.env.DEV && !this.isVerifiedMode && !this.rankedChallenge && new URLSearchParams(window.location.search).has('lightningtrial')) { + const sim = this.sim; + void import('../dev/lightningTrial').then(({ installLightningTrial }) => { + if (this.scene.isActive() && this.sim === sim) installLightningTrial(this, sim); + }); + } } override update(time: number): void { diff --git a/phaser-asteroids/src/ui/hud.ts b/phaser-asteroids/src/ui/hud.ts index 25872ad..b36cc04 100644 --- a/phaser-asteroids/src/ui/hud.ts +++ b/phaser-asteroids/src/ui/hud.ts @@ -211,7 +211,7 @@ export class AbilityHud { const right = index === 1; const x = right ? SCREEN_WIDTH - 10 : 10; const size = Math.round(20 * scale); - this.lines = Array.from({ length: 6 }, () => { + this.lines = Array.from({ length: 7 }, () => { const text = addText(scene, x, 80 * scale, '', { size, originX: right ? 1 : 0 }).setDepth(10); return new CachedText(text, COLORS.white, size); }); @@ -244,6 +244,8 @@ export class AbilityHud { if (p.shieldActive) row('SHIELD: ACTIVE', HUD_SHIELD); if (single && sim.slowMotion.active) row(`SLOW MOTION: ${secondsLeft(sim.slowMotion.timer)}s`, HUD_SLOW); } + // Independent of Mega Power: it neither grants nor hides Lightning. + if (p.chainLightning.active) row(`LIGHTNING: ${Math.ceil(p.chainLightning.timer)}s`, '#39cfff'); } const k = this.scale; diff --git a/phaser-asteroids/src/ui/menu/pages/title.ts b/phaser-asteroids/src/ui/menu/pages/title.ts index a01e514..5c4459f 100644 --- a/phaser-asteroids/src/ui/menu/pages/title.ts +++ b/phaser-asteroids/src/ui/menu/pages/title.ts @@ -301,8 +301,8 @@ function buildLegend(kit: PageKit, ctx: MenuContext, count: 1 | 2, nav: PageNav) const cell = (LEGEND.w - 40) / info.length; info.forEach((p, i) => { const cx = LEGEND.x + 20 + cell * i + cell / 2; - kit.text(cx, LEGEND.y + 142, p.name, { size: TEXT.body - 2, originX: 0.5, originY: 0.5, color: p.color }); - kit.text(cx, LEGEND.y + 180, p.short, { size: TEXT.small, originX: 0.5, originY: 0.5, color: COLORS.hint, bold: false }); + kit.text(cx, LEGEND.y + 142, p.name, { size: info.length > 6 ? 20 : TEXT.body - 2, originX: 0.5, originY: 0.5, color: p.color }); + kit.text(cx, LEGEND.y + 180, p.short, { size: info.length > 6 ? 18 : TEXT.small, originX: 0.5, originY: 0.5, color: COLORS.hint, bold: false }); }); kit.onFrame((now) => { icons.clear(); diff --git a/phaser-asteroids/src/ui/menu/powerupInfo.ts b/phaser-asteroids/src/ui/menu/powerupInfo.ts index 68327da..5d51613 100644 --- a/phaser-asteroids/src/ui/menu/powerupInfo.ts +++ b/phaser-asteroids/src/ui/menu/powerupInfo.ts @@ -1,4 +1,7 @@ import { + CHAIN_LIGHTNING_DURATION, + CHAIN_LIGHTNING_MAX_TARGETS, + CHAIN_LIGHTNING_RANGE, MEGA_POWER_DURATION, MULTI_SHOT_DURATION, PLAYER_SHOOT_COOLDOWN, @@ -36,7 +39,7 @@ const seconds = (s: number): string => `${s} second${s === 1 ? '' : 's'}`; const color = (type: PowerUpType): string => toCss(POWERUP_COLOR[type]); -/** The five one-player power-ups, then Revive. */ +/** The six one-player power-ups, then Revive. */ export const POWERUP_INFO: readonly PowerUpInfo[] = [ { type: 'rapid_fire', @@ -70,10 +73,18 @@ export const POWERUP_INFO: readonly PowerUpInfo[] = [ coopOnly: false, color: color('slow_motion'), }, + { + type: 'chain_lightning', + name: 'LIGHTNING', + short: 'Chain hits', + detail: `Charged bullets jump to ${CHAIN_LIGHTNING_MAX_TARGETS} more asteroids within ${CHAIN_LIGHTNING_RANGE} px per jump, for ${seconds(CHAIN_LIGHTNING_DURATION)}.`, + coopOnly: false, + color: color('chain_lightning'), + }, { type: 'mega_power', name: 'MEGA POWER', - short: 'All powers!', + short: '4 powers!', detail: `Rapid Fire + Multi-Shot + Shield + Slow Motion at once, for ${seconds(MEGA_POWER_DURATION)}. The shield stays until hit.`, coopOnly: false, color: color('mega_power'), @@ -88,7 +99,7 @@ export const POWERUP_INFO: readonly PowerUpInfo[] = [ }, ]; -/** What the compact legend on the title screen lists: the one-player five, plus Revive when two players are on. */ +/** What the compact legend on the title screen lists: the one-player six, plus Revive when two players are on. */ export function legendFor(playerCount: 1 | 2): readonly PowerUpInfo[] { return playerCount === 2 ? POWERUP_INFO : POWERUP_INFO.filter((p) => !p.coopOnly); } diff --git a/phaser-asteroids/tests/audioMix.test.ts b/phaser-asteroids/tests/audioMix.test.ts index 6a5f00f..20e3466 100644 --- a/phaser-asteroids/tests/audioMix.test.ts +++ b/phaser-asteroids/tests/audioMix.test.ts @@ -43,6 +43,7 @@ const DURATION: Record = { explosion_medium: 4.94, explosion_large: 12.34, laser: 2.04, + lightning: 0.11, boost: 0.77, player_death: 3.35, }; diff --git a/phaser-asteroids/tests/chainLightning.test.ts b/phaser-asteroids/tests/chainLightning.test.ts new file mode 100644 index 0000000..1fbeb56 --- /dev/null +++ b/phaser-asteroids/tests/chainLightning.test.ts @@ -0,0 +1,268 @@ +import { describe, expect, it, vi } from 'vitest'; +import { SfxPlayer } from '../src/audio/sfxPlayer'; +import { CHAIN_LIGHTNING_DURATION, RAPID_FIRE_COOLDOWN } from '../src/core/constants'; +import { GameSim, LIGHTNING_FLASH_LIMIT } from '../src/core/game'; +import { activateChainLightning, activateMegaPower, activateMultiShot, activateRapidFire, createPlayer, eliminatePlayer, NO_INPUT, respawnPlayer, updatePlayer } from '../src/core/player'; +import { seededRng } from '../src/core/rng'; +import { createShot } from '../src/core/shot'; +import { captureSimSnapshot, FIXED_DT, GAMEPLAY_RULES_VERSION } from '../src/replay'; +import * as engine from '../src/replay'; +import { loadSettings, RANKED_CONFIG } from '../server/src/config'; +import { verifyRankedReplay } from '../server/src/verify'; +import { generateBotReplay } from '../server/testing/bot.mjs'; +import { FakeBackend } from './audioFakes'; +import { eventsOfType, FRAME, hold, parkedUfoFor, pickupAt, pickupAtShip, quietCoop, quietSim, rock, runFor, shotBy } from './helpers'; + +const chargedAt = (x: number, y: number, owner = 1) => ({ ...shotBy(owner, x, y), charged: true }); + +describe('Chain Lightning power-up', () => { + it('collects for the collector only, refreshes to 7 seconds, expires on real time', () => { + const sim = quietCoop(); + const p = sim.player2!; + pickupAt(sim, 'chain_lightning', p.position.x, p.position.y); + expect(eventsOfType(sim.step(FRAME), 'powerup_collected')).toContainEqual({ type: 'powerup_collected', powerType: 'chain_lightning', player: 2 }); + expect(p.chainLightning).toEqual({ active: true, timer: CHAIN_LIGHTNING_DURATION }); + expect(sim.player.chainLightning.active).toBe(false); + runFor(sim, 2); + pickupAt(sim, 'chain_lightning', p.position.x, p.position.y); + sim.step(FRAME); + expect(p.chainLightning.timer).toBe(CHAIN_LIGHTNING_DURATION); + sim.slowMotion = { active: true, timer: 20 }; + runFor(sim, 7.1); + expect(p.chainLightning).toEqual({ active: false, timer: 0 }); + }); + + it('freezes charge at firing time and coexists with Rapid Fire, Multi-Shot and Mega Power', () => { + const p = createPlayer(200, 200); + const ordinary = updatePlayer(p, hold({ shoot: true }), FRAME).shots[0]!; + activateChainLightning(p); + activateRapidFire(p); + activateMultiShot(p); + p.shootTimer = 0; + const charged = updatePlayer(p, hold({ shoot: true }), FRAME).shots; + expect(charged).toHaveLength(3); + expect(charged.every((s) => s.charged && s.owner === 1)).toBe(true); + expect(p.shootTimer).toBe(RAPID_FIRE_COOLDOWN); + expect(ordinary.charged).toBe(false); + activateMegaPower(p); + p.chainLightning.timer = FRAME / 2; + p.shootTimer = 0; + const expired = updatePlayer(p, hold({ shoot: true }), FRAME).shots; + expect(expired.every((s) => !s.charged)).toBe(true); + expect(charged.every((s) => s.charged)).toBe(true); + const megaOnly = createPlayer(0, 0); + activateMegaPower(megaOnly); + expect(megaOnly.chainLightning.active).toBe(false); + }); + + it('clears on respawn and elimination', () => { + const p = createPlayer(100, 100); + activateChainLightning(p); + respawnPlayer(p, 100, 100); + expect(p.chainLightning).toEqual({ active: false, timer: 0 }); + activateChainLightning(p); + p.lives = 0; + eliminatePlayer(p); + expect(p.chainLightning).toEqual({ active: false, timer: 0 }); + }); + + it('selects nearest from each previous hit, breaks ties by list order, caps at two extra', () => { + const sim = quietSim(); + const source = rock(200, 150, 20); + const farther = rock(200, 300, 20); + const first = rock(300, 150, 20); + const tie = rock(200, 250, 20); + const next = rock(440, 150, 20); // in range only from first, closer than the other tied candidate + sim.asteroids.push(source, farther, first, tie, next, rock(550, 150, 20)); + sim.shots.push(chargedAt(200, 150)); + const events = sim.step(FRAME); + expect(sim.lightningFlashes[0]!.points).toEqual([source.position, first.position, next.position]); + expect(eventsOfType(events, 'asteroid_destroyed')).toHaveLength(3); + expect(eventsOfType(events, 'lightning_discharged')).toHaveLength(1); + expect(tie.dying).toBe(false); + expect(sim.shots).toHaveLength(0); + }); + + it('includes exact 160px boundary, excludes radii and targets beyond it, stops when empty', () => { + const sim = quietSim(); + const edge = rock(360, 150, 20); + const outside = rock(520.01, 150, 60); + sim.asteroids.push(rock(200, 150, 20), edge, outside); + sim.shots.push(chargedAt(200, 150)); + sim.step(FRAME); + expect(edge.dying).toBe(true); + expect(outside.dying).toBe(false); + expect(sim.lightningFlashes[0]!.points).toHaveLength(2); + }); + + it('chains from a surviving armored initial hit and never revisits it or other armor', () => { + const sim = quietSim(); + const source = rock(200, 150, 20, 'armored'); + const armor = rock(300, 150, 20, 'armored'); + const last = rock(440, 150, 20); + sim.asteroids.push(source, armor, last); + sim.shots.push(chargedAt(200, 150)); + const events = sim.step(FRAME); + expect(source.hitPoints).toBe(1); + expect(armor.hitPoints).toBe(1); + expect(last.dying).toBe(true); + expect(eventsOfType(events, 'asteroid_hit')).toHaveLength(2); + expect(eventsOfType(events, 'asteroid_destroyed')).toHaveLength(1); + expect(sim.lightningFlashes[0]!.points).toHaveLength(3); + }); + + it('credits normal combo scores to player 2, once per kill and drop roll', () => { + // All drops guaranteed; presentation particle RNG also returns zero, but cannot create extra drops. + const sim = quietCoop({}, 1, () => 0); + sim.asteroids.push(rock(200, 150, 20), rock(350, 150, 20), rock(500, 150, 20)); + sim.shots.push(chargedAt(200, 150, 2), chargedAt(200, 150, 1)); + const kills = eventsOfType(sim.step(FRAME), 'asteroid_destroyed'); + expect(kills.map((e) => [e.player, e.combo, e.multiplier, e.points])).toEqual([[2, 1, 1, 50], [2, 2, 1.5, 75], [2, 3, 2, 100]]); + expect(sim.player.score).toBe(0); + expect(sim.player2!.score).toBe(225); + expect(sim.powerups).toHaveLength(3); + expect(eventsOfType(sim.step(FRAME), 'asteroid_destroyed')).toHaveLength(0); + expect(sim.powerups).toHaveLength(3); + }); + + it('detonates volatile chains, skips blast kills and keeps their normal ownership without extra chains', () => { + const sim = quietCoop(); + const source = rock(200, 150, 20); + const volatile = rock(350, 150, 20, 'volatile'); + const blastKill = rock(450, 150, 20, 'volatile'); + const armor = rock(500, 210, 20, 'armored'); + const last = rock(350, 300, 20); + sim.asteroids.push(source, volatile, blastKill, armor, last); + sim.shots.push(chargedAt(200, 150, 2)); + const events = sim.step(FRAME); + expect(eventsOfType(events, 'volatile_exploded')).toHaveLength(2); + expect(armor.hitPoints).toBe(1); // normal blast damage + expect(sim.lightningFlashes[0]!.points).toEqual([source.position, volatile.position, last.position]); + expect(eventsOfType(events, 'lightning_discharged')).toHaveLength(1); + const kills = eventsOfType(events, 'asteroid_destroyed'); + expect(kills).toHaveLength(4); + expect(kills.every((e) => e.player === 2)).toBe(true); + expect(sim.player2!.score).toBe(kills.reduce((sum, e) => sum + e.points, 0)); + }); + + it('handles a volatile initial hit and does not jump to asteroids its blast already killed', () => { + const sim = quietSim(); + sim.asteroids.push(rock(200, 150, 20, 'volatile'), rock(300, 150, 20), rock(200, 305, 20)); + sim.shots.push(chargedAt(200, 150)); + sim.step(FRAME); + expect(sim.lightningFlashes[0]!.points).toEqual([{ x: 200, y: 150 }, { x: 200, y: 305 }]); + expect(sim.combo.count).toBe(3); + }); + + it('does not chain from ordinary bullets, lasers, UFO hits or friendly hits', () => { + const sim = quietCoop({ friendlyFire: true }); + activateChainLightning(sim.player2!); + sim.asteroids.push(rock(200, 150, 20), rock(350, 150, 20)); + sim.shots.push(shotBy(2, 200, 150)); // already in flight before pickup + const ufo = parkedUfoFor(sim, 'large', 900, 200); + sim.shots.push(chargedAt(900, 200, 2)); + const p = sim.player; + sim.shots.push(chargedAt(p.position.x, p.position.y, 2)); + sim.step(FRAME); + expect(sim.asteroids[1]!.dying).toBe(false); + expect(ufo.alive).toBe(false); // original bullet still behaves normally + expect(p.lives).toBe(2); // existing friendly fire remains normal + expect(sim.lightningFlashes).toHaveLength(0); + sim.player2!.position = { x: 100, y: 150 }; + sim.player2!.rotation = 270; + expect(eventsOfType(sim.step(FRAME, NO_INPUT, hold({ laser: true })), 'lightning_discharged')).toHaveLength(0); + }); + + it('spares nearby players, UFOs and powerups, ignores dead/dying rocks', () => { + const sim = quietCoop(); + sim.player.position = { x: 200, y: 235 }; + const ufo = parkedUfoFor(sim, 'large', 200, 65); + const pickup = pickupAt(sim, 'shield', 200, 285); + const dead = rock(210, 150, 20); + dead.alive = false; + const dying = rock(220, 150, 20); + dying.dying = true; + dying.deathTimer = 1; + sim.asteroids.push(rock(200, 150, 20), dead, dying); + sim.shots.push(chargedAt(200, 150, 2)); + sim.step(FRAME); + expect(sim.player.lives).toBe(3); + expect(ufo.alive).toBe(true); + expect(pickup.alive).toBe(true); + expect(sim.lightningFlashes[0]!.points).toHaveLength(1); + }); + + it('caps and expires decoration, rate-limits zap voices and consumes no additional gameplay RNG', () => { + const a = quietSim(42); + const b = quietSim(42); + for (const sim of [a, b]) { + pickupAtShip(sim, 'chain_lightning'); + sim.step(FRAME); + sim.asteroids.push(rock(200, 150, 20), rock(350, 150, 20, 'volatile'), rock(450, 150, 20)); + sim.shots.push(chargedAt(200, 150)); + } + const backend = new FakeBackend(); + const sfx = new SfxPlayer(backend, seededRng(999)); + for (let tick = 0; tick < 30; tick++) { + const events = a.step(FRAME); + sfx.handle(events); + expect(b.step(FRAME)).toEqual(events); + b.lightningFlashes = []; + } + expect(captureSimSnapshot(a)).toEqual(captureSimSnapshot(b)); + expect(a.rng()).toBe(b.rng()); + expect(a.lightningFlashes).toHaveLength(0); + sfx.handle(Array.from({ length: 30 }, () => ({ type: 'lightning_discharged' as const, player: 1 }))); + expect(backend.count('lightning')).toBe(1); + const dense = quietSim(); + for (let i = 0; i < 90; i++) { + dense.asteroids.push(rock(200, 150, 20)); + dense.shots.push(chargedAt(200, 150)); + } + dense.step(FRAME); + expect(dense.lightningFlashes).toHaveLength(LIGHTNING_FLASH_LIMIT); + }); + + it('retains charge through expiration and starts no more than one chain per projectile', () => { + const sim = quietSim(); + const p = sim.player; + activateChainLightning(p); + p.rotation = 270; + const shot = createShot({ x: 200, y: 150 }, 270, 1, p.chainLightning.active); + shot.velocity = { x: 0, y: 0 }; + p.chainLightning = { active: false, timer: 0 }; + sim.asteroids.push(rock(200, 150, 20, 'armored'), rock(300, 150, 20), rock(400, 150, 20)); + sim.shots.push(shot); + expect(eventsOfType(sim.step(FRAME), 'lightning_discharged')).toHaveLength(1); + expect(shot.alive).toBe(false); + expect(eventsOfType(sim.step(FRAME), 'lightning_discharged')).toHaveLength(0); + }); + + it('reproduces genuine lightning pickups and destruction order in the authoritative current-rules verifier', () => { + const seed = 54321; + const events: ReturnType = []; + const original = GameSim.prototype.step; + const spy = vi.spyOn(GameSim.prototype, 'step').mockImplementation(function (this: GameSim, ...args) { + const result = original.apply(this, args); + events.push(...result); + return result; + }); + try { + const run = generateBotReplay(engine, { seed }); + const trace = events.splice(0); + const verdict = verifyRankedReplay(run.replay, { + seed, rulesVersion: GAMEPLAY_RULES_VERSION, config: RANKED_CONFIG, createdAt: 0, + }, run.ticks * FIXED_DT * 1000, loadSettings()); + expect(verdict.ok).toBe(true); + if (verdict.ok) expect(verdict.result.calculatedScore).toBe(run.score); + expect(events).toEqual(trace); + expect(eventsOfType(events, 'powerup_collected').some((e) => e.powerType === 'chain_lightning')).toBe(true); + expect(eventsOfType(events, 'lightning_discharged').length).toBeGreaterThan(0); + const oldReplay = structuredClone(run.replay); + oldReplay.header.rulesVersion = '1.1.0'; + expect(verifyRankedReplay(oldReplay, { seed, rulesVersion: GAMEPLAY_RULES_VERSION, config: RANKED_CONFIG, createdAt: 0 }, 1e9, loadSettings()).ok).toBe(false); + } finally { + spy.mockRestore(); + } + }); +}); diff --git a/phaser-asteroids/tests/menuContent.test.ts b/phaser-asteroids/tests/menuContent.test.ts index 7c9c177..02bd591 100644 --- a/phaser-asteroids/tests/menuContent.test.ts +++ b/phaser-asteroids/tests/menuContent.test.ts @@ -19,8 +19,8 @@ import { legendFor, POWERUP_INFO, SHORT_MAX } from '../src/ui/menu/powerupInfo'; describe('power-up text', () => { const info = (type: PowerUpType) => POWERUP_INFO.find((p) => p.type === type)!; - it('covers the five one-player power-ups and Revive, each once', () => { - expect(POWERUP_INFO.map((p) => p.type)).toEqual(['rapid_fire', 'multi_shot', 'shield', 'slow_motion', 'mega_power', 'revive']); + it('covers the six one-player power-ups and Revive, each once', () => { + expect(POWERUP_INFO.map((p) => p.type)).toEqual(['rapid_fire', 'multi_shot', 'shield', 'slow_motion', 'chain_lightning', 'mega_power', 'revive']); expect(POWERUP_INFO.filter((p) => p.coopOnly).map((p) => p.type)).toEqual(['revive']); }); @@ -58,15 +58,15 @@ describe('power-up text', () => { const cell = (1200 - 40) / list.length; for (const p of list) { expect(p.short.length).toBeLessThanOrEqual(SHORT_MAX); - expect(p.short.length * 13.2).toBeLessThan(cell - 4); - expect(p.name.length * 14.4).toBeLessThan(cell - 4); + expect(p.short.length * (list.length > 6 ? 10.8 : 13.2)).toBeLessThan(cell - 4); + expect(p.name.length * (list.length > 6 ? 12 : 14.4)).toBeLessThan(cell - 4); } } }); it('shows Revive in the legend only for two players', () => { expect(legendFor(1).map((p) => p.type)).not.toContain('revive'); - expect(legendFor(1)).toHaveLength(5); + expect(legendFor(1)).toHaveLength(6); expect(legendFor(2).map((p) => p.type)).toContain('revive'); }); }); diff --git a/phaser-asteroids/tests/powerup.test.ts b/phaser-asteroids/tests/powerup.test.ts index 7c7e8cb..85bc155 100644 --- a/phaser-asteroids/tests/powerup.test.ts +++ b/phaser-asteroids/tests/powerup.test.ts @@ -27,14 +27,14 @@ describe('power-up drops', () => { expect(maybeSpawnPowerUp(100, 100, rng)?.type).toBe('mega_power'); }); - it('otherwise a roll under 12% drops one of the four ordinary types, picked uniformly', () => { + it('otherwise a roll under 12% drops one of the five ordinary types, picked uniformly', () => { const types = []; - for (const pick of [0.0, 0.26, 0.51, 0.76]) { + for (const pick of [0.0, 0.2, 0.4, 0.6, 0.8]) { const rng = queueRng(); rng.queue(0.5 /* not mega */, 0.1199 /* drops */, pick /* which one */); types.push(maybeSpawnPowerUp(0, 0, rng)?.type); } - expect(types).toEqual(['rapid_fire', 'shield', 'multi_shot', 'slow_motion']); + expect(types).toEqual(['rapid_fire', 'shield', 'multi_shot', 'slow_motion', 'chain_lightning']); }); it('does not drop on a roll of 12% or more', () => { @@ -55,8 +55,8 @@ describe('power-up drops', () => { expect(total / n).toBeCloseTo(0.015 + 0.985 * 0.12, 2); expect((counts['mega_power'] ?? 0) / n).toBeCloseTo(0.015, 2); expect(counts['revive']).toBeUndefined(); - for (const t of ['rapid_fire', 'shield', 'multi_shot', 'slow_motion']) { - expect((counts[t] ?? 0) / n).toBeCloseTo((0.985 * 0.12) / 4, 2); + for (const t of ['rapid_fire', 'shield', 'multi_shot', 'slow_motion', 'chain_lightning']) { + expect((counts[t] ?? 0) / n).toBeCloseTo((0.985 * 0.12) / 5, 2); } }); }); diff --git a/phaser-asteroids/tests/ranked.test.ts b/phaser-asteroids/tests/ranked.test.ts index d4a8899..bb8cf3c 100644 --- a/phaser-asteroids/tests/ranked.test.ts +++ b/phaser-asteroids/tests/ranked.test.ts @@ -30,7 +30,7 @@ const challenge: RankedChallenge = { runId: '11111111-1111-4111-8111-111111111111', token: 't'.repeat(43), seed: 123456, - rulesVersion: '1.1.0', + rulesVersion: '1.2.0', schemaVersion: 1, tickRate: 60, config: { playerCount: 1, livesMode: 'independent', friendlyFire: false, speed: [1, 1] }, @@ -43,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, rulesVersion: '1.1.0', completedAt: '2026-10-22T15:01:00.000Z', durationSeconds: 25, endReason: 'game_over' }, + score: { id: 's1', nickname: 'Ace', score: 1250, rulesVersion: '1.2.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 }); @@ -218,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', rulesVersion: '1.1.0' }]); + expect(readLocalScores(storage)).toEqual([{ id: 's1', score: 1250, at: '2026-10-22T15:01:00.000Z', nickname: 'Ace', rulesVersion: '1.2.0' }]); expect(lastNickname(storage)).toBe('Ace'); }); @@ -376,13 +376,14 @@ 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); + rememberScore({ id: 'v2', score: 900, at: 'earlier', nickname: 'Ace', rulesVersion: '1.1.0' }, s); + rememberScore({ id: 'v3', score: 800, at: 'new', nickname: 'Ace', rulesVersion: '1.2.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(readLocalScores(s).map((score) => score.rulesVersion)).toEqual(['1.0.0', '1.1.0', '1.2.0']); 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', () => { @@ -427,35 +428,38 @@ 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, 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 }); + const entry = (rank: number) => ({ id: `id${rank}`, rank, nickname: `Pilot ${rank}`, score: 1000 - rank, rulesVersion: '1.2.0', completedAt: '2026-10-22T15:00:00.000Z', durationSeconds: 60, endReason: 'game_over' }); + const page = (over: Record = {}) => ({ scope: 'weekly', rulesVersion: '1.2.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 () => { let url = ''; 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', rulesVersion: '1.1.0' }); + expect(p.entries[0]).toMatchObject({ rank: 1, nickname: 'Pilot 1', rulesVersion: '1.2.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 v2 = { ...entry(2), rulesVersion: '1.1.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 p = await fetchLeaderboard('http://x', 'all-time', { limit: 10, offset: 0 }, async () => reply(200, page({ entries: [historical, v2, entry(3), future] }))); + expect(p.entries.map((e) => scoringEraLabel(e.rulesVersion))).toEqual(['V1', 'V2', 'V3', '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' } }); + expect(accepted).toMatchObject({ kind: 'accepted', score: { rulesVersion: '1.2.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'); + expect(localBest(s)?.rulesVersion).toBe('1.2.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']); + expect(scoringEra('1.2.0')).toBe('V3'); + expect(rulesInScoringEra('1.2.0')).toEqual(['1.2.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'); diff --git a/phaser-asteroids/tests/volatileExplosion.test.ts b/phaser-asteroids/tests/volatileExplosion.test.ts index c9cb0ee..48a1299 100644 --- a/phaser-asteroids/tests/volatileExplosion.test.ts +++ b/phaser-asteroids/tests/volatileExplosion.test.ts @@ -130,7 +130,7 @@ describe('volatile blasts', () => { expect(a.rng()).toBe(b.rng()); }); - it('accepts a short genuine recording with the current local ranked verifier under rules 1.1.0', () => { + it('accepts a short genuine recording with the current local ranked verifier under rules 1.2.0', () => { const seed = 54321; const sim = new GameSim({ rng: seededRng(seed), config: RANKED_CONFIG }); const recorder = new ReplayRecorder(seed, RANKED_CONFIG); @@ -141,7 +141,7 @@ describe('volatile blasts', () => { expect(sim.isGameOver).toBe(false); } recorder.markTimeLimit(sim); - expect(GAMEPLAY_RULES_VERSION).toBe('1.1.0'); + expect(GAMEPLAY_RULES_VERSION).toBe('1.2.0'); const replay = JSON.parse(recorder.serialize()); const verdict = verifyRankedReplay(replay, { seed, rulesVersion: GAMEPLAY_RULES_VERSION, config: RANKED_CONFIG, createdAt: 0, timeLimitTicks: ticks, From c41789e2242ff2783c7d9a9cf13bb9ac45a5c342 Mon Sep 17 00:00:00 2001 From: djblackett <49618491+djblackett@users.noreply.github.com> Date: Fri, 23 Oct 2026 22:07:46 -0300 Subject: [PATCH 2/2] test: update gain and UFO drop expectations after chain lightning --- phaser-asteroids/tests/musicTracks.test.ts | 2 +- phaser-asteroids/tests/ufo.test.ts | 14 +++++++++----- 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/phaser-asteroids/tests/musicTracks.test.ts b/phaser-asteroids/tests/musicTracks.test.ts index 5dc7023..3eb684c 100644 --- a/phaser-asteroids/tests/musicTracks.test.ts +++ b/phaser-asteroids/tests/musicTracks.test.ts @@ -126,7 +126,7 @@ describe('per-track gain', () => { expect(SFX_GAIN.shoot_low).toBe(0.28); expect(SFX_GAIN.explosion_large).toBe(0.8); expect(SFX_GAIN.laser).toBe(0.5); - expect(SFX_GAIN.player_death).toBe(0.7); + expect(SFX_GAIN.player_death).toBe(0.8); }); }); diff --git a/phaser-asteroids/tests/ufo.test.ts b/phaser-asteroids/tests/ufo.test.ts index ba2f9fe..b93749c 100644 --- a/phaser-asteroids/tests/ufo.test.ts +++ b/phaser-asteroids/tests/ufo.test.ts @@ -544,19 +544,23 @@ describe('player shots vs UFOs', () => { expect(sim.powerups).toHaveLength(1); }); - it('drops one of the four ordinary power-ups, uniformly, and never MEGA POWER or Revive', () => { + it('drops one of the ordinary power-ups, uniformly, and never MEGA POWER or Revive', () => { const sim = quietSim(77); + const sampleSize = 800; + const expectedCount = sampleSize / ORDINARY_POWERUPS.length; const counts: Record = {}; - for (let i = 0; i < 800; i++) { + for (let i = 0; i < sampleSize; i++) { parkedUfo(sim, i % 2 ? 'large' : 'small', 300, 300); sim.shots.push(shotAt(300, 300)); const events = sim.step(FRAME); - for (const e of eventsOfType(events, 'powerup_dropped')) counts[e.powerType] = (counts[e.powerType] ?? 0) + 1; + const drops = eventsOfType(events, 'powerup_dropped'); + expect(drops).toHaveLength(1); + for (const e of drops) counts[e.powerType] = (counts[e.powerType] ?? 0) + 1; } expect(Object.keys(counts).sort()).toEqual([...ORDINARY_POWERUPS].sort()); for (const type of ORDINARY_POWERUPS) { - expect(counts[type]).toBeGreaterThan(150); - expect(counts[type]).toBeLessThan(250); + expect(counts[type]).toBeGreaterThan(expectedCount * 0.75); + expect(counts[type]).toBeLessThan(expectedCount * 1.25); } });