@clarity-js/engine 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/skins.js ADDED
@@ -0,0 +1,433 @@
1
+ // @clarity-js/engine/view — how the kits after the first two are drawn on a canvas and played with keys, a
2
+ // pointer, touch and a pad. Each skin is made per game (it may keep a camera) and is given the view's tools:
3
+ // env: { sim, pal, look, style, tileFill, rgba, shade, round, lum, act(name, ...args), canvas }
4
+ // A skin has draw(c, w, h, dt), hud(report) → [left, right], and may have keys(e, down) → handled,
5
+ // pointer.{ down, move, up }(x, y, e), pad: [{ label, aria, hold: [dx, dy, button] | 'name' }] and params/docs
6
+ // for the agent's contract.
7
+
8
+ const TAU = Math.PI * 2;
9
+ const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
10
+
11
+ /** Held keys as a stick: arrows or WASD give (dx, dy); space (or Enter) the button. */
12
+ function stick(env, send) {
13
+ const held = { l: 0, r: 0, u: 0, d: 0, b: false };
14
+ const map = { ArrowLeft: 'l', a: 'l', A: 'l', ArrowRight: 'r', d: 'r', D: 'r', ArrowUp: 'u', w: 'u', W: 'u', ArrowDown: 'd', s: 'd', S: 'd' };
15
+ const push = () => send(held.r - held.l, held.d - held.u, held.b);
16
+ return {
17
+ held,
18
+ keys(e, down) {
19
+ if (map[e.key]) held[map[e.key]] = down ? 1 : 0;
20
+ else if (e.key === ' ' || e.key === 'Enter' || e.key === 'j' || e.key === 'J') held.b = down;
21
+ else return false;
22
+ push();
23
+ return true;
24
+ },
25
+ pad(dx, dy, b, on) {
26
+ if (dx < 0) held.l = on ? 1 : 0; if (dx > 0) held.r = on ? 1 : 0; if (dy < 0) held.u = on ? 1 : 0; if (dy > 0) held.d = on ? 1 : 0; if (b) held.b = on;
27
+ push();
28
+ },
29
+ };
30
+ }
31
+
32
+ function face(c, x, y, r, ink, look = 0) {
33
+ c.fillStyle = ink;
34
+ for (const ex of [-0.32, 0.32]) { c.beginPath(); c.arc(x + r * ex + look * r * 0.15, y - r * 0.12, r * 0.14, 0, TAU); c.fill(); }
35
+ }
36
+
37
+ // ─── top-down ────────────────────────────────────────────────────────────────
38
+
39
+ function topDown(env) {
40
+ const { pal, look, tileFill, rgba, shade, round, art } = env;
41
+ const st = stick(env, (dx, dy, b) => env.act('input', dx, dy, b));
42
+ let cx = null, cy = null, t = 0;
43
+ return {
44
+ keys: st.keys,
45
+ pad: [{ label: '◀', aria: 'left', stick: [-1, 0, false] }, { label: '▲', aria: 'up', stick: [0, -1, false] }, { label: '▼', aria: 'down', stick: [0, 1, false] }, { label: '▶', aria: 'right', stick: [1, 0, false] }, { label: '⚔', aria: 'attack', stick: [0, 0, true], right: true }],
46
+ padPress: st.pad,
47
+ hud: (r) => `♥ ${r.hp} ${r.keys ? '⚿ ' + r.keys + ' ' : ''}◆ ${r.gems}${r.needGems ? '/' + r.needGems : ''}`,
48
+ params: { input: ['dx', 'dy', 'attack'], attack: ['dx', 'dy'] },
49
+ docs: { input: 'Hold a direction (dx, dy from -1 to 1; dy -1 is up) and attack (true/false) until the next input', attack: 'Swing once toward (dx, dy)' },
50
+ draw(c, w, h, dt) {
51
+ const s = env.sim.state; t += dt;
52
+ const ts = clamp(Math.floor(Math.min(w, h) / 13), 18, 52);
53
+ cx = cx == null ? s.x : cx + (s.x - cx) * Math.min(1, dt * 8); cy = cy == null ? s.y : cy + (s.y - cy) * Math.min(1, dt * 8);
54
+ const ox = w / 2 - cx * ts, oy = h / 2 + 18 - cy * ts;
55
+ const x0 = Math.max(0, Math.floor(-ox / ts) - 1), x1 = Math.min(s.w, Math.ceil((w - ox) / ts) + 1), y0 = Math.max(0, Math.floor(-oy / ts) - 1), y1 = Math.min(s.h, Math.ceil((h - oy) / ts) + 1);
56
+ for (let y = y0; y < y1; y++) for (let x = x0; x < x1; x++) {
57
+ const v = s.walls[y * s.w + x], px = ox + x * ts, py = oy + y * ts;
58
+ if (v === 1) {
59
+ const below = y + 1 < s.h && s.walls[(y + 1) * s.w + x] !== 1;
60
+ if (art?.draw(c, below && art.has('wallFront') ? 'wallFront' : 'wall', px, py, ts + 0.5, ts + 0.5, { t })) continue;
61
+ c.fillStyle = shade(pal[0], -0.05); c.fillRect(px, py, ts + 0.5, ts + 0.5);
62
+ if (below) { c.fillStyle = shade(pal[0], -0.35); c.fillRect(px, py + ts * 0.62, ts + 0.5, ts * 0.38 + 0.5); }
63
+ } else {
64
+ if (!art?.draw(c, 'floor', px, py, ts + 0.5, ts + 0.5, { t, key: (x * 7 + y * 13) % 4 })) { c.fillStyle = (x + y) % 2 ? rgba(look.ink, 0.05) : rgba(look.ink, 0.085); c.fillRect(px, py, ts + 0.5, ts + 0.5); }
65
+ if (v === 2 && art?.draw(c, 'locked', px, py, ts + 0.5, ts + 0.5, { t })) continue;
66
+ if (v === 2) { tileFill(c, px + 2, py + 2, ts - 4, pal[4] ?? pal[2], 'door'); c.fillStyle = look.background; c.beginPath(); c.arc(px + ts / 2, py + ts * 0.42, ts * 0.1, 0, TAU); c.fill(); c.fillRect(px + ts * 0.46, py + ts * 0.45, ts * 0.08, ts * 0.22); }
67
+ }
68
+ }
69
+ const sx = (x) => ox + x * ts, sy = (y) => oy + y * ts;
70
+ // a picture of a part, in the cell it stands in the middle of (false: no picture, the shape is drawn)
71
+ const pic = (role, x, y, o) => !!art && art.draw(c, role, sx(x) - ts / 2, sy(y) - ts / 2, ts, ts, o);
72
+ // the way out: a ring that glows when it is open
73
+ const open = s.gemsGot >= s.needGems;
74
+ if (!pic(open && art?.has('exitOpen') ? 'exitOpen' : 'exit', s.exit.x, s.exit.y, { t })) {
75
+ c.strokeStyle = open ? pal[2] : rgba(look.ink, 0.3); c.lineWidth = ts * 0.12;
76
+ c.beginPath(); c.arc(sx(s.exit.x), sy(s.exit.y), ts * (0.32 + (open ? Math.sin(t * 4) * 0.04 : 0)), 0, TAU); c.stroke();
77
+ }
78
+ for (const k of s.keys) if (!k.got) { if (pic('key', k.x, k.y, { t })) continue; const bob = Math.sin(t * 3 + k.x) * ts * 0.05; c.strokeStyle = pal[4] ?? pal[2]; c.lineWidth = ts * 0.09; c.beginPath(); c.arc(sx(k.x) - ts * 0.12, sy(k.y) + bob, ts * 0.13, 0, TAU); c.stroke(); c.beginPath(); c.moveTo(sx(k.x), sy(k.y) + bob); c.lineTo(sx(k.x) + ts * 0.25, sy(k.y) + bob); c.stroke(); }
79
+ for (const g of s.gems) if (!g.got) { if (pic('gem', g.x, g.y, { t, key: Math.floor(g.x + g.y) })) continue; const gx = sx(g.x), gy = sy(g.y) + Math.sin(t * 3 + g.y) * ts * 0.05, r = ts * 0.18; c.fillStyle = pal[2]; c.beginPath(); c.moveTo(gx, gy - r); c.lineTo(gx + r, gy); c.lineTo(gx, gy + r); c.lineTo(gx - r, gy); c.closePath(); c.fill(); }
80
+ for (const hh of s.hearts) if (!hh.got) { if (pic('heart', hh.x, hh.y, { t })) continue; const hx = sx(hh.x), hy = sy(hh.y), r = ts * 0.12; c.fillStyle = pal[1]; c.beginPath(); c.arc(hx - r * 0.6, hy - r * 0.2, r * 0.7, 0, TAU); c.arc(hx + r * 0.6, hy - r * 0.2, r * 0.7, 0, TAU); c.moveTo(hx - r * 1.3, hy); c.lineTo(hx, hy + r * 1.4); c.lineTo(hx + r * 1.3, hy); c.fill(); }
81
+ for (const e of s.enemies) {
82
+ if (!e.alive) continue;
83
+ if (pic(e.kind === 'chaser' ? 'chaser' : 'sentry', e.x, e.y, { t, flip: s.x < e.x })) continue;
84
+ const ex = sx(e.x), ey = sy(e.y), r = ts * 0.34;
85
+ c.fillStyle = rgba('#000000', 0.15); c.beginPath(); c.ellipse(ex, ey + r * 0.9, r * 0.8, r * 0.25, 0, 0, TAU); c.fill();
86
+ if (e.kind === 'chaser') { c.fillStyle = e.cool > 0.5 ? shade(pal[1], 0.4) : pal[1]; round(c, ex - r, ey - r, r * 2, r * 2, r * 0.8); c.fill(); }
87
+ else { c.fillStyle = pal[3] ?? pal[1]; round(c, ex - r, ey - r * 1.1, r * 2, r * 2.1, r * 0.3); c.fill(); }
88
+ face(c, ex, ey, r, look.background, Math.sign(s.x - e.x));
89
+ }
90
+ for (const sh of s.shots) { if (pic('shot', sh.x, sh.y, { t })) continue; c.fillStyle = pal[1]; c.beginPath(); c.arc(sx(sh.x), sy(sh.y), ts * 0.1, 0, TAU); c.fill(); }
91
+ // the walker, blinking while hurt, its swing an arc in front
92
+ const drawn = !(s.hurt > 0 && Math.floor(t * 12) % 2);
93
+ if (drawn && pic('hero', s.x, s.y, { t, flip: s.fx < 0, state: s.hurt > 0 ? 'hurt' : s.swing > 0 ? 'attack' : s.ix || s.iy ? 'walk' : 'idle' })) { /* its picture stands for it */ }
94
+ else if (drawn) {
95
+ const px = sx(s.x), py = sy(s.y), r = ts * 0.33;
96
+ c.fillStyle = rgba('#000000', 0.18); c.beginPath(); c.ellipse(px, py + r * 0.95, r * 0.8, r * 0.25, 0, 0, TAU); c.fill();
97
+ c.fillStyle = pal[3] ?? pal[2]; c.beginPath(); c.arc(px, py, r, 0, TAU); c.fill();
98
+ c.fillStyle = look.background; c.beginPath(); c.arc(px + s.fx * r * 0.45, py + s.fy * r * 0.45, r * 0.22, 0, TAU); c.fill();
99
+ }
100
+ if (s.swing > 0) { const a = Math.atan2(s.fy, s.fx); c.strokeStyle = rgba(look.ink, 0.6); c.lineWidth = ts * 0.1; c.beginPath(); c.arc(sx(s.x), sy(s.y), ts * s.cfg.reach * 0.9, a - 0.9, a + 0.9); c.stroke(); }
101
+ },
102
+ };
103
+ }
104
+
105
+ // ─── shmup ───────────────────────────────────────────────────────────────────
106
+
107
+ function shmup(env) {
108
+ const { pal, look, rgba, shade, round, style, art } = env;
109
+ const st = stick(env, (dx, dy, b) => env.act('input', dx, dy, b));
110
+ const stars = Array.from({ length: 70 }, (_, i) => ({ x: ((i * 7919) % 1000) / 1000, y: ((i * 104729) % 1000) / 1000, z: 0.3 + ((i * 31) % 10) / 14 }));
111
+ let geo = null, drag = null;
112
+ return {
113
+ keys: st.keys,
114
+ hud: (r) => `${'♥'.repeat(Math.max(0, r.lives))} ${r.boss?.on ? 'boss ' + Math.round((r.boss.hp / r.boss.max) * 100) + '%' : r.killed + ' down'}`,
115
+ params: { input: ['dx', 'dy', 'focus'] },
116
+ docs: { input: 'Hold a direction (dx, dy from -1 to 1; dy -1 is up) and focus (true: slow, for threading between shots) until the next input. The ship fires by itself.' },
117
+ pointer: {
118
+ // a finger drags the ship: it follows where the finger moves, at the ship's own speed
119
+ down(x, y) { drag = { x, y }; },
120
+ move(x, y) { if (!drag || !geo) return; const s = env.sim.state, tx = (x - geo.ox) / geo.u, ty = (y - geo.oy) / geo.u - 1.2; const dx = tx - s.x, dy = ty - s.y; env.act('input', clamp(dx * 2, -1, 1), clamp(dy * 2, -1, 1), false); },
121
+ up() { drag = null; env.act('input', 0, 0, false); },
122
+ },
123
+ draw(c, w, h, dt) {
124
+ const s = env.sim.state, u = Math.min(h / 16, w / s.W), fw = s.W * u, ox = (w - fw) / 2, oy = (h - 16 * u) / 2;
125
+ geo = { u, ox, oy };
126
+ c.fillStyle = shade(look.background, look.glow ? 0.04 : -0.04); c.fillRect(ox, oy, fw, 16 * u);
127
+ for (const p of stars) { const y = ((p.y + s.scroll * 0.06 * p.z) % 1) * 16 * u + oy; c.fillStyle = rgba(look.ink, 0.12 + p.z * 0.25); c.fillRect(ox + p.x * fw, y, Math.max(1, p.z * 2.2), Math.max(1, p.z * 2.2 * (look.glow ? 3 : 1))); }
128
+ const X = (x) => ox + x * u, Y = (y) => oy + y * u;
129
+ for (const it of s.items) { if (art?.draw(c, 'item', X(it.x) - u * 0.4, Y(it.y) - u * 0.4, u * 0.8, u * 0.8, { t: s.t })) continue; c.fillStyle = pal[2]; round(c, X(it.x) - u * 0.3, Y(it.y) - u * 0.2, u * 0.6, u * 0.4, u * 0.2); c.fill(); c.fillStyle = look.background; c.font = `800 ${Math.round(u * 0.3)}px system-ui,sans-serif`; c.textAlign = 'center'; c.textBaseline = 'middle'; c.fillText('P', X(it.x), Y(it.y) + 1); }
130
+ for (const f of s.foes) {
131
+ const fx = X(f.x), fy = Y(f.y), r = u * 0.42;
132
+ if (art?.draw(c, 'foe', fx - u / 2, fy - u / 2, u, u, { t: s.t, state: f.kind })) continue;
133
+ c.fillStyle = f.hp < f.max ? shade(pal[1], 0.35) : f.kind === 'dive' ? (pal[4] ?? pal[1]) : f.kind === 'sine' ? (pal[3] ?? pal[1]) : pal[1];
134
+ if (look.glow) { c.shadowColor = c.fillStyle; c.shadowBlur = u * look.glow; }
135
+ c.beginPath();
136
+ if (f.kind === 'dive') { c.moveTo(fx, fy + r); c.lineTo(fx + r, fy - r * 0.6); c.lineTo(fx - r, fy - r * 0.6); }
137
+ else if (f.kind === 'column') { c.rect(fx - r * 0.8, fy - r * 0.8, r * 1.6, r * 1.6); }
138
+ else { c.moveTo(fx, fy - r); c.lineTo(fx + r, fy); c.lineTo(fx, fy + r); c.lineTo(fx - r, fy); }
139
+ c.closePath(); c.fill(); c.shadowBlur = 0;
140
+ }
141
+ const b = s.boss;
142
+ if (b && b.on && b.hp > 0) {
143
+ const bx = X(b.x), by = Y(b.y), r = u * 1.4;
144
+ if (!art?.draw(c, 'boss', bx - r, by - r * 0.7, r * 2, r * 1.4, { t: s.t })) {
145
+ c.fillStyle = pal[1]; if (look.glow) { c.shadowColor = pal[1]; c.shadowBlur = u * look.glow * 2.5; }
146
+ round(c, bx - r, by - r * 0.7, r * 2, r * 1.4, r * 0.5); c.fill(); c.shadowBlur = 0;
147
+ c.fillStyle = pal[4] ?? pal[2]; c.beginPath(); c.arc(bx, by, r * 0.35, 0, TAU); c.fill();
148
+ }
149
+ c.fillStyle = rgba(look.ink, 0.2); c.fillRect(ox + u, oy + u * 0.6, fw - 2 * u, u * 0.18);
150
+ c.fillStyle = pal[1]; c.fillRect(ox + u, oy + u * 0.6, (fw - 2 * u) * (b.hp / b.max), u * 0.18);
151
+ }
152
+ c.strokeStyle = pal[2]; c.lineWidth = Math.max(2, u * 0.1);
153
+ for (const sh of s.shots) { if (art?.draw(c, 'shot', X(sh.x) - u * 0.15, Y(sh.y) - u * 0.1, u * 0.3, u * 0.6, { t: s.t })) continue; c.beginPath(); c.moveTo(X(sh.x), Y(sh.y)); c.lineTo(X(sh.x), Y(sh.y) + u * 0.45); c.stroke(); }
154
+ for (const bl of s.bullets) { const br = bl.r * u * 1.2; if (art?.draw(c, 'bullet', X(bl.x) - br, Y(bl.y) - br, br * 2, br * 2, { t: s.t })) continue; c.fillStyle = pal[4] ?? pal[1]; if (look.glow) { c.shadowColor = c.fillStyle; c.shadowBlur = u * look.glow * 1.2; } c.beginPath(); c.arc(X(bl.x), Y(bl.y), bl.r * u * 1.2, 0, TAU); c.fill(); c.shadowBlur = 0; c.fillStyle = look.background; c.beginPath(); c.arc(X(bl.x), Y(bl.y), bl.r * u * 0.5, 0, TAU); c.fill(); }
155
+ const drawn = !(s.hurt > 0 && Math.floor(s.t * 12) % 2);
156
+ if (drawn && art?.draw(c, 'ship', X(s.x) - u / 2, Y(s.y) - u / 2, u, u, { t: s.t })) { if (s.focus) { c.fillStyle = look.ink; c.beginPath(); c.arc(X(s.x), Y(s.y), s.cfg.hitbox * u, 0, TAU); c.fill(); } }
157
+ else if (drawn) {
158
+ const px = X(s.x), py = Y(s.y), r = u * 0.5;
159
+ c.fillStyle = pal[3] ?? pal[2]; c.beginPath(); c.moveTo(px, py - r * 1.2); c.lineTo(px + r, py + r * 0.8); c.lineTo(px, py + r * 0.4); c.lineTo(px - r, py + r * 0.8); c.closePath(); c.fill();
160
+ c.fillStyle = pal[4] ?? pal[2]; c.beginPath(); c.arc(px, py + r * 0.9 + Math.random() * r * 0.2, r * 0.18, 0, TAU); c.fill();
161
+ if (s.focus) { c.fillStyle = look.ink; c.beginPath(); c.arc(px, py, s.cfg.hitbox * u, 0, TAU); c.fill(); }
162
+ }
163
+ // outside the field: the page's own background
164
+ c.fillStyle = rgba(look.background, 0.85); c.fillRect(0, 0, ox, h); c.fillRect(ox + fw, 0, w - ox - fw, h);
165
+ },
166
+ };
167
+ }
168
+
169
+ // ─── racing ──────────────────────────────────────────────────────────────────
170
+
171
+ function racing(env) {
172
+ const { pal, look, rgba, shade, round } = env;
173
+ const held = { l: 0, r: 0, up: 0, down: 0 };
174
+ const send = (touch) => env.act('input', held.r - held.l, held.down ? -1 : held.up || touch ? 1 : 0);
175
+ let touching = false;
176
+ const pointAt = (s, d) => { const tr = s.track, k = ((d % tr.total) + tr.total) % tr.total / tr.total * tr.n, i = Math.floor(k), f = k - i, a = tr.pts[i % tr.n], b = tr.pts[(i + 1) % tr.n]; return { x: a.x + (b.x - a.x) * f, y: a.y + (b.y - a.y) * f, h: Math.atan2(b.y - a.y, b.x - a.x) }; };
177
+ let cam = null;
178
+ const car = (c, x, y, h, color, scale) => { c.save(); c.translate(x, y); c.rotate(h); c.fillStyle = rgba('#000000', 0.25); round(c, -1.15 * scale, -0.62 * scale + 0.15 * scale, 2.3 * scale, 1.24 * scale, 0.4 * scale); c.fill(); c.fillStyle = color; round(c, -1.1 * scale, -0.6 * scale, 2.2 * scale, 1.2 * scale, 0.4 * scale); c.fill(); c.fillStyle = rgba('#ffffff', 0.55); round(c, 0.1 * scale, -0.45 * scale, 0.55 * scale, 0.9 * scale, 0.2 * scale); c.fill(); c.restore(); };
179
+ return {
180
+ keys(e, down) {
181
+ const k = { ArrowLeft: 'l', a: 'l', A: 'l', ArrowRight: 'r', d: 'r', D: 'r', ArrowUp: 'up', w: 'up', W: 'up', ArrowDown: 'down', s: 'down', S: 'down', ' ': 'down' }[e.key];
182
+ if (!k) return false; held[k] = down ? 1 : 0; send(touching); return true;
183
+ },
184
+ pad: [{ label: '◀', aria: 'steer left', key: 'l' }, { label: '▶', aria: 'steer right', key: 'r' }, { label: '■', aria: 'brake', key: 'down', right: true }],
185
+ padPress(btn, on) { touching = true; held[btn.key] = on ? 1 : 0; send(true); },
186
+ hud: (r) => `lap ${r.lap}/${r.laps} place ${r.place}/${r.of}${r.want < r.of ? ' (top ' + r.want + ')' : ''} ${r.t.toFixed(1)} s`,
187
+ params: { input: ['steer', 'throttle'] },
188
+ docs: { input: 'Hold the wheel (steer -1 left … 1 right) and the pedals (throttle 1, brake -1) until the next input' },
189
+ draw(c, w, h, dt) {
190
+ const s = env.sim.state, tr = s.track, scale = Math.min(w, h) / 46;
191
+ cam = cam ?? { x: s.x, y: s.y, h: s.h };
192
+ cam.x += (s.x - cam.x) * Math.min(1, dt * 10); cam.y += (s.y - cam.y) * Math.min(1, dt * 10);
193
+ let dh = s.h - cam.h; dh = Math.atan2(Math.sin(dh), Math.cos(dh)); cam.h += dh * Math.min(1, dt * 4);
194
+ c.fillStyle = shade(pal[3] ?? '#8ab17d', -0.25); c.fillRect(0, 0, w, h);
195
+ c.save(); c.translate(w / 2, h * 0.68); c.scale(scale, scale); c.rotate(-cam.h - Math.PI / 2); c.translate(-cam.x, -cam.y);
196
+ const path = () => { c.beginPath(); tr.pts.forEach((p, i) => (i ? c.lineTo(p.x, p.y) : c.moveTo(p.x, p.y))); c.closePath(); };
197
+ c.lineJoin = 'round';
198
+ path(); c.strokeStyle = '#ffffff'; c.lineWidth = s.width + 1.6; c.stroke();
199
+ path(); c.strokeStyle = pal[1]; c.setLineDash([2, 2]); c.lineWidth = s.width + 1.6; c.stroke(); c.setLineDash([]);
200
+ path(); c.strokeStyle = '#3b3f46'; c.lineWidth = s.width; c.stroke();
201
+ path(); c.strokeStyle = rgba('#ffffff', 0.35); c.lineWidth = 0.25; c.setLineDash([2.5, 3]); c.stroke(); c.setLineDash([]);
202
+ // the start: a checked line across
203
+ const p0 = tr.pts[0];
204
+ for (let k = -4; k < 4; k++) for (let j = 0; j < 2; j++) { c.fillStyle = (k + j) % 2 ? '#ffffff' : '#111111'; const ax = p0.x + Math.cos(p0.h + Math.PI / 2) * (k + 0.5) * s.width / 8 + Math.cos(p0.h) * (j - 1) * 0.6, ay = p0.y + Math.sin(p0.h + Math.PI / 2) * (k + 0.5) * s.width / 8 + Math.sin(p0.h) * (j - 1) * 0.6; c.fillRect(ax - 0.3, ay - 0.3, 0.6, 0.6); }
205
+ s.rivals.forEach((r, i) => { const p = pointAt(s, r.d), lane = ((i % 3) - 1) * s.width * 0.25; car(c, p.x + Math.cos(p.h + Math.PI / 2) * lane, p.y + Math.sin(p.h + Math.PI / 2) * lane, p.h, [pal[1], pal[4] ?? pal[0], pal[0], pal[3]][i % 4], 1); });
206
+ car(c, s.x, s.y, s.h, pal[2], 1);
207
+ c.restore();
208
+ // a map of the track in a corner
209
+ const xs = tr.pts.map((p) => p.x), ys = tr.pts.map((p) => p.y), mx = Math.min(...xs), my = Math.min(...ys), sz = Math.min(110, w * 0.22) / Math.max(Math.max(...xs) - mx, Math.max(...ys) - my);
210
+ const MX = (x) => 14 + (x - mx) * sz, MY = (y) => h - 14 - (Math.max(...ys) - my) * sz + (y - my) * sz;
211
+ c.beginPath(); tr.pts.forEach((p, i) => (i ? c.lineTo(MX(p.x), MY(p.y)) : c.moveTo(MX(p.x), MY(p.y)))); c.closePath(); c.strokeStyle = rgba('#ffffff', 0.7); c.lineWidth = 3; c.stroke();
212
+ for (const r of s.rivals) { const p = pointAt(s, r.d); c.fillStyle = pal[1]; c.beginPath(); c.arc(MX(p.x), MY(p.y), 3, 0, TAU); c.fill(); }
213
+ c.fillStyle = pal[2]; c.beginPath(); c.arc(MX(s.x), MY(s.y), 4, 0, TAU); c.fill();
214
+ },
215
+ };
216
+ }
217
+
218
+ // ─── cards and boards ────────────────────────────────────────────────────────
219
+
220
+ function cardBoard(env) {
221
+ const { pal, look, rgba, shade, round, lum } = env;
222
+ let hits = [], hover = -1, t = 0;
223
+ const cardColor = (k) => (k.c < 0 ? look.ink : pal[[1, 2, 3, 4, 0, 5][k.c] ?? 0] ?? pal[0]);
224
+ const drawCard = (c, x, y, cw, ch, k, faceUp, lifted) => {
225
+ c.save(); c.translate(x, y - (lifted ? ch * 0.12 : 0));
226
+ c.fillStyle = rgba('#000000', 0.18); round(c, 2, 3, cw, ch, cw * 0.12); c.fill();
227
+ if (!faceUp) { c.fillStyle = shade(pal[0], -0.1); round(c, 0, 0, cw, ch, cw * 0.12); c.fill(); c.strokeStyle = rgba('#ffffff', 0.35); c.lineWidth = 2; round(c, cw * 0.12, cw * 0.12, cw * 0.76, ch - cw * 0.24, cw * 0.08); c.stroke(); c.restore(); return; }
228
+ c.fillStyle = '#fbfaf7'; round(c, 0, 0, cw, ch, cw * 0.12); c.fill();
229
+ const col = cardColor(k);
230
+ c.fillStyle = col; round(c, cw * 0.1, cw * 0.1, cw * 0.8, ch - cw * 0.2, cw * 0.08); c.fill();
231
+ c.fillStyle = /^#/.test(col) && lum(col) > 0.45 ? '#1d1d24' : '#ffffff';
232
+ c.font = `800 ${Math.round(cw * 0.5)}px system-ui,sans-serif`; c.textAlign = 'center'; c.textBaseline = 'middle';
233
+ c.fillText(k.c < 0 ? '★' : String(k.r), cw / 2, ch / 2 + 1);
234
+ c.restore();
235
+ };
236
+ return {
237
+ keys(e, down) {
238
+ if (!down) return false;
239
+ const s = env.sim.state;
240
+ if (s.goal === 'line') { const n = Number(e.key); if (n >= 1 && n <= s.board.w) { env.act('drop', n - 1); return true; } if (e.key === 'ArrowLeft') { hover = Math.max(0, (hover < 0 ? 0 : hover) - 1); return true; } if (e.key === 'ArrowRight') { hover = Math.min(s.board.w - 1, hover + 1); return true; } if ((e.key === ' ' || e.key === 'Enter') && hover >= 0) { env.act('drop', hover); return true; } return false; }
241
+ const n = Number(e.key); if (n >= 1 && n <= 9) { env.act('play', n - 1); return true; }
242
+ if (e.key === 'd' || e.key === 'D' || e.key === ' ') { env.act('draw'); return true; }
243
+ return false;
244
+ },
245
+ pointer: {
246
+ move(x) { const s = env.sim.state; if (s.goal === 'line') { const h = hits.find((k) => x >= k.x && x < k.x + k.w); hover = h ? h.col : -1; } },
247
+ down(x, y) { const h = hits.find((k) => x >= k.x && x < k.x + k.w && y >= k.y && y < k.y + k.h); if (!h) return; if (h.act === 'drop') env.act('drop', h.col); else if (h.act === 'play') env.act('play', h.i); else env.act('draw'); },
248
+ },
249
+ hud: (r) => (r.goal === 'line' ? `${r.inRow} in a row wins` : `${r.hand.length} in hand · rival ${r.rivals.join(', ')}`),
250
+ params: { play: ['i', 'color'], draw: [], drop: ['col'] },
251
+ docs: { play: 'Play the i-th card of your hand (0 first); a wild (c -1) names a colour', draw: 'Draw a card; the turn passes', drop: 'Drop a token into a column (0 is the left)' },
252
+ draw(c, w, h, dt) {
253
+ const s = env.sim.state; t += dt; hits = [];
254
+ if (s.goal === 'line') {
255
+ const b = s.board, cs = Math.floor(Math.min((w - 40) / b.w, (h - 90) / (b.h + 0.6))), bw = cs * b.w, bh = cs * b.h, ox = (w - bw) / 2, oy = 56 + cs * 0.6;
256
+ if (hover >= 0) { c.fillStyle = rgba(pal[1], 0.5); c.beginPath(); c.arc(ox + (hover + 0.5) * cs, oy - cs * 0.45, cs * 0.32, 0, TAU); c.fill(); }
257
+ c.fillStyle = pal[0]; round(c, ox - 8, oy - 8, bw + 16, bh + 16, 14); c.fill();
258
+ for (let y = 0; y < b.h; y++) for (let x = 0; x < b.w; x++) {
259
+ const v = b.cells[y * b.w + x], px = ox + (x + 0.5) * cs, py = oy + (y + 0.5) * cs;
260
+ c.fillStyle = v === 1 ? pal[1] : v === 2 ? (pal[4] ?? pal[2]) : look.background;
261
+ c.beginPath(); c.arc(px, py, cs * 0.38, 0, TAU); c.fill();
262
+ if (b.last === y * b.w + x) { c.strokeStyle = rgba('#ffffff', 0.8); c.lineWidth = 3; c.stroke(); }
263
+ }
264
+ for (let x = 0; x < b.w; x++) hits.push({ act: 'drop', col: x, x: ox + x * cs, y: 0, w: cs, h });
265
+ return;
266
+ }
267
+ const g = s.cards, cw = clamp(Math.floor(w / 9), 44, 86), ch = Math.round(cw * 1.4);
268
+ // rivals' hands, face down, along the top
269
+ g.hands.slice(1).forEach((hand, p) => { const n = hand.length, span = Math.min(w * 0.6, n * cw * 0.35), x0 = w / 2 - span / 2 + (p - (g.hands.length - 2) / 2) * w * 0.3; hand.forEach((_, i) => drawCard(c, x0 + (i / Math.max(1, n - 1)) * (span - cw * 0.5), 48, cw * 0.7, ch * 0.7, null, false)); });
270
+ // the pile and the deck in the middle
271
+ const top = g.pile[g.pile.length - 1], cy = h * 0.42 - ch / 2;
272
+ drawCard(c, w / 2 + 8, cy, cw, ch, top.c < 0 ? { c: g.color, r: '★' } : top, true);
273
+ if (top.c < 0) { c.fillStyle = cardColor({ c: g.color }); c.beginPath(); c.arc(w / 2 + 8 + cw / 2, cy - 12, 7, 0, TAU); c.fill(); }
274
+ drawCard(c, w / 2 - cw - 8, cy, cw, ch, null, false);
275
+ c.fillStyle = look.ink; c.font = '600 12px system-ui,sans-serif'; c.textAlign = 'center'; c.fillText(`${g.deck.length} left · draw`, w / 2 - cw / 2 - 8, cy + ch + 16);
276
+ hits.push({ act: 'draw', x: w / 2 - cw - 8, y: cy, w: cw, h: ch });
277
+ // your hand, the cards you can play raised
278
+ const hand = g.hands[0], n = hand.length, gap = Math.min(cw + 8, (w - 40 - cw) / Math.max(1, n - 1)), x0 = w / 2 - ((n - 1) * gap + cw) / 2, hy = h - ch - 22;
279
+ hand.forEach((k, i) => { const ok = k.c < 0 || k.c === g.color || k.r === top.r; drawCard(c, x0 + i * gap, hy, cw, ch, k, true, ok); hits.push({ act: 'play', i, x: x0 + i * gap, y: hy - ch * 0.12, w: i === n - 1 ? cw : gap, h: ch * 1.12 }); });
280
+ hits.reverse();
281
+ },
282
+ };
283
+ }
284
+
285
+ // ─── explore-3d: a small world, drawn as a diorama from above and to the side ─
286
+
287
+ function explore(env) {
288
+ const { pal, look, rgba, shade } = env;
289
+ const st = stick(env, (dx, dy, b) => env.act('input', dx, dy, b));
290
+ let cx = null, cy = null, t = 0, saidAt = -9, lastSaid = null;
291
+ const ground = (hgt, x, y) => { const k = clamp(hgt / 6, 0, 1); const base = k < 0.18 ? (pal[2] ?? '#f2cc8f') : k < 0.6 ? (pal[3] ?? pal[0]) : k < 0.85 ? pal[0] : shade(pal[5] ?? pal[0], 0.3); return shade(base, ((x * 7 + y * 13) % 5) * 0.012 - 0.02); };
292
+ return {
293
+ keys: st.keys,
294
+ pad: [{ label: '◀', aria: 'west', stick: [-1, 0, false] }, { label: '▲', aria: 'north', stick: [0, -1, false] }, { label: '▼', aria: 'south', stick: [0, 1, false] }, { label: '▶', aria: 'east', stick: [1, 0, false] }, { label: '💬', aria: 'talk', stick: [0, 0, true], right: true }],
295
+ padPress: st.pad,
296
+ hud: (r) => `found ${r.delivered + r.carrying}/${r.items}${r.carrying ? ' · bring it home' : ''}`,
297
+ params: { input: ['dx', 'dy', 'talk'], talk: [] },
298
+ docs: { input: 'Hold a direction (dx east, dy south, each -1 … 1) and talk (true) until the next input', talk: 'Talk to whoever stands next to you: they say where something lost is' },
299
+ draw(c, w, h, dt) {
300
+ const s = env.sim.state; t += dt;
301
+ if (s.said !== lastSaid) { lastSaid = s.said; saidAt = t; }
302
+ const a = clamp(Math.min(w, h) / 20, 14, 34), b = a * 0.5, hz = a * 0.55;
303
+ cx = cx == null ? s.x : cx + (s.x - cx) * Math.min(1, dt * 6); cy = cy == null ? s.y : cy + (s.y - cy) * Math.min(1, dt * 6);
304
+ const P = (x, y, z) => [w / 2 + (x - cx - (y - cy)) * a, h * 0.52 + (x - cx + (y - cy)) * b - z * hz];
305
+ const sky = c.createLinearGradient(0, 0, 0, h); sky.addColorStop(0, shade(look.background, 0.15)); sky.addColorStop(1, shade(look.background, -0.08)); c.fillStyle = sky; c.fillRect(0, 0, w, h);
306
+ const R = Math.ceil(Math.max(w / a, h / b) / 2) + 2, fx = Math.floor(cx), fy = Math.floor(cy);
307
+ const things = new Map();
308
+ for (const o of [...s.props.map((p) => ({ ...p, t: 'prop' })), ...s.items.filter((i) => !i.got).map((i) => ({ ...i, t: 'item' })), ...s.npcs.map((n) => ({ ...n, t: 'npc' }))]) things.set(Math.floor(o.y) * s.w + Math.floor(o.x), o);
309
+ const H = (x, y) => (x < 0 || y < 0 || x >= s.w || y >= s.h ? -1 : s.water[y * s.w + x] ? -0.3 : s.height[y * s.w + x]);
310
+ for (let d = -2 * R; d <= 2 * R; d++) for (let x = fx - R; x <= fx + R; x++) {
311
+ const y = fx + fy + d - x; if (y < fy - R || y > fy + R) continue;
312
+ const inside = x >= 0 && y >= 0 && x < s.w && y < s.h;
313
+ const seen = inside && s.seen[y * s.w + x], z = inside ? H(x, y) : -0.3, far = Math.hypot(x + 0.5 - s.x, y + 0.5 - s.y) > s.fog;
314
+ const top = [P(x, y, z), P(x + 1, y, z), P(x + 1, y + 1, z), P(x, y + 1, z)];
315
+ if (!inside || (inside && s.water[y * s.w + x])) {
316
+ c.fillStyle = shade('#4f8fb5', Math.sin(t * 1.5 + x * 0.7 + y * 0.4) * 0.03 + (inside && !seen ? -0.35 : 0));
317
+ c.beginPath(); top.forEach(([px, py], i) => (i ? c.lineTo(px, py) : c.moveTo(px, py))); c.closePath(); c.fill();
318
+ continue;
319
+ }
320
+ const col = ground(z, x, y);
321
+ // the sides that face the eye, where the neighbour is lower
322
+ const zs = H(x, y + 1), ze = H(x + 1, y);
323
+ if (zs < z) { const q = [P(x, y + 1, z), P(x + 1, y + 1, z), P(x + 1, y + 1, Math.max(zs, -0.3)), P(x, y + 1, Math.max(zs, -0.3))]; c.fillStyle = shade(col, -0.22); c.beginPath(); q.forEach(([px, py], i) => (i ? c.lineTo(px, py) : c.moveTo(px, py))); c.closePath(); c.fill(); }
324
+ if (ze < z) { const q = [P(x + 1, y, z), P(x + 1, y + 1, z), P(x + 1, y + 1, Math.max(ze, -0.3)), P(x + 1, y, Math.max(ze, -0.3))]; c.fillStyle = shade(col, -0.34); c.beginPath(); q.forEach(([px, py], i) => (i ? c.lineTo(px, py) : c.moveTo(px, py))); c.closePath(); c.fill(); }
325
+ c.fillStyle = seen ? col : shade(col, -0.45); c.beginPath(); top.forEach(([px, py], i) => (i ? c.lineTo(px, py) : c.moveTo(px, py))); c.closePath(); c.fill();
326
+ if (seen && far) { c.fillStyle = rgba(look.background, 0.35); c.fill(); }
327
+ // what stands on the cell
328
+ const o = things.get(y * s.w + x), [mx, my] = P(x + 0.5, y + 0.5, z);
329
+ if (x === Math.floor(s.goal.x) && y === Math.floor(s.goal.y)) {
330
+ c.fillStyle = '#f4f1de'; c.fillRect(mx - a * 0.18, my - a * 1.5, a * 0.36, a * 1.5); c.fillStyle = pal[1]; c.fillRect(mx - a * 0.22, my - a * 1.62, a * 0.44, a * 0.2);
331
+ const lit = s.delivered / Math.max(1, s.items.length); c.fillStyle = lit ? rgba('#ffe28a', 0.4 + lit * 0.6) : rgba(look.ink, 0.4); c.beginPath(); c.arc(mx, my - a * 1.75, a * (0.14 + lit * 0.1), 0, TAU); c.fill();
332
+ }
333
+ if (o && (seen || o.t === 'prop')) {
334
+ if (o.t === 'prop' && o.kind === 'tree') { const sz = a * (o.s ?? 1); c.fillStyle = shade(pal[5] ?? '#6b4f3a', -0.3); c.fillRect(mx - sz * 0.06, my - sz * 0.4, sz * 0.12, sz * 0.4); c.fillStyle = shade(pal[0], seen ? 0 : -0.4); c.beginPath(); c.moveTo(mx, my - sz * 1.5); c.lineTo(mx + sz * 0.42, my - sz * 0.3); c.lineTo(mx - sz * 0.42, my - sz * 0.3); c.closePath(); c.fill(); c.fillStyle = rgba('#ffffff', 0.12); c.beginPath(); c.moveTo(mx, my - sz * 1.5); c.lineTo(mx - sz * 0.42, my - sz * 0.3); c.lineTo(mx - sz * 0.1, my - sz * 0.3); c.closePath(); c.fill(); }
335
+ else if (o.t === 'prop') { const sz = a * (o.s ?? 1) * 0.5; c.fillStyle = shade('#9a9a9a', seen ? 0 : -0.4); c.beginPath(); c.moveTo(mx - sz, my); c.lineTo(mx - sz * 0.6, my - sz * 0.9); c.lineTo(mx + sz * 0.5, my - sz); c.lineTo(mx + sz, my - sz * 0.1); c.closePath(); c.fill(); }
336
+ else if (o.t === 'item') { const bob = Math.sin(t * 3 + x) * a * 0.08; c.fillStyle = rgba('#ffe28a', 0.35); c.beginPath(); c.arc(mx, my - a * 0.5 + bob, a * 0.42, 0, TAU); c.fill(); c.fillStyle = pal[4] ?? '#f4a261'; c.beginPath(); c.moveTo(mx, my - a * 0.85 + bob); c.lineTo(mx + a * 0.2, my - a * 0.5 + bob); c.lineTo(mx, my - a * 0.15 + bob); c.lineTo(mx - a * 0.2, my - a * 0.5 + bob); c.closePath(); c.fill(); }
337
+ else if (o.t === 'npc') { c.fillStyle = pal[1]; c.beginPath(); c.ellipse(mx, my - a * 0.4, a * 0.22, a * 0.4, 0, 0, TAU); c.fill(); c.fillStyle = '#f2cc8f'; c.beginPath(); c.arc(mx, my - a * 0.95, a * 0.18, 0, TAU); c.fill(); if (!o.told) { c.fillStyle = look.ink; c.font = `800 ${Math.round(a * 0.5)}px system-ui,sans-serif`; c.textAlign = 'center'; c.fillText('!', mx, my - a * 1.3); } }
338
+ }
339
+ if (x === Math.floor(s.x) && y === Math.floor(s.y)) {
340
+ const [px, py] = P(s.x, s.y, z);
341
+ c.fillStyle = rgba('#000000', 0.22); c.beginPath(); c.ellipse(px, py, a * 0.25, a * 0.12, 0, 0, TAU); c.fill();
342
+ c.fillStyle = pal[2] === look.background ? pal[1] : (pal[4] ?? pal[1]); c.beginPath(); c.ellipse(px, py - a * 0.38, a * 0.2, a * 0.36, 0, 0, TAU); c.fill();
343
+ c.fillStyle = '#f2cc8f'; c.beginPath(); c.arc(px, py - a * 0.85, a * 0.16, 0, TAU); c.fill();
344
+ if (s.carrying) { c.fillStyle = pal[4] ?? '#f4a261'; c.beginPath(); c.arc(px + a * 0.2, py - a * 1.15, a * 0.1, 0, TAU); c.fill(); }
345
+ }
346
+ }
347
+ if (s.said && t - saidAt < 5) {
348
+ c.fillStyle = rgba(look.background, 0.92); env.round(c, 16, h - 76, w - 32, 56, 12); c.fill();
349
+ c.fillStyle = look.ink; c.font = '600 15px system-ui,sans-serif'; c.textAlign = 'left'; c.textBaseline = 'middle'; c.fillText(s.said, 32, h - 48, w - 64);
350
+ }
351
+ },
352
+ };
353
+ }
354
+
355
+ // ─── physics toy ─────────────────────────────────────────────────────────────
356
+
357
+ function physicsToy(env) {
358
+ const { pal, look, rgba, shade, round } = env;
359
+ let aim = { angle: 40, power: 0.75 }, dragging = false, ghost = null, geo = null;
360
+ const L = { x: 1.5, y: 1.2 };
361
+ return {
362
+ keys(e, down) {
363
+ if (!down) return false;
364
+ const s = env.sim.state;
365
+ if (s.goal === 'topple') {
366
+ if (e.key === 'ArrowUp') aim.angle = clamp(aim.angle + 2, 0, 89); else if (e.key === 'ArrowDown') aim.angle = clamp(aim.angle - 2, 0, 89);
367
+ else if (e.key === 'ArrowRight') aim.power = clamp(aim.power + 0.03, 0.05, 1); else if (e.key === 'ArrowLeft') aim.power = clamp(aim.power - 0.03, 0.05, 1);
368
+ else if (e.key === ' ' || e.key === 'Enter') env.act('throw', aim.angle, aim.power); else return false;
369
+ return true;
370
+ }
371
+ ghost = ghost ?? s.px;
372
+ if (e.key === 'ArrowLeft') ghost -= 0.1; else if (e.key === 'ArrowRight') ghost += 0.1; else if (e.key === ' ' || e.key === 'Enter') env.act('drop', ghost); else return false;
373
+ return true;
374
+ },
375
+ pointer: {
376
+ down(x, y) { dragging = true; this.move(x, y); },
377
+ move(x, y) {
378
+ if (!geo) return;
379
+ const s = env.sim.state, wx = (x - geo.ox) / geo.k, wy = (geo.oy - y) / geo.k;
380
+ if (s.goal === 'stack') { ghost = clamp(wx, s.px - 6, s.px + 6); return; }
381
+ if (!dragging) return;
382
+ const dx = wx - L.x, dy = wy - L.y;
383
+ aim.angle = clamp(Math.atan2(dy, dx) * 180 / Math.PI, 0, 89); aim.power = clamp(Math.hypot(dx, dy) / 7, 0.05, 1);
384
+ },
385
+ up() { const s = env.sim.state; if (s.goal === 'topple' && dragging) env.act('throw', aim.angle, aim.power); else if (s.goal === 'stack' && ghost != null) env.act('drop', ghost); dragging = false; },
386
+ },
387
+ hud: (r) => (r.goal === 'topple' ? `${r.down}/${r.targets} down · ${r.shots} throws left` : `${Math.max(0, r.top - 1).toFixed(1)} of ${r.height} m · ${r.pieces - r.next} pieces`),
388
+ params: { throw: ['angle', 'power'], drop: ['x'] },
389
+ docs: { throw: 'Throw the ball: angle in degrees above the ground (0 … 89), power 0 … 1; wait for it to settle', drop: 'Drop the next piece with its middle at x (the platform\'s middle is x 8)' },
390
+ draw(c, w, h, dt) {
391
+ const s = env.sim.state, world = env.sim.world.world;
392
+ const span = s.goal === 'topple' ? Math.max(18, ...s.blocks.map((b) => b[0] + 3)) : 16, k = Math.min(w / span, (h - 70) / 8), ox = s.goal === 'topple' ? 10 : w / 2 - s.px * k, oy = h - 26;
393
+ geo = { k, ox, oy };
394
+ const X = (x) => ox + x * k, Y = (y) => oy - y * k;
395
+ c.fillStyle = rgba(look.ink, 0.12); c.fillRect(0, oy, w, h - oy);
396
+ c.fillStyle = rgba(look.ink, 0.35); c.fillRect(0, oy, w, 3);
397
+ if (s.goal === 'stack') {
398
+ c.fillStyle = pal[0]; c.fillRect(X(s.px - s.platform / 2), Y(1), s.platform * k, k);
399
+ c.strokeStyle = rgba(look.ink, 0.5); c.setLineDash([6, 6]); c.lineWidth = 2; c.beginPath(); c.moveTo(0, Y(1 + s.height)); c.lineTo(w, Y(1 + s.height)); c.stroke(); c.setLineDash([]);
400
+ c.fillStyle = look.ink; c.font = '600 12px system-ui,sans-serif'; c.textAlign = 'left'; c.fillText(`${s.height} m`, 12, Y(1 + s.height) - 6);
401
+ } else {
402
+ c.fillStyle = shade(pal[0], -0.2); c.fillRect(X(L.x) - 5, Y(L.y), 10, L.y * k);
403
+ if (!s.busy && s.shots > 0) {
404
+ const a = aim.angle * Math.PI / 180, v = aim.power * s.cfg.launch, g = s.cfg.gravity;
405
+ c.fillStyle = rgba(look.ink, 0.45);
406
+ for (let tt = 0.06; tt < 1.6; tt += 0.06) { const x = L.x + Math.cos(a) * v * tt, y = L.y + Math.sin(a) * v * tt - 0.5 * g * tt * tt; if (y < 0) break; c.beginPath(); c.arc(X(x), Y(y), 2.2, 0, TAU); c.fill(); }
407
+ c.fillStyle = pal[2]; c.beginPath(); c.arc(X(L.x), Y(L.y), s.cfg.ball * k, 0, TAU); c.fill();
408
+ }
409
+ }
410
+ for (const b of world.bodies) {
411
+ if (!b.invMass) continue;
412
+ const ang = 2 * Math.atan2(b.quaternion[2], b.quaternion[3]);
413
+ c.save(); c.translate(X(b.position[0]), Y(b.position[1])); c.rotate(-ang);
414
+ if (b.shape.type === 'sphere') { c.fillStyle = pal[2]; c.beginPath(); c.arc(0, 0, b.shape.radius * k, 0, TAU); c.fill(); }
415
+ else {
416
+ const hw = b.shape.half[0] * k, hh = b.shape.half[1] * k;
417
+ c.fillStyle = b.name === 'target' ? pal[1] : b.name === 'piece' ? (pal[4] ?? pal[0]) : pal[0];
418
+ round(c, -hw, -hh, hw * 2, hh * 2, Math.min(hw, hh) * 0.25); c.fill();
419
+ c.fillStyle = rgba('#ffffff', 0.18); c.fillRect(-hw + 2, -hh + 2, hw * 2 - 4, Math.max(2, hh * 0.3));
420
+ if (b.name === 'target') face(c, 0, 0, hw, look.background);
421
+ }
422
+ c.restore();
423
+ }
424
+ if (s.goal === 'stack' && !s.busy && s.next < s.pieces.length) {
425
+ const [pw, ph] = s.pieces[s.next], gx = ghost ?? s.px;
426
+ let top = 1; for (const b of world.bodies) if (b.invMass) top = Math.max(top, b.position[1] + b.shape.half[1]);
427
+ c.fillStyle = rgba(pal[4] ?? pal[0], 0.45); round(c, X(gx - pw / 2), Y(top + ph + 0.4), pw * k, ph * k, 4); c.fill();
428
+ }
429
+ },
430
+ };
431
+ }
432
+
433
+ export const SKINS = { 'top-down': topDown, shmup, racing, 'card-board': cardBoard, 'explore-3d': explore, 'physics-toy': physicsToy };
package/src/sound.js ADDED
@@ -0,0 +1,179 @@
1
+ // @clarity-js/engine — sound made for the game, not loaded: music composed from the game's seed and mood, and
2
+ // effects synthesized for what happens in it. No files, nobody's samples; Web Audio in the page.
3
+ //
4
+ // game.json: "sound": { "music": "calm" | "tense" | "playful" | "none", "sfx": true, "volume": 0.6 }
5
+ //
6
+ // compose({ seed, mood, bars }) → the notes, as data (the same seed, the same tune; tested in Node)
7
+ // createSound(game, { context }) → { start(), stop(), play(effect), hear(event), mute(on), muted, context }
8
+ // renderMusic(song, seconds, ctx) → the music drawn into an OfflineAudioContext (for a test, or a file)
9
+
10
+ import { createRng } from '@ozsarman/clarityjs/sim';
11
+
12
+ export const MOODS = {
13
+ calm: { scale: [0, 2, 4, 7, 9], root: 57, bpm: 76, lead: 'sine', bass: 'triangle', swing: 0, density: 0.45, drums: false },
14
+ playful: { scale: [0, 2, 4, 5, 7, 9, 11], root: 60, bpm: 118, lead: 'square', bass: 'triangle', swing: 0.12, density: 0.7, drums: true },
15
+ tense: { scale: [0, 2, 3, 5, 7, 8, 10], root: 50, bpm: 132, lead: 'sawtooth', bass: 'square', swing: 0, density: 0.75, drums: true },
16
+ };
17
+
18
+ /** Which mood a game asks for: its sound, else its pace. */
19
+ export function moodOf(game) {
20
+ const m = game?.sound?.music;
21
+ if (m === 'none') return null;
22
+ if (MOODS[m]) return m;
23
+ return game?.feel?.pace === 'calm' ? 'calm' : game?.feel?.pace === 'fast' ? 'tense' : 'playful';
24
+ }
25
+
26
+ const PROGRESSIONS = [[0, 5, 3, 4], [0, 3, 4, 4], [0, 4, 5, 3], [0, 5, 1, 4]];
27
+
28
+ /**
29
+ * A loop of `bars` bars in a mood, by the seed: chords, a bass on their roots, a melody that walks the scale
30
+ * and leans on the chord's notes, and drums for the livelier moods. Times in beats. → { bpm, beats, notes }
31
+ */
32
+ export function compose({ seed = 1, mood = 'playful', bars = 8 } = {}) {
33
+ const m = MOODS[mood] ?? MOODS.playful, rng = createRng('music/' + seed + '/' + mood);
34
+ const prog = rng.pick(PROGRESSIONS), notes = [];
35
+ const degree = (d) => { const n = m.scale.length, o = Math.floor(d / n); return m.scale[((d % n) + n) % n] + o * 12; };
36
+ let walk = rng.int(0, m.scale.length - 1) + m.scale.length;
37
+ for (let bar = 0; bar < bars; bar++) {
38
+ const chord = prog[bar % prog.length], t0 = bar * 4;
39
+ // a pad: the chord's three notes, the whole bar
40
+ for (const k of [0, 2, 4]) notes.push({ t: t0, dur: 4, note: m.root + degree(chord + k), vel: 0.18, voice: 'pad' });
41
+ // the bass: the root on the beats (the fifth on the third in livelier moods)
42
+ for (let b = 0; b < 4; b += mood === 'calm' ? 2 : 1) notes.push({ t: t0 + b, dur: mood === 'calm' ? 1.8 : 0.45, note: m.root - 12 + degree(chord + (b === 2 && mood !== 'calm' ? 4 : 0)), vel: 0.5, voice: 'bass' });
43
+ // the melody: eighths, a step or two at a time, landing on a chord note on the strong beats
44
+ for (let e = 0; e < 8; e++) {
45
+ if (rng() > m.density && e % 2) continue;
46
+ const strong = e % 4 === 0;
47
+ if (strong) { const target = chord + rng.pick([0, 2, 4]) + m.scale.length; walk += Math.sign(target - walk) * Math.min(2, Math.abs(target - walk)); }
48
+ else walk += rng.pick([-2, -1, -1, 1, 1, 2]);
49
+ walk = Math.max(m.scale.length - 2, Math.min(m.scale.length * 2 + 3, walk));
50
+ const t = t0 + e * 0.5 + (e % 2 ? m.swing : 0);
51
+ notes.push({ t, dur: strong ? 0.9 : 0.4, note: m.root + degree(walk), vel: strong ? 0.42 : 0.3, voice: 'lead' });
52
+ }
53
+ if (m.drums) for (let s = 0; s < 8; s++) {
54
+ if (s % 4 === 0) notes.push({ t: t0 + s * 0.5, dur: 0.2, note: 0, vel: 0.7, voice: 'kick' });
55
+ if (s % 4 === 2) notes.push({ t: t0 + s * 0.5, dur: 0.15, note: 0, vel: 0.35, voice: 'snare' });
56
+ notes.push({ t: t0 + s * 0.5 + (s % 2 ? m.swing : 0), dur: 0.05, note: 0, vel: s % 2 ? 0.12 : 0.2, voice: 'hat' });
57
+ }
58
+ }
59
+ notes.sort((a, b) => a.t - b.t);
60
+ return { mood, bpm: m.bpm, beats: bars * 4, notes, lead: m.lead, bass: m.bass };
61
+ }
62
+
63
+ const hz = (midi) => 440 * 2 ** ((midi - 69) / 12);
64
+
65
+ /** One note into a context at a time (seconds), through `out`. */
66
+ function voiceNote(ctx, out, n, at, beat, song, noise) {
67
+ const dur = n.dur * beat;
68
+ if (n.voice === 'kick') { const o = ctx.createOscillator(), g = ctx.createGain(); o.frequency.setValueAtTime(140, at); o.frequency.exponentialRampToValueAtTime(42, at + 0.18); g.gain.setValueAtTime(n.vel, at); g.gain.exponentialRampToValueAtTime(0.001, at + 0.22); o.connect(g).connect(out); o.start(at); o.stop(at + 0.25); return; }
69
+ if (n.voice === 'snare' || n.voice === 'hat') {
70
+ const s = ctx.createBufferSource(), f = ctx.createBiquadFilter(), g = ctx.createGain();
71
+ s.buffer = noise; f.type = n.voice === 'hat' ? 'highpass' : 'bandpass'; f.frequency.value = n.voice === 'hat' ? 7000 : 1800;
72
+ g.gain.setValueAtTime(n.vel, at); g.gain.exponentialRampToValueAtTime(0.001, at + (n.voice === 'hat' ? 0.05 : 0.15));
73
+ s.connect(f).connect(g).connect(out); s.start(at); s.stop(at + 0.2); return;
74
+ }
75
+ const o = ctx.createOscillator(), g = ctx.createGain(), f = ctx.createBiquadFilter();
76
+ o.type = n.voice === 'lead' ? song.lead : n.voice === 'bass' ? song.bass : 'triangle';
77
+ o.frequency.setValueAtTime(hz(n.note), at);
78
+ f.type = 'lowpass'; f.frequency.value = n.voice === 'pad' ? 1200 : n.voice === 'bass' ? 900 : 2600;
79
+ const a = n.voice === 'pad' ? Math.min(0.6, dur * 0.3) : 0.01, rel = n.voice === 'pad' ? 0.5 : 0.08;
80
+ g.gain.setValueAtTime(0, at); g.gain.linearRampToValueAtTime(n.vel * (o.type === 'square' || o.type === 'sawtooth' ? 0.35 : 1), at + a);
81
+ g.gain.setTargetAtTime(0, at + Math.max(a, dur - rel), rel / 3);
82
+ o.connect(f).connect(g).connect(out); o.start(at); o.stop(at + dur + rel * 2);
83
+ }
84
+
85
+ function noiseBuffer(ctx) { const b = ctx.createBuffer(1, ctx.sampleRate * 0.5, ctx.sampleRate), d = b.getChannelData(0), rng = createRng('noise'); for (let i = 0; i < d.length; i++) d[i] = rng() * 2 - 1; return b; }
86
+
87
+ /** Effects, each a few oscillators or a burst of noise: what the game's events sound like. */
88
+ export const EFFECTS = {
89
+ jump: [{ type: 'square', from: 300, to: 660, len: 0.14, vel: 0.18 }],
90
+ coin: [{ type: 'square', from: 988, to: 988, len: 0.07, vel: 0.15 }, { type: 'square', from: 1319, to: 1319, len: 0.18, vel: 0.15, at: 0.07 }],
91
+ hit: [{ noise: true, len: 0.18, vel: 0.4, filter: 900 }, { type: 'sawtooth', from: 220, to: 70, len: 0.2, vel: 0.2 }],
92
+ clear: [{ type: 'triangle', from: 660, to: 660, len: 0.08, vel: 0.2 }, { type: 'triangle', from: 880, to: 880, len: 0.08, vel: 0.2, at: 0.07 }, { type: 'triangle', from: 1175, to: 1175, len: 0.16, vel: 0.2, at: 0.14 }],
93
+ click: [{ type: 'triangle', from: 520, to: 420, len: 0.05, vel: 0.15 }],
94
+ swing: [{ noise: true, len: 0.12, vel: 0.25, filter: 3000, sweep: 800 }],
95
+ shoot: [{ type: 'square', from: 880, to: 440, len: 0.06, vel: 0.08 }],
96
+ throw: [{ noise: true, len: 0.25, vel: 0.3, filter: 1200, sweep: 300 }],
97
+ drop: [{ type: 'sine', from: 180, to: 90, len: 0.15, vel: 0.35 }],
98
+ card: [{ noise: true, len: 0.06, vel: 0.25, filter: 5000 }],
99
+ talk: [{ type: 'sine', from: 600, to: 700, len: 0.06, vel: 0.12 }, { type: 'sine', from: 500, to: 560, len: 0.06, vel: 0.12, at: 0.08 }],
100
+ win: [523, 659, 784, 1047].map((f, i) => ({ type: 'square', from: f, to: f, len: i === 3 ? 0.45 : 0.12, vel: 0.15, at: i * 0.12 })),
101
+ lose: [392, 330, 262].map((f, i) => ({ type: 'triangle', from: f, to: f * 0.97, len: i === 2 ? 0.5 : 0.18, vel: 0.2, at: i * 0.18 })),
102
+ };
103
+
104
+ /** The game's events, by type, as effects (an event of a type not here is quiet). */
105
+ export const EVENT_SOUNDS = {
106
+ jump: 'jump', coin: 'coin', gem: 'coin', key: 'coin', found: 'coin', heal: 'coin', power: 'clear', checkpoint: 'clear',
107
+ death: 'hit', hurt: 'hit', stomp: 'hit', strike: 'hit', crash: 'hit', defeat: 'clear', clear: 'clear', unlock: 'clear', lap: 'clear', delivered: 'clear',
108
+ swap: 'click', press: 'click', push: 'click', move: 'click', swing: 'swing', throw: 'throw', drop: 'drop', settled: null,
109
+ play: 'card', draw: 'card', rival: 'card', talk: 'talk', won: 'win', lost: 'lose', boss: 'hit',
110
+ };
111
+
112
+ function effectInto(ctx, out, name, at, noise) {
113
+ for (const p of EFFECTS[name] ?? []) {
114
+ const t = at + (p.at ?? 0), g = ctx.createGain();
115
+ g.gain.setValueAtTime(p.vel, t); g.gain.exponentialRampToValueAtTime(0.001, t + p.len);
116
+ if (p.noise) { const s = ctx.createBufferSource(), f = ctx.createBiquadFilter(); s.buffer = noise; f.type = 'bandpass'; f.frequency.setValueAtTime(p.filter, t); if (p.sweep) f.frequency.exponentialRampToValueAtTime(p.sweep, t + p.len); s.connect(f).connect(g).connect(out); s.start(t); s.stop(t + p.len + 0.02); continue; }
117
+ const o = ctx.createOscillator(); o.type = p.type; o.frequency.setValueAtTime(p.from, t); if (p.to !== p.from) o.frequency.exponentialRampToValueAtTime(p.to, t + p.len);
118
+ o.connect(g).connect(out); o.start(t); o.stop(t + p.len + 0.02);
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Music and effects for a game in the page. The context starts on the first press or tap (browsers ask for one).
124
+ * @param {object} game
125
+ * @param {{ context?: AudioContext, seed?: any }} [options]
126
+ */
127
+ export function createSound(game, { context = null, seed } = {}) {
128
+ const mood = moodOf(game), wantSfx = game?.sound?.sfx !== false, volume = Math.max(0, Math.min(1, game?.sound?.volume ?? 0.6));
129
+ const AC = globalThis.AudioContext ?? globalThis.webkitAudioContext;
130
+ let ctx = context, master = null, musicBus = null, noise = null, timer = 0, next = 0, step = 0, song = null, muted = false;
131
+ const heard = [];
132
+ const ensure = () => {
133
+ if (ctx && master) return ctx;
134
+ if (!ctx) { if (!AC) return null; ctx = new AC(); }
135
+ master = ctx.createGain(); master.gain.value = muted ? 0 : volume; master.connect(ctx.destination);
136
+ musicBus = ctx.createGain(); musicBus.gain.value = 0.5; musicBus.connect(master);
137
+ noise = noiseBuffer(ctx);
138
+ return ctx;
139
+ };
140
+ const api = {
141
+ get context() { return ctx; },
142
+ get muted() { return muted; },
143
+ mood, heard,
144
+ /** Start the music (after a press: browsers keep sound off until then). */
145
+ start() {
146
+ if (!mood || timer || !ensure()) return;
147
+ ctx.resume?.();
148
+ song = compose({ seed: seed ?? game?.title ?? 1, mood, bars: 8 });
149
+ const beat = 60 / song.bpm;
150
+ next = ctx.currentTime + 0.1; step = 0;
151
+ const ahead = () => {
152
+ // notes in the next 0.3 s, scheduled on the context's own clock
153
+ while (next < ctx.currentTime + 0.3) {
154
+ const loop = Math.floor(step / song.beats), within = step % song.beats;
155
+ for (const n of song.notes) if (n.t >= within && n.t < within + 1) voiceNote(ctx, musicBus, n, next + (n.t - within) * beat, beat, song, noise);
156
+ void loop;
157
+ step++; next += beat;
158
+ }
159
+ };
160
+ ahead(); timer = setInterval(ahead, 100);
161
+ },
162
+ stop() { clearInterval(timer); timer = 0; },
163
+ /** An effect by name (EFFECTS). */
164
+ play(name) { heard.push(name); if (!wantSfx || muted || !ensure() || ctx.state === 'suspended') return; effectInto(ctx, master, name, ctx.currentTime + 0.005, noise); },
165
+ /** A game event → its effect. */
166
+ hear(event) { const name = EVENT_SOUNDS[event?.type]; if (name) api.play(name); },
167
+ mute(on = !muted) { muted = !!on; if (master) master.gain.setTargetAtTime(muted ? 0 : volume, ctx.currentTime, 0.02); return muted; },
168
+ close() { api.stop(); if (ctx && !context) ctx.close?.(); },
169
+ };
170
+ return api;
171
+ }
172
+
173
+ /** The music drawn into an OfflineAudioContext for `seconds`: for a test (is it heard?) or to save it. → AudioBuffer */
174
+ export async function renderMusic(song, seconds = 4, OfflineContext = globalThis.OfflineAudioContext) {
175
+ const ctx = new OfflineContext(1, Math.round(44100 * seconds), 44100), out = ctx.createGain(), noise = noiseBuffer(ctx), beat = 60 / song.bpm;
176
+ out.gain.value = 0.6; out.connect(ctx.destination);
177
+ for (let loop = 0; loop * song.beats * beat < seconds; loop++) for (const n of song.notes) { const at = (loop * song.beats + n.t) * beat; if (at < seconds) voiceNote(ctx, out, n, at, beat, song, noise); }
178
+ return ctx.startRendering();
179
+ }