diff --git a/phaser-asteroids/docs/gameplay-experiment-a.md b/phaser-asteroids/docs/gameplay-experiment-a.md new file mode 100644 index 0000000..ca17680 --- /dev/null +++ b/phaser-asteroids/docs/gameplay-experiment-a.md @@ -0,0 +1,47 @@ +# Gameplay experiment A (local only) + +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. + +Rules `1.1.0`, replay schema still `1`. Initial values: + +| Setting | Previous | Experiment | +| --- | --- | --- | +| Ordinary asteroid drop roll (after failed Mega roll) | 8% | 12% | +| Mega Power roll | 1.5% | 1.5%, unchanged | +| Armored unlock | 45 s | 25 s | +| Volatile unlock / relative spawn weight | 120 s / 0 | 60 s / 0.12 | +| Small UFO chance per scheduled spawn | 0% until 120 s | 10% from 60 s | + +The existing later small-UFO steps remain 20% at 120 s, 40% at 240 s and 60% at 360 s. +Volatile's normalized share after unlocking is `0.12 / (1 + 0.35 + 0.12)`, about 8.2% of new asteroid +spawn attempts; children inherit the existing archetype rules. Edge spawning/culling is unchanged. +Drop chance including Mega is `0.015 + 0.985 * 0.12 = 13.32%` per eligible asteroid destruction. +Types, durations, UFO cadence/cap/AI, health, visuals, scoring and controls are unchanged. No explosions. + +Play on the Vite development server (`http://127.0.0.1:5173/`), selecting **PLAY** / Space on desktop +or **PRACTICE** on mobile for local play without a ranked backend. If the server is stopped, run +`npm run dev -- --host 127.0.0.1 --port 5173`. +Around 25 s armored rocks become eligible; around 60 s volatile rocks and occasional small UFOs become +eligible. Unlocks do not force immediate encounters: the next scheduled spawn and random roll still apply. + +## Ranked release implications + +Spawn/drop changes alter RNG consumption and simulation outcomes. Both client and Worker import the same +rules constant and core simulation; neither old replays nor old clients should be treated as compatible. +The local client rejects a live `1.0.0` challenge, and the `1.1.0` server rejects runs issued under `1.0.0`. +The verifier supports only the currently deployed rules, with no backward simulation implementation. + +If the experiment is approved, the simplest safe approach is a coordinated frontend/Worker release under +`1.1.0`, with a planned ranked maintenance/cutover window that drains active old-rules runs first and +asks players to refresh. A staggered rollout will temporarily reject mismatched clients; outstanding old +run tokens cannot be verified after the Worker upgrade. Decide that release procedure separately. + +Scores are not directly comparable across these balance rules even though point formulas are unchanged. +Existing leaderboard queries already filter by current rules version, so old rows remain stored but are +excluded from the new all-time/weekly rankings. No database reset or data migration is needed; historical +board browsing is not implemented by this experiment. No production data or deployment was changed. + +The fixed-seed server test's genuine completed run now earns 7884 (previously 9114), illustrating why old +and new results must stay separate. Its replay is generated normally and independently re-simulated by +the existing verifier; no ticks, inputs or claims are padded to force a result. diff --git a/phaser-asteroids/docs/gameplay-experiment-b.md b/phaser-asteroids/docs/gameplay-experiment-b.md new file mode 100644 index 0000000..cb50a11 --- /dev/null +++ b/phaser-asteroids/docs/gameplay-experiment-b.md @@ -0,0 +1,68 @@ +# Experiment B: volatile explosions (local only) + +Experiment A remains in place. Both experiments belong to the unpublished rules `1.1.0`; replay schema remains `1`. +No Worker deployment, production leaderboard changes, commits or pushes were performed. + +## Gameplay + +- `VOLATILE_EXPLOSION_RADIUS` in `src/core/constants.ts` starts at **110 world pixels**. The target's collision + radius counts: a radius-20 rock touching a blast at a centre distance of 130 is hit. +- Every volatile destruction detonates once, including shots, lasers, boost rams, UFO shots and body collisions. + Only living, non-dying asteroids are eligible. Ships, UFOs, shots and pickups take no blast damage. +- Each blast visits a snapshot of the asteroid list once. Destruction marks a rock dying before it can be + targeted again. Newly destroyed volatile rocks append a blast to an explicit breadth-first queue, processed + synchronously in stable asteroid-list order. There is no recursive chain traversal or lingering damage zone. +- Standard rocks die; armor takes one ordinary hit per blast. Two overlapping blasts can finish armored rocks. +- Player credit follows the entire chain. Kills use the existing combo, points and multiplier calculation, + and the existing power-up drop rules. No explosion bonus multiplier was added. +- UFO-initiated chains pay nobody, retaining the existing uncredited-hit combo/drop rules. A body collision + still pays nothing and gives no combo/drop for the original rock; subsequent blast kills remain uncredited + and use the ordinary hit rules. Competing shots cannot steal a rock already marked dying. +- Splitting is unchanged, including volatile children. Children appear after the normal death delay and are + outside the completed chain's target snapshot. A later, separate blast can hit them normally. +- Volatile unlock (60 seconds), spawn weight (0.12), orange color, bonus points, all Experiment A balancing, + power-up behavior, enemy AI, player abilities and difficulty progression are preserved. + +## Feedback and limits + +Each detonation has its own orange/yellow expanding double ring and 12 short spark strokes, fading over +0.32 seconds. Chain links stagger their visuals by 25 ms per depth (maximum 100 ms), with immediate gameplay +damage. At most 32 blast visuals remain active. There is no fullscreen flash, texture or particle emitter. +These new visuals use no random numbers and can be discarded without changing gameplay/RNG state. + +Volatile breakups replace the ordinary sound with the existing large explosion sample at a deeper playback +rate (0.8, increasing by 0.06 per chain depth up to 1.04). Existing explosion voice caps and overlap falloff +remain active. Shake requests are 6 pixels, using the existing 100 ms cooldown and global 12-pixel cap; +simultaneous chain links do not stack shake. + +## Focused validation + +`tests/volatileExplosion.test.ts` covers range boundaries, standard and armored damage, cyclic and dense +chains, player-2 score/combo ownership, uncredited causes, duplicate prevention, player/UFO immunity, +splitting, effect/audio caps, matching seeded outcomes with presentation discarded, and a short genuine +recording accepted by the local ranked verifier. Existing asteroid and audio tests are also relevant. + +Validation passed: all 121 tests in the selected explosion/asteroid/audio files, nine targeted ranked +integration cases, and both client and server TypeScript checks. No browser suite or production build was run. + +The existing genuine ranked reference replay is accepted by the authoritative local verifier with a score +of **13959** (A alone: 7884). Its longer survival also requires fixture clocks to advance by actual replay +duration instead of a fixed 200 seconds. This is a deterministic fixture result, not a balance estimate. +Both browser and server import the same updated simulation. Rules stay `1.1.0`; A-only development replays +with that version are no longer outcome-compatible. The coordinated-release considerations in +`gameplay-experiment-a.md` still apply. Production was not contacted. + +## Trying it + +From `phaser-asteroids`, run: + +```powershell +npm run dev -- --host 127.0.0.1 --port 5173 +``` + +Open `http://127.0.0.1:5173/`, then **PLAY** / Space on desktop or **PRACTICE** on mobile. +Volatile spawns become eligible at 60 seconds; the unlock does not guarantee an immediate spawn. +Shoot orange rocks near groups, try overlapping blasts on armor, and try laser/boost-triggered chains. + +Watch score/combo growth and drop density in clusters, the continuing threat from volatile children, +and whether the boom/rings remain readable and comfortable during larger chains on mobile. diff --git a/phaser-asteroids/scripts/ranked-ui.mjs b/phaser-asteroids/scripts/ranked-ui.mjs index 58a56e9..e2dca87 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.0.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.0.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.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);`; }) .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/scripts/worker-e2e.mjs b/phaser-asteroids/server/scripts/worker-e2e.mjs index fb0cad3..7c1c70f 100644 --- a/phaser-asteroids/server/scripts/worker-e2e.mjs +++ b/phaser-asteroids/server/scripts/worker-e2e.mjs @@ -87,10 +87,10 @@ try { // --- challenge issuance ------------------------------------------------------------------------------------------------- const health = await api('GET', '/api/v1/health'); - check('health reports rules version', health.json?.rulesVersion === '1.0.0'); + check('health reports rules version', health.json?.rulesVersion === '1.1.0'); const probe = await api('POST', '/api/v1/runs', { body: JSON.stringify({ seed: 1, config: { playerCount: 2 } }), headers: { 'content-type': 'application/json' } }); check('POST /runs issues a challenge (201) with server-chosen seed and approved config', probe.status === 201 && probe.json.seed !== 1 && probe.json.config.playerCount === 1); - check('challenge carries id, secret token, rules version, expiry', !!probe.json.runId && probe.json.token?.length >= 40 && probe.json.rulesVersion === '1.0.0' && Date.parse(probe.json.expiresAt) > Date.now()); + check('challenge carries id, secret token, rules version, expiry', !!probe.json.runId && probe.json.token?.length >= 40 && probe.json.rulesVersion === '1.1.0' && Date.parse(probe.json.expiresAt) > Date.now()); // --- prepare several real games, all played against server-issued seeds ----------------------------------------------------- const honest = await playableRun(); diff --git a/phaser-asteroids/server/tests/harness.ts b/phaser-asteroids/server/tests/harness.ts index ca7d913..646901d 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); } -/** 2-minute game, score 9114 (the Phase 1 reference run). */ +/** Genuine reference game; combined experiments A+B under rules 1.1.0 produce 13959 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.0.0', s.completedAt - 60_000, s.completedAt + 3_600_000, s.completedAt, id], + params: [runId, s.rules ?? '1.1.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.0.0', s.visibility ?? 'visible'], + params: [id, runId, s.score, s.nickname ?? 'Tester', s.completedAt, s.rules ?? '1.1.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 8d3a31c..88236c1 100644 --- a/phaser-asteroids/server/tests/leaderboard.test.ts +++ b/phaser-asteroids/server/tests/leaderboard.test.ts @@ -108,7 +108,7 @@ describe('weekly leaderboard', () => { 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(9114); + expect(detail.body.score.score).toBe(13959); }); }); @@ -198,7 +198,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.0.0', schemaVersion: 1 }); + expect(res.body).toMatchObject({ ok: true, rulesVersion: '1.1.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 15c4df4..2e2e853 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.0.0'); + expect(run.rulesVersion).toBe('1.1.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.0.0'); + expect(res.body.rulesVersion).toBe('1.1.0'); }); it('issues unique ids, tokens and (practically) unique seeds', async () => { @@ -57,21 +57,23 @@ describe('submitting a legitimate run', () => { const h = makeHarness(); const run = await h.start({ seed: REFERENCE_SEED }); const bot = reference(); + expect(bot.gameOver).toBe(true); + expect(bot.ticks).toBeGreaterThan(60 * 60); // Exercises both earlier unlocks, without padding or changing the run. const res = await h.playAndSubmit(run, bot.replay, { nickname: 'Dave J', controls: { scheme: 'keyboard' } }); expect(res.status).toBe(200); expect(res.body.status).toBe('accepted'); expect(res.body.replayed).toBe(false); - expect(res.body.score.score).toBe(9114); + expect(res.body.score.score).toBe(13959); 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: 9114, ticks: bot.ticks, reported_controls: 'keyboard', visibility: 'visible', rules_version: '1.0.0' }); + expect(row).toMatchObject({ score: 13959, ticks: bot.ticks, reported_controls: 'keyboard', visibility: 'visible', rules_version: '1.1.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([9114]); + expect(board.body.entries.map((e: { score: number }) => e.score)).toEqual([13959]); }); it('ignores the score the client claims when it is not consistent, and never takes it as the score', async () => { @@ -82,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(9114); + expect(res.body.score.score).toBe(13959); }); }); @@ -118,9 +120,9 @@ describe('forged and invalid recordings are rejected', () => { 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 }); - await h.db.run("UPDATE runs SET rules_version = '0.9.0' WHERE id = ?", [run.runId]); + await h.db.run("UPDATE runs SET rules_version = '1.0.0' WHERE id = ?", [run.runId]); const bot = botRun(REFERENCE_SEED); - bot.replay.header.rulesVersion = '0.9.0'; + bot.replay.header.rulesVersion = '1.0.0'; const res = await h.playAndSubmit(run, bot.replay); expect(res.status).toBe(422); expect(res.body.error.reason).toBe('rules_mismatch'); @@ -226,7 +228,7 @@ describe('credentials, ownership and expiry', () => { const mine = await h.start({ seed: REFERENCE_SEED }); const theirs = await h.start({ seed: REFERENCE_SEED, ip: '198.51.100.9' }); const bot = reference(); - h.clock.advance(200_000); + h.clock.advance(bot.ticks / 60 * 1000 + 1500); expect((await h.submit(theirs, bot.replay, { token: mine.token })).status).toBe(401); expect((await h.submit(theirs, bot.replay, { token: null })).status).toBe(401); expect(await count(h.db, 'scores')).toBe(0); @@ -283,7 +285,7 @@ describe('one-use runs', () => { const h = makeHarness(); const run = await h.start({ seed: REFERENCE_SEED }); const bot = reference(); - h.clock.advance(200_000); + h.clock.advance(bot.ticks / 60 * 1000 + 1500); const results = await Promise.all(Array.from({ length: 12 }, () => h.submit(run, bot.replay, { nickname: 'Racer' }))); const ok = results.filter((r) => r.status === 200); expect(ok.length).toBeGreaterThanOrEqual(1); @@ -297,7 +299,7 @@ describe('one-use runs', () => { const h = makeHarness(); const run = await h.start({ seed: REFERENCE_SEED }); const bot = reference(); - h.clock.advance(200_000); + h.clock.advance(bot.ticks / 60 * 1000 + 1500); const results = await Promise.all(['Alpha', 'Bravo', 'Charlie', 'Delta', 'Echo'].map((n) => h.submit(run, bot.replay, { nickname: n }))); expect(results.filter((r) => r.status === 200).length).toBe(1); expect(await count(h.db, 'scores')).toBe(1); @@ -314,7 +316,7 @@ describe('one-use runs', () => { try { const run = await instances[0]!.start({ seed: REFERENCE_SEED }); const bot = reference(); - clock.advance(200_000); + clock.advance(bot.ticks / 60 * 1000 + 1500); const results = await Promise.all( Array.from({ length: 16 }, (_, i) => instances[i % 4]!.submit(run, bot.replay, { nickname: `Inst${i % 4}` })), ); @@ -332,7 +334,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.0.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.1.0', 1, 1)`, [run.runId]), ).rejects.toThrow(); }); }); @@ -379,7 +381,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(9114); + expect(res.body.score.score).toBe(13959); }); it('truncated gzip and corrupt gzip -> 400, run not consumed', async () => { @@ -405,7 +407,7 @@ describe('request size and encoding limits', () => { const run = await h.start({ seed: REFERENCE_SEED }); const bot = reference(); const json = JSON.stringify({ replay: bot.replay }); - h.clock.advance(200_000); + h.clock.advance(bot.ticks / 60 * 1000 + 1500); for (const rawBody of [json.slice(0, json.length - 40), 'not json', '[]', '{}', '{"replay": 5}', '{"replay": []}', '']) { const res = await h.submit(run, null, { rawBody }); expect([400]).toContain(res.status); @@ -420,7 +422,7 @@ describe('nicknames', () => { const h = makeHarness(); const run = await h.start({ seed: REFERENCE_SEED }); const bot = reference(); - h.clock.advance(200_000); + h.clock.advance(bot.ticks / 60 * 1000 + 1500); for (const nickname of ['ab', 'x'.repeat(17), '', 'a { const h = makeHarness({ settings: { rate: { ...makeHarness().settings.rate, submitPerIp: 2 } } }); const run = await h.start({ seed: REFERENCE_SEED }); const bot = reference(); - h.clock.advance(200_000); + h.clock.advance(bot.ticks / 60 * 1000 + 1500); await h.submit(run, bot.replay, { token: 'bad' }); await h.submit(run, bot.replay, { token: 'bad' }); const res = await h.submit(run, bot.replay); diff --git a/phaser-asteroids/src/audio/phaserAudio.ts b/phaser-asteroids/src/audio/phaserAudio.ts index 8614cc4..3fa8c28 100644 --- a/phaser-asteroids/src/audio/phaserAudio.ts +++ b/phaser-asteroids/src/audio/phaserAudio.ts @@ -23,13 +23,13 @@ type Sound = Phaser.Sound.BaseSoundManager; class PhaserSfxBackend implements SfxBackend { constructor(private readonly manager: Sound) {} - play(key: SfxKey, volume: number, onFinished: () => void): PlayingSound | null { + play(key: SfxKey, volume: number, onFinished: () => void, rate = 1): PlayingSound | null { // While the browser's autoplay lock is on, Phaser would queue the sound and replay it as a burst on // unlock. A shot that nobody could hear is better dropped. if (this.manager.locked) return null; if (!this.manager.game.cache.audio.exists(key)) return null; try { - const sound = this.manager.add(key, { volume }); + const sound = this.manager.add(key, { volume, rate }); let done = false; const finish = (): void => { if (done) return; diff --git a/phaser-asteroids/src/audio/sfxPlayer.ts b/phaser-asteroids/src/audio/sfxPlayer.ts index 3cea657..83b53c6 100644 --- a/phaser-asteroids/src/audio/sfxPlayer.ts +++ b/phaser-asteroids/src/audio/sfxPlayer.ts @@ -19,6 +19,7 @@ import { clampVolume } from './audioSettings'; export interface SoundCue { key: SfxKey; volume: number; + rate?: number; } const SHOOT_KEYS: readonly SfxKey[] = ['shoot_low', 'shoot_mid', 'shoot_high']; @@ -43,9 +44,13 @@ export function cueForEvent(event: SimEvent, rng: Rng): SoundCue | null { return { key, volume: SFX_GAIN[key] }; } case 'asteroid_destroyed': { + if (event.volatile) return null; // its dedicated blast cue replaces the ordinary breakup sound const key = explosionKey(event.radius); return { key, volume: SFX_GAIN[key] }; } + 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 'ufo_destroyed': { const key = explosionKey(event.radius); return { key, volume: SFX_GAIN[key] * UFO_EXPLOSION_GAIN_SCALE }; @@ -68,7 +73,7 @@ export interface PlayingSound { /** What the player needs from the audio engine. Returns null when the sound could not be started. */ export interface SfxBackend { - play(key: SfxKey, volume: number, onFinished: () => void): PlayingSound | null; + play(key: SfxKey, volume: number, onFinished: () => void, rate?: number): PlayingSound | null; } export interface SfxPlayerOptions { @@ -187,7 +192,7 @@ export class SfxPlayer { handle = this.backend.play(cue.key, volume, () => { finished = true; if (handle) voices.delete(handle); - }); + }, cue.rate); if (!handle) return; 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 c2061da..282ef6d 100644 --- a/phaser-asteroids/src/core/constants.ts +++ b/phaser-asteroids/src/core/constants.ts @@ -34,15 +34,15 @@ export const ASTEROID_ARCHETYPES: Record = { /** Seconds of play before each archetype can spawn (continuous mode). */ export const ASTEROID_ARCHETYPE_TIME_UNLOCKS: Record = { standard: 0, - armored: 45, - volatile: 120, + armored: 25, + volatile: 60, }; -/** Volatile has weight 0 in the original, so it never spawns. */ +/** Relative weights among unlocked archetypes; volatile remains uncommon. */ export const ASTEROID_ARCHETYPE_SPAWN_WEIGHTS: Record = { standard: 1.0, armored: 0.35, - volatile: 0.0, + volatile: 0.12, }; export const ASTEROID_ARMORED_HIT_FLASH_DURATION = 0.12; @@ -52,6 +52,10 @@ export const ASTEROID_DEATH_DURATION = 0.15; export const ASTEROID_DEATH_DURATION_MAX = 0.15; export const ASTEROID_SHAKE_INTENSITY = 3; +/** Volatile blasts hit asteroid collision circles touching this radius; ships and UFOs are excluded. */ +export const VOLATILE_EXPLOSION_RADIUS = 110; +export const VOLATILE_EXPLOSION_SHAKE = 6; + export const POINTS_LARGE_ASTEROID = 10; export const POINTS_MEDIUM_ASTEROID = 20; export const POINTS_SMALL_ASTEROID = 50; @@ -99,7 +103,7 @@ export const FRIENDLY_FIRE_DEFAULT = true; export const REVIVE_LIVES = 3; /** * Python defines `REVIVE_SPAWN_CHANCE` = 0.3 ("30 % chance to spawn revive when a player dies") but never uses it, so no - * Revive ever appeared. Here it is the share of power-up drops (an asteroid's 8 % roll and the guaranteed UFO drop) that + * Revive ever appeared. Here it is the share of ordinary power-up drops (and the guaranteed UFO drop) that * turn into a Revive while a player is out of lives and their teammate is still alive and no Revive is already on the field. */ export const REVIVE_SPAWN_CHANCE = 0.3; @@ -119,7 +123,7 @@ export const POWERUP_LIFETIME = 12.0; // seconds before an uncollected pickup di export const REVIVE_LIFETIME = 15.0; export const POWERUP_SPEED = 30; // px/s drift /** Chance that a destroyed asteroid drops one of the four ordinary power-ups. */ -export const POWERUP_SPAWN_CHANCE = 0.08; +export const POWERUP_SPAWN_CHANCE = 0.12; /** Checked first; a successful roll drops MEGA POWER instead. */ export const MEGA_POWER_SPAWN_CHANCE = 0.015; @@ -203,6 +207,7 @@ export const UFO_SMALL_SPAWN_CHANCE = 0.4; * asteroids faster. Each row is "from this difficulty level on, a UFO spawn is small with this probability" (the highest * row reached wins; before the first row every spawn is a large UFO and no random number is drawn). * + * level 2 (1:00) 10 % - an occasional early small UFO * level 4 (2:00) 20 % - the odd small UFO * level 8 (4:00) 40 % - the rate Python uses from wave 5 * level 12 (6:00) 60 % - small UFOs are now the more likely spawn @@ -211,6 +216,7 @@ export const UFO_SMALL_SPAWN_CHANCE = 0.4; * the original "large only" behaviour. */ export const UFO_SMALL_PROGRESSION: ReadonlyArray<{ readonly level: number; readonly chance: number }> = [ + { level: 2, chance: 0.1 }, { level: 4, chance: 0.2 }, { level: 8, chance: 0.4 }, { level: 12, chance: 0.6 }, diff --git a/phaser-asteroids/src/core/game.ts b/phaser-asteroids/src/core/game.ts index d239fd4..d3e61f0 100644 --- a/phaser-asteroids/src/core/game.ts +++ b/phaser-asteroids/src/core/game.ts @@ -29,6 +29,8 @@ import { UFO_DESTROY_PARTICLES, UFO_DESTROY_SHAKE, UFO_SHIELD_CONTACT_GRACE, + VOLATILE_EXPLOSION_RADIUS, + VOLATILE_EXPLOSION_SHAKE, } from './constants'; import { beginDeath, @@ -107,7 +109,8 @@ export type SimEvent = * to `player` (absent when nobody was paid). `combo` / `multiplier` are present when it was a kill that counted * towards the combo. */ - | { type: 'asteroid_destroyed'; radius: number; points: number; combo?: number; multiplier?: number; player?: number } + | { 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: 'asteroid_hit'; position: Vec2 } | { type: 'powerup_dropped'; powerType: PowerUpType } | { type: 'powerup_collected'; powerType: PowerUpType; player?: number } @@ -138,6 +141,22 @@ export interface PickupFlash { } export const PICKUP_FLASH_DURATION = 0.4; +/** Presentation only: negative age briefly staggers chain rings, never their damage. No RNG is used. */ +export interface VolatileFlash { + position: Vec2; + radius: number; + depth: number; + age: number; +} +export const VOLATILE_FLASH_DURATION = 0.32; +export const VOLATILE_FLASH_LIMIT = 32; + +interface VolatileBlast { + position: Vec2; + scorer: PlayerState | null; + depth: number; +} + export interface GameSimOptions { rng?: Rng; /** Overrides the "no shooting right after starting" grace period (mainly for tests). */ @@ -178,6 +197,7 @@ export class GameSim { ufoShots: UfoShot[] = []; lasers: LaserBeam[] = []; pickupFlashes: PickupFlash[] = []; + volatileFlashes: VolatileFlash[] = []; readonly particles = new ParticleSystem(); readonly starfield: Starfield; readonly spawner: SpawnerState = createSpawner(); @@ -314,6 +334,7 @@ export class GameSim { // Entities freeze, but explosion particles finish and the retry countdown runs. this.retryDelay = Math.max(0, this.retryDelay - dt); this.particles.update(dt); + this.updateVolatileFlashes(dt); } private substep(dt: number, inputs: readonly PlayerInput[]): void { @@ -332,6 +353,7 @@ export class GameSim { } private updateTimers(dt: number): void { + this.updateVolatileFlashes(dt); if (this.startCooldown > 0) this.startCooldown -= dt; this.time += dt; this.difficultyTimer += dt; @@ -749,7 +771,9 @@ export class GameSim { * (flash + sparks, no points); a kill scores, starts the death animation and may drop a power-up. * `scorer` is the player credited (null for UFO shots, which pay nobody). */ - private hitAsteroid(asteroid: Asteroid, scorer: PlayerState | null): void { + private hitAsteroid(asteroid: Asteroid, scorer: PlayerState | null, blasts?: VolatileBlast[], depth = 0): void { + // Keep the guard at the damage/score boundary as well as in collision callers. + if (!asteroid.alive || asteroid.dying) return; const result = takeHit(asteroid); if (!result.destroyed) { this.applyEffect(result.effect, 1); @@ -762,13 +786,15 @@ export class GameSim { const points = scorer ? scaledPoints(getPoints(asteroid), credit.multiplier) : 0; if (scorer) scorer.score += points; const drop = maybeSpawnPowerUp(asteroid.position.x, asteroid.position.y, this.rng, this.reviveEligible); - this.applyEffect(beginDeath(asteroid), 1); + const effect = beginDeath(asteroid); + if (asteroid.archetype !== 'volatile') this.applyEffect(effect, 1); this.events.push({ type: 'asteroid_destroyed', radius: asteroid.radius, points, combo: credit.count, multiplier: credit.multiplier, + ...(asteroid.archetype === 'volatile' ? { volatile: true } : {}), ...(scorer ? { player: scorer.playerNumber } : {}), }); @@ -780,6 +806,7 @@ export class GameSim { this.powerups.push(drop); this.events.push({ type: 'powerup_dropped', powerType: drop.type }); } + this.detonateVolatile(asteroid, scorer, blasts, depth); } /** @@ -807,9 +834,44 @@ export class GameSim { } private destroyWithoutScore(asteroid: Asteroid, shakeScale: number): void { + if (!asteroid.alive || asteroid.dying) return; const effect = beginDeath(asteroid); - this.applyEffect(effect, shakeScale); - if (effect) this.events.push({ type: 'asteroid_destroyed', radius: asteroid.radius, points: 0 }); + const volatile = asteroid.archetype === 'volatile'; + if (!volatile) this.applyEffect(effect, shakeScale); + if (effect) this.events.push({ type: 'asteroid_destroyed', radius: asteroid.radius, points: 0, ...(volatile ? { volatile: true } : {}) }); + this.detonateVolatile(asteroid, null); + } + + /** + * Breadth-first, synchronous damage in stable asteroid-list order. A nested kill only appends to the queue. + * beginDeath has already marked each source dying, so it can be queued once and cannot be paid again. + * Children appear after the usual death delay, outside this snapshot and this blast's lifetime. + */ + private detonateVolatile(asteroid: Asteroid, scorer: PlayerState | null, pending?: VolatileBlast[], depth = 0): void { + if (asteroid.archetype !== 'volatile') return; + const blasts = pending ?? []; + blasts.push({ position: { ...asteroid.position }, scorer, depth }); + if (pending) return; + + const targets = this.asteroids.slice(); + for (let i = 0; i < blasts.length; i++) { + const blast = blasts[i]!; + const radius = VOLATILE_EXPLOSION_RADIUS; + this.volatileFlashes.push({ position: { ...blast.position }, radius, depth: blast.depth, age: -Math.min(blast.depth, 4) * 0.025 }); + if (this.volatileFlashes.length > VOLATILE_FLASH_LIMIT) this.volatileFlashes.shift(); + this.events.push({ type: 'volatile_exploded', position: { ...blast.position }, radius, depth: blast.depth }); + this.addScreenShake(VOLATILE_EXPLOSION_SHAKE); + // Visit each original target once per blast. Distinct blasts may each strip one armor hit. + for (const target of targets) { + if (!target.alive || target.dying || !circlesOverlap({ position: blast.position, radius }, target)) continue; + this.hitAsteroid(target, blast.scorer, blasts, blast.depth + 1); + } + } + } + + private updateVolatileFlashes(dt: number): void { + for (const flash of this.volatileFlashes) flash.age += dt; + this.volatileFlashes = this.volatileFlashes.filter((flash) => flash.age < VOLATILE_FLASH_DURATION); } private applyEffect(effect: DeathEffect | null, shakeScale: number): void { diff --git a/phaser-asteroids/src/core/powerup.ts b/phaser-asteroids/src/core/powerup.ts index fb779c9..03b5a25 100644 --- a/phaser-asteroids/src/core/powerup.ts +++ b/phaser-asteroids/src/core/powerup.ts @@ -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 an 8 % chance of one of the four ordinary power-ups, chosen uniformly (~9.4 % overall). + * otherwise a 12 % chance of one of the four 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 8 % 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 four 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/scoring.ts b/phaser-asteroids/src/core/scoring.ts index 9050abf..4db7e51 100644 --- a/phaser-asteroids/src/core/scoring.ts +++ b/phaser-asteroids/src/core/scoring.ts @@ -10,7 +10,7 @@ import { * Combo and kill-streak bookkeeping, ported from the Python `collisions.py` / `gamestate.py` / `killstreak.py`. * * What counts as a kill (each one advances the combo by exactly one and is scored at the new multiplier): - * an asteroid that is actually destroyed by a player shot, a Laser Beam hit, a boost ram, or a UFO shot. + * an asteroid that is actually destroyed by a player shot, a Laser Beam hit, a boost ram, a UFO shot or a volatile blast. * It does NOT count: a non-lethal armored hit, an asteroid that crashes into the ship (shielded or not), or a UFO * (UFOs pay a flat 200 / 500). The combo is only reset by its 3 s timer or a new game, never by losing a life. */ diff --git a/phaser-asteroids/src/core/ufo.ts b/phaser-asteroids/src/core/ufo.ts index 1b3e8cc..8bc949b 100644 --- a/phaser-asteroids/src/core/ufo.ts +++ b/phaser-asteroids/src/core/ufo.ts @@ -237,7 +237,7 @@ export function chooseContinuousUfoType(difficultyLevel: number, rng: Rng): UfoT * The UFO appears on a random edge, 20-80 % along it, exactly as far outside the screen as an asteroid spawn * (Python reuses the asteroid edge table), so it spends a moment wrapping from side to side before it flies in. * Neither difficulty scaling nor Slow Motion affects the timing. The *type* does follow the difficulty level: large UFOs - * only at first, small ones from level 4 on and more and more often (`UFO_SMALL_PROGRESSION`). + * only at first, small ones from level 2 on and more and more often (`UFO_SMALL_PROGRESSION`). */ export function updateUfoSpawner( state: UfoSpawnerState, diff --git a/phaser-asteroids/src/render/worldRenderer.ts b/phaser-asteroids/src/render/worldRenderer.ts index 5c0d624..8503100 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, type GameSim } from '../core/game'; +import { 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'; @@ -219,5 +219,27 @@ export function drawWorld(g: Graphics, sim: GameSim, timeMs: number): void { g.fillCircle(p.x, p.y, Math.max(1, p.size * fade)); } + // A few procedural strokes per blast, with no textures, emitters or gameplay RNG. + // Each source has its own ring; chain depth staggers/rotates the sparks for readable overlapping blasts. + for (const flash of sim.volatileFlashes) { + if (flash.age < 0) continue; + const t = flash.age / VOLATILE_FLASH_DURATION; + const fade = 1 - t; + const { x, y } = flash.position; + const radius = 8 + (flash.radius - 8) * (1 - fade * fade); + g.lineStyle(5 * fade + 1, 0xff8a24, fade * 0.45); + g.strokeCircle(x, y, radius); + g.lineStyle(2, 0xffe477, fade); + g.strokeCircle(x, y, radius * 0.94); + for (let i = 0; i < 12; i++) { + const angle = i * Math.PI / 6 + flash.depth * 0.7; + const distance = (12 + 100 * t) * (0.7 + (i % 3) * 0.15); + const dx = Math.cos(angle); + const dy = Math.sin(angle); + g.lineStyle(2, i % 2 ? 0xffa52a : 0xffee99, fade * fade); + g.lineBetween(x + dx * distance, y + dy * distance, x + dx * (distance + 9 * fade), y + dy * (distance + 9 * 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 0394a97..a9c7c9a 100644 --- a/phaser-asteroids/src/replay/constants.ts +++ b/phaser-asteroids/src/replay/constants.ts @@ -4,8 +4,8 @@ export const REPLAY_SCHEMA_VERSION = 1; -/** Semantic rules version defining physics, collision, and scoring rules. */ -export const GAMEPLAY_RULES_VERSION = '1.0.0'; +/** Semantic rules version defining simulation outcomes, including spawn/drop balance. */ +export const GAMEPLAY_RULES_VERSION = '1.1.0'; /** Authoritative simulation tick rate in Hz. */ export const FIXED_TICK_RATE = 60; diff --git a/phaser-asteroids/tests/asteroid.test.ts b/phaser-asteroids/tests/asteroid.test.ts index be46af3..c8e97d2 100644 --- a/phaser-asteroids/tests/asteroid.test.ts +++ b/phaser-asteroids/tests/asteroid.test.ts @@ -34,6 +34,10 @@ describe('asteroid sizes and scoring', () => { [60, 'armored', 25], [40, 'armored', 40], [20, 'armored', 85], + // Volatile points remain int(base * 1.75 + 20); blast kills use the same formula. + [60, 'volatile', 37], + [40, 'volatile', 55], + [20, 'volatile', 107], ] as const)('radius %i %s asteroid is worth %i points', (radius, archetype, points) => { expect(getPoints(createAsteroid(0, 0, radius, archetype))).toBe(points); }); diff --git a/phaser-asteroids/tests/boost.test.ts b/phaser-asteroids/tests/boost.test.ts index 841d599..4ae7466 100644 --- a/phaser-asteroids/tests/boost.test.ts +++ b/phaser-asteroids/tests/boost.test.ts @@ -145,7 +145,7 @@ describe('boost ramming', () => { it('can drop power-ups like any other kill', () => { const sim = boostSim(); - // Force the next drop roll: not mega, under 8%, and pick index 0 (rapid fire). + // Force the next drop roll: not mega, under 12%, and pick index 0 (rapid fire). const asteroid = rock(PLAYER_START_X + 30, PLAYER_START_Y, 60); sim.asteroids.push(asteroid); const rolls = [0.5, 0.01, 0.0]; diff --git a/phaser-asteroids/tests/powerup.test.ts b/phaser-asteroids/tests/powerup.test.ts index c944133..7c7e8cb 100644 --- a/phaser-asteroids/tests/powerup.test.ts +++ b/phaser-asteroids/tests/powerup.test.ts @@ -27,23 +27,23 @@ describe('power-up drops', () => { expect(maybeSpawnPowerUp(100, 100, rng)?.type).toBe('mega_power'); }); - it('otherwise a roll under 8% drops one of the four ordinary types, picked uniformly', () => { + it('otherwise a roll under 12% drops one of the four ordinary types, picked uniformly', () => { const types = []; for (const pick of [0.0, 0.26, 0.51, 0.76]) { const rng = queueRng(); - rng.queue(0.5 /* not mega */, 0.0799 /* drops */, pick /* which one */); + 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']); }); - it('does not drop on a roll of 8% or more', () => { + it('does not drop on a roll of 12% or more', () => { const rng = queueRng(); - rng.queue(0.5, 0.08); + rng.queue(0.5, 0.12); expect(maybeSpawnPowerUp(0, 0, rng)).toBeNull(); }); - it('never drops Revive, and matches the original odds over many rolls (~9.4% overall, 1.5% mega)', () => { + it('never drops Revive, and matches the experimental odds over many rolls (~13.3% overall, 1.5% mega)', () => { const rng = seededRng(42); const counts: Record = {}; const n = 200_000; @@ -52,11 +52,11 @@ describe('power-up drops', () => { if (drop) counts[drop.type] = (counts[drop.type] ?? 0) + 1; } const total = Object.values(counts).reduce((a, b) => a + b, 0); - expect(total / n).toBeCloseTo(0.015 + 0.985 * 0.08, 2); + 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.08) / 4, 2); + expect((counts[t] ?? 0) / n).toBeCloseTo((0.985 * 0.12) / 4, 2); } }); }); diff --git a/phaser-asteroids/tests/ranked.test.ts b/phaser-asteroids/tests/ranked.test.ts index 7e45468..2846fb4 100644 --- a/phaser-asteroids/tests/ranked.test.ts +++ b/phaser-asteroids/tests/ranked.test.ts @@ -29,7 +29,7 @@ const challenge: RankedChallenge = { runId: '11111111-1111-4111-8111-111111111111', token: 't'.repeat(43), seed: 123456, - rulesVersion: '1.0.0', + rulesVersion: '1.1.0', schemaVersion: 1, tickRate: 60, config: { playerCount: 1, livesMode: 'independent', friendlyFire: false, speed: [1, 1] }, @@ -99,6 +99,7 @@ describe('requestChallenge', () => { await expect(requestChallenge('http://x', async () => reply(503, {}))).rejects.toMatchObject({ code: 'unavailable' }); }); it('refuses a challenge for different rules, an unsupported config or an implausible limit', async () => { + await expect(requestChallenge('http://x', async () => reply(201, { ...challenge, rulesVersion: '1.0.0' }))).rejects.toMatchObject({ code: 'update_required' }); await expect(requestChallenge('http://x', async () => reply(201, { ...challenge, rulesVersion: '2.0.0' }))).rejects.toMatchObject({ code: 'update_required' }); await expect(requestChallenge('http://x', async () => reply(201, { ...challenge, config: { ...challenge.config, playerCount: 2 } }))).rejects.toBeInstanceOf(RankedApiError); await expect(requestChallenge('http://x', async () => reply(201, { ...challenge, seed: -1 }))).rejects.toMatchObject({ code: 'bad_challenge' }); @@ -414,7 +415,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 page = (over: Record = {}) => ({ scope: 'weekly', rulesVersion: '1.0.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 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 () => { let url = ''; diff --git a/phaser-asteroids/tests/refinements.test.ts b/phaser-asteroids/tests/refinements.test.ts index 3198e91..75d213a 100644 --- a/phaser-asteroids/tests/refinements.test.ts +++ b/phaser-asteroids/tests/refinements.test.ts @@ -128,14 +128,16 @@ describe('0B: small UFOs are introduced gradually in continuous mode', () => { expect(sim.asteroidSpeedMultiplier).toBeCloseTo(1.6, 9); }); - it('documented thresholds: 0 % before 2:00, 20 % from 2:00, 40 % from 4:00, 60 % from 6:00', () => { + it('documented thresholds: 0 % before 1:00, then 10 / 20 / 40 / 60 % at 1 / 2 / 4 / 6 minutes', () => { expect(UFO_SMALL_PROGRESSION).toEqual([ + { level: 2, chance: 0.1 }, { level: 4, chance: 0.2 }, { level: 8, chance: 0.4 }, { level: 12, chance: 0.6 }, ]); const at = (seconds: number): number => smallUfoChance(Math.floor(seconds / DIFFICULTY_INCREASE_INTERVAL)); - expect([0, 29, 60, 119].map(at)).toEqual([0, 0, 0, 0]); + expect([0, 29, 59.999].map(at)).toEqual([0, 0, 0]); + expect([60, 90, 119.999].map(at)).toEqual([0.1, 0.1, 0.1]); expect([120, 200, 239].map(at)).toEqual([0.2, 0.2, 0.2]); expect([240, 300, 359].map(at)).toEqual([0.4, 0.4, 0.4]); expect([360, 600, 3600].map(at)).toEqual([0.6, 0.6, 0.6]); @@ -144,13 +146,15 @@ describe('0B: small UFOs are introduced gradually in continuous mode', () => { it('draws no random number while the chance is zero, so early games are exactly as before', () => { let draws = 0; const counting = (): number => (draws++, 0); - for (let level = 0; level < 4; level++) expect(chooseContinuousUfoType(level, counting)).toBe('large'); + for (let level = 0; level < 2; level++) expect(chooseContinuousUfoType(level, counting)).toBe('large'); expect(draws).toBe(0); expect(chooseContinuousUfoType(4, counting)).toBe('small'); expect(draws).toBe(1); }); it('the roll is deterministic under a controlled RNG: small exactly below the chance', () => { + expect(chooseContinuousUfoType(2, () => 0.0999)).toBe('small'); + expect(chooseContinuousUfoType(2, () => 0.1)).toBe('large'); expect(chooseContinuousUfoType(4, () => 0.19)).toBe('small'); expect(chooseContinuousUfoType(4, () => 0.2)).toBe('large'); expect(chooseContinuousUfoType(8, () => 0.39)).toBe('small'); @@ -159,7 +163,7 @@ describe('0B: small UFOs are introduced gradually in continuous mode', () => { expect(chooseContinuousUfoType(12, () => 0.6)).toBe('large'); }); - it('measured over many spawns the shares are about 0 / 20 / 40 / 60 %', () => { + it('measured over many spawns the shares are about 0 / 10 / 20 / 40 / 60 %', () => { const share = (level: number): number => { const rng = seededRng(77); let small = 0; @@ -167,7 +171,9 @@ describe('0B: small UFOs are introduced gradually in continuous mode', () => { for (let i = 0; i < n; i++) if (chooseContinuousUfoType(level, rng) === 'small') small++; return small / n; }; - expect(share(3)).toBe(0); + expect(share(1)).toBe(0); + expect(share(2)).toBeGreaterThan(0.07); + expect(share(2)).toBeLessThan(0.13); expect(share(4)).toBeGreaterThan(0.17); expect(share(4)).toBeLessThan(0.23); expect(share(8)).toBeGreaterThan(0.37); @@ -194,7 +200,7 @@ describe('0B: small UFOs are introduced gradually in continuous mode', () => { expect(updateUfoSpawner(state, 5, 0, seededRng(1))?.type).toBe('large'); }); - it('in a real run no small UFO appears before 2:00 and some do afterwards', () => { + it('in a real run no small UFO appears before 1:00 and some do afterwards', () => { const sim = new GameSim({ rng: seededRng(9), startCooldown: 0 }); sim.spawner.spawnTimer = -1e9; sim.player.lives = 999; @@ -204,7 +210,7 @@ describe('0B: small UFOs are introduced gradually in continuous mode', () => { sim.ufos.length = 0; } expect(first['large']).toBeLessThan(6); - expect(first['small']).toBeGreaterThanOrEqual(120); + expect(first['small']).toBeGreaterThanOrEqual(60); }); }); diff --git a/phaser-asteroids/tests/spawner.test.ts b/phaser-asteroids/tests/spawner.test.ts index ca11ec4..e8b2631 100644 --- a/phaser-asteroids/tests/spawner.test.ts +++ b/phaser-asteroids/tests/spawner.test.ts @@ -87,27 +87,50 @@ describe('spawn timing', () => { }); describe('archetypes', () => { - it('only standard asteroids exist before 45 s', () => { + it('only standard asteroids exist before 25 s', () => { expect(availableArchetypes(0)).toEqual(['standard']); - expect(availableArchetypes(44.9)).toEqual(['standard']); + expect(availableArchetypes(24.999)).toEqual(['standard']); }); - it('armored asteroids unlock at 45 s; volatile never spawns (weight 0)', () => { - expect(availableArchetypes(45)).toEqual(['standard', 'armored']); - expect(availableArchetypes(10_000)).toEqual(['standard', 'armored']); + it('armored unlocks at 25 s and volatile at 60 s', () => { + expect(availableArchetypes(25)).toEqual(['standard', 'armored']); + expect(availableArchetypes(59.999)).toEqual(['standard', 'armored']); + expect(availableArchetypes(60)).toEqual(['standard', 'armored', 'volatile']); + expect(availableArchetypes(10_000)).toEqual(['standard', 'armored', 'volatile']); }); it('armored makes up about 0.35 / 1.35 of spawns once unlocked', () => { const rng = seededRng(8); let armored = 0; const n = 20_000; - for (let i = 0; i < n; i++) if (chooseArchetype(60, rng) === 'armored') armored++; + for (let i = 0; i < n; i++) if (chooseArchetype(30, rng) === 'armored') armored++; expect(armored / n).toBeCloseTo(0.35 / 1.35, 1); }); it('never picks armored before it unlocks', () => { const rng = seededRng(8); - for (let i = 0; i < 2000; i++) expect(chooseArchetype(30, rng)).toBe('standard'); + for (let i = 0; i < 2000; i++) expect(chooseArchetype(24.999, rng)).toBe('standard'); + }); + + it('volatile takes its modest normalized share only after unlocking', () => { + const rng = seededRng(83); + let volatile = 0; + const n = 20_000; + for (let i = 0; i < n; i++) if (chooseArchetype(60, rng) === 'volatile') volatile++; + expect(volatile / n).toBeCloseTo(0.12 / 1.47, 2); + }); + + it('a volatile large asteroid can spawn and enter the field using the existing edge behavior', () => { + const rng = seededRng(21); + let found: Asteroid | undefined; + for (let i = 0; i < 200 && !found; i++) { + const candidate = spawnEdgeAsteroid(60, rng); + if (candidate.archetype === 'volatile' && candidate.radius === 60) found = candidate; + } + expect(found).toBeDefined(); + expect(found!.hitPoints).toBe(1); + updateAsteroid(found!, 1 / 60, 1 / 60, rng); + expect(found!.alive).toBe(true); }); }); diff --git a/phaser-asteroids/tests/ufo.test.ts b/phaser-asteroids/tests/ufo.test.ts index 31ffe89..ba2f9fe 100644 --- a/phaser-asteroids/tests/ufo.test.ts +++ b/phaser-asteroids/tests/ufo.test.ts @@ -384,12 +384,12 @@ describe('UFO spawning', () => { expect(more).toBe(1); }); - it('continuous mode: only large UFOs for the first two minutes, then small ones join in (see UFO_SMALL_PROGRESSION)', () => { + it('continuous mode: only large UFOs before 60 s, then small ones become eligible', () => { const sim = schedulerSim(21); const early = new Set(); const late = new Set(); - for (let i = 0; i < 60 * 600; i++) { - for (const e of eventsOfType(sim.step(FRAME), 'ufo_spawned')) (sim.time < 120 ? early : late).add(e.ufoType); + for (let i = 0; i < 60 * 120; i++) { + for (const e of eventsOfType(sim.step(FRAME), 'ufo_spawned')) (sim.time < 60 ? early : late).add(e.ufoType); sim.ufos.length = 0; } expect([...early]).toEqual(['large']); diff --git a/phaser-asteroids/tests/volatileExplosion.test.ts b/phaser-asteroids/tests/volatileExplosion.test.ts new file mode 100644 index 0000000..c9cb0ee --- /dev/null +++ b/phaser-asteroids/tests/volatileExplosion.test.ts @@ -0,0 +1,152 @@ +import { describe, expect, it } from 'vitest'; +import { cueForEvent, SfxPlayer } from '../src/audio/sfxPlayer'; +import { VOLATILE_EXPLOSION_RADIUS, VOLATILE_EXPLOSION_SHAKE } from '../src/core/constants'; +import { GameSim, VOLATILE_FLASH_LIMIT } from '../src/core/game'; +import { NO_INPUT } from '../src/core/player'; +import { seededRng } from '../src/core/rng'; +import { FIXED_DT, GAMEPLAY_RULES_VERSION } from '../src/replay/constants'; +import { ReplayRecorder } from '../src/replay/recorder'; +import { captureSimSnapshot } from '../src/replay/snapshot'; +import { loadSettings, RANKED_CONFIG } from '../server/src/config'; +import { verifyRankedReplay } from '../server/src/verify'; +import { FakeBackend } from './audioFakes'; +import { eventsOfType, FRAME, parkedUfoFor, quietCoop, quietSim, rock, runFor, shotAt, shotBy, ufoShotAt } from './helpers'; + +describe('volatile blasts', () => { + it('detonates once, touches collision radii, applies one armor hit, and spares ships/UFOs', () => { + const sim = quietSim(); + sim.player.position = { x: 300, y: 330 }; // within the blast, outside body contact + sim.player.isRespawning = false; + const ufo = parkedUfoFor(sim, 'large', 300, 190); + const source = rock(300, 250, 20, 'volatile'); + const edge = rock(300 + VOLATILE_EXPLOSION_RADIUS + 20, 250, 20); + const outside = rock(edge.position.x + 1, 250, 20); + const armor = rock(330, 280, 20, 'armored'); + const worn = rock(270, 280, 20, 'armored'); + worn.hitPoints = 1; + sim.asteroids.push(source, edge, outside, armor, worn); + sim.shots.push(shotAt(300, 250), shotAt(300, 250)); + + const events = sim.step(FRAME); + expect(source.dying).toBe(true); + expect(edge.dying).toBe(true); + expect(outside.dying).toBe(false); + expect(armor.hitPoints).toBe(1); + expect(armor.dying).toBe(false); + expect(worn.dying).toBe(true); + expect(eventsOfType(events, 'asteroid_hit')).toHaveLength(1); + expect(eventsOfType(events, 'asteroid_destroyed')).toHaveLength(3); + const blasts = eventsOfType(events, 'volatile_exploded'); + expect(blasts).toEqual([{ type: 'volatile_exploded', position: { x: 300, y: 250 }, radius: 110, depth: 0 }]); + expect(sim.player.lives).toBe(3); + expect(sim.player.isRespawning).toBe(false); + expect(ufo.alive).toBe(true); + expect(sim.screenShake).toBe(VOLATILE_EXPLOSION_SHAKE); + expect(cueForEvent(blasts[0]!, seededRng(1))).toMatchObject({ key: 'explosion_large', rate: 0.8 }); + expect(cueForEvent(eventsOfType(events, 'asteroid_destroyed')[0]!, seededRng(1))).toBeNull(); + expect(eventsOfType(sim.step(FRAME), 'volatile_exploded')).toHaveLength(0); + expect(armor.hitPoints).toBe(1); // the lingering ring does no damage + }); + + it('resolves a cyclic chain in stable breadth-first order, paying player 2 at existing combo multipliers', () => { + const sim = quietCoop(); + sim.asteroids.push(rock(300, 200, 20, 'volatile'), rock(420, 200, 20, 'volatile'), + rock(420, 320, 20, 'volatile'), rock(300, 320, 20, 'volatile')); + sim.shots.push(shotBy(2, 300, 200), shotBy(1, 420, 200)); + const events = sim.step(FRAME); + expect(eventsOfType(events, 'volatile_exploded').map((e) => [e.position.x, e.position.y, e.depth])) + .toEqual([[300, 200, 0], [420, 200, 1], [300, 320, 1], [420, 320, 2]]); + expect(eventsOfType(events, 'asteroid_destroyed').map((e) => [e.player, e.combo, e.multiplier, e.points])) + .toEqual([[2, 1, 1, 107], [2, 2, 1.5, 160], [2, 3, 2, 214], [2, 4, 2.5, 267]]); + expect(sim.player.score).toBe(0); + expect(sim.player2!.score).toBe(748); + expect(sim.combo.count).toBe(4); + expect(sim.shots).toHaveLength(1); // the competing shot never steals a dying target + expect(eventsOfType(sim.step(FRAME), 'asteroid_destroyed')).toHaveLength(0); + }); + + it('allows two distinct blasts to destroy armor, with no duplicate kills in a dense chain', () => { + const sim = quietSim(); + const armor = rock(160, 120, 20, 'armored'); + sim.asteroids.push(armor); + for (let i = 0; i < 64; i++) sim.asteroids.push(rock(100 + i % 16 * 10, 100 + Math.floor(i / 16) * 10, 20, 'volatile')); + sim.shots.push(shotAt(100, 100)); + const events = sim.step(FRAME); + expect(eventsOfType(events, 'asteroid_hit')).toHaveLength(1); + expect(armor.hitPoints).toBe(0); + expect(eventsOfType(events, 'volatile_exploded')).toHaveLength(64); + expect(eventsOfType(events, 'asteroid_destroyed')).toHaveLength(65); + expect(sim.combo.count).toBe(65); + expect(sim.volatileFlashes).toHaveLength(VOLATILE_FLASH_LIMIT); + expect(sim.screenShake).toBeLessThanOrEqual(VOLATILE_EXPLOSION_SHAKE); + const backend = new FakeBackend(); + new SfxPlayer(backend, seededRng(1)).handle(events); + expect(backend.requests.length).toBeLessThanOrEqual(4); + expect(eventsOfType(sim.step(FRAME), 'volatile_exploded')).toHaveLength(0); + }); + + it('preserves delayed splitting without hitting newly spawned children with an old blast', () => { + const sim = quietSim(); + sim.asteroids.push(rock(250, 200, 40, 'volatile'), rock(300, 200, 40)); + sim.shots.push(shotAt(250, 200)); + sim.step(FRAME); + expect(sim.combo.count).toBe(2); + runFor(sim, 0.2); + expect(sim.asteroids).toHaveLength(4); + expect(sim.asteroids.every((a) => a.radius === 20 && !a.dying && a.hitPoints === 1)).toBe(true); + expect(sim.asteroids.filter((a) => a.archetype === 'volatile')).toHaveLength(2); + expect(sim.combo.count).toBe(2); + runFor(sim, 0.3); + expect(sim.volatileFlashes).toHaveLength(0); + }); + + it.each(['ufo', 'collision'] as const)('keeps %s destruction uncredited through the chain', (cause) => { + const sim = quietSim(); + sim.asteroids.push(rock(300, 200, 20, 'volatile'), rock(420, 200, 20, 'volatile'), rock(540, 200, 20)); + if (cause === 'ufo') sim.ufoShots.push(ufoShotAt(300, 200)); + else sim.player.position = { x: 300, y: 200 }; + const kills = eventsOfType(sim.step(FRAME), 'asteroid_destroyed'); + expect(kills).toHaveLength(3); + expect(kills.every((e) => e.points === 0 && e.player === undefined)).toBe(true); + expect(sim.totalScore).toBe(0); + expect(sim.combo.count).toBe(cause === 'ufo' ? 3 : 2); // body contact itself retains its no-combo rule + }); + + it('reproduces chain events, splits and RNG state with presentation enabled or discarded', () => { + const a = quietSim(42); + const b = quietSim(42); + for (const sim of [a, b]) { + sim.asteroids.push(rock(200, 200, 40, 'volatile'), rock(320, 200, 20, 'volatile'), rock(440, 200, 20, 'armored')); + sim.shots.push(shotAt(200, 200)); + } + const sfx = new SfxPlayer(new FakeBackend(), seededRng(998)); + for (let tick = 0; tick < 30; tick++) { + const events = a.step(FRAME); + sfx.handle(events); + expect(b.step(FRAME)).toEqual(events); + b.volatileFlashes = []; // headless presentation cannot affect simulation outcomes + } + expect(captureSimSnapshot(a, 30)).toEqual(captureSimSnapshot(b, 30)); + expect(a.rng()).toBe(b.rng()); + }); + + it('accepts a short genuine recording with the current local ranked verifier under rules 1.1.0', () => { + const seed = 54321; + const sim = new GameSim({ rng: seededRng(seed), config: RANKED_CONFIG }); + const recorder = new ReplayRecorder(seed, RANKED_CONFIG); + const ticks = 300; + for (let tick = 0; tick < ticks; tick++) { + recorder.recordTick(tick, NO_INPUT); + sim.step(FIXED_DT, NO_INPUT); + expect(sim.isGameOver).toBe(false); + } + recorder.markTimeLimit(sim); + expect(GAMEPLAY_RULES_VERSION).toBe('1.1.0'); + const replay = JSON.parse(recorder.serialize()); + const verdict = verifyRankedReplay(replay, { + seed, rulesVersion: GAMEPLAY_RULES_VERSION, config: RANKED_CONFIG, createdAt: 0, timeLimitTicks: ticks, + }, 5000, loadSettings()); + expect(verdict.ok).toBe(true); + if (verdict.ok) expect(verdict.result.calculatedScore).toBe(sim.totalScore); + }); +});