Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 80 additions & 0 deletions phaser-asteroids/docs/gameplay-experiment-c.md
Original file line number Diff line number Diff line change
@@ -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:

<http://127.0.0.1:5173/?lightningtrial=1>

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.
Binary file added phaser-asteroids/public/audio/sfx/lightning.wav
Binary file not shown.
26 changes: 26 additions & 0 deletions phaser-asteroids/scripts/generate-lightning-sfx.py
Original file line number Diff line number Diff line change
@@ -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('<h', int(max(-1, min(1, value)) * 26000)))

path = Path(__file__).resolve().parents[1] / 'public/audio/sfx/lightning.wav'
with wave.open(str(path), 'wb') as output:
output.setnchannels(1)
output.setsampwidth(2)
output.setframerate(rate)
output.writeframes(b''.join(samples))
16 changes: 8 additions & 8 deletions phaser-asteroids/scripts/historical-leaderboard.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ try {
const now = Date.now();
const rows = [
['Old Champ_99!', 20000, '1.0.0', now, 'visible'], // historical rules, inside the current week
['Current Pilot', 1000, '1.1.0', now, 'visible'],
['Past Week', 30000, '1.1.0', now - 9 * 86400000, 'visible'],
['Current Pilot', 1000, '1.2.0', now, 'visible'],
['Past Week', 30000, '1.2.0', now - 9 * 86400000, 'visible'],
['Hidden Pilot', 99999, '1.0.0', now, 'hidden'],
['Unknown Pilot', 99998, '9.0.0', now, 'visible'],
['Zero Pilot', 0, '1.0.0', now, 'visible'],
Expand All @@ -55,7 +55,7 @@ try {
}).join('\n')));
const board = await api('/leaderboard/all-time');
assert.equal(board.total, 3);
assert.deepEqual(board.entries.map((e) => [e.id, e.rank, e.rulesVersion]), [[id(2), 1, '1.1.0'], [id(0), 2, '1.0.0'], [id(1), 3, '1.1.0']]);
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));
Expand All @@ -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 });
Expand All @@ -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();
Expand Down
4 changes: 2 additions & 2 deletions phaser-asteroids/scripts/ranked-ui.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand Down
6 changes: 3 additions & 3 deletions phaser-asteroids/server/tests/harness.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ export function botRun(seed: number, opts: Omit<BotOptions, 'seed'> = {}): 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 {
Expand Down Expand Up @@ -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;
Expand Down
24 changes: 17 additions & 7 deletions phaser-asteroids/server/tests/leaderboard.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 } });
});
Expand Down Expand Up @@ -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);
Expand All @@ -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 });
Expand Down Expand Up @@ -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 () => {
Expand Down Expand Up @@ -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();
Expand Down
Loading
Loading