@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/view.js ADDED
@@ -0,0 +1,340 @@
1
+ // @clarity-js/engine/view — a game in the page: drawn on a canvas in its look, played with keys, touch, a pad
2
+ // or an agent (the game's ai contract: what clarity mcp reads and plays), on the shared frame clock (so a test
3
+ // or an agent can hold time and step it).
4
+ //
5
+ // import { mountGame } from '@clarity-js/engine/view'
6
+ // import game from './game.json'
7
+ // import rules from './rules.js'
8
+ // mountGame(document.getElementById('app'), game, rules)
9
+
10
+ import { mount, _component, onDispose, _css } from '@ozsarman/clarityjs/runtime';
11
+ import { frame } from '@ozsarman/clarityjs/game-loop';
12
+ import { loadGame } from './index.js';
13
+ import { lookOf } from './make.js';
14
+ import { SKINS } from './skins.js';
15
+ import { createArt } from './art.js';
16
+ import { createSound } from './sound.js';
17
+
18
+ const CSS = `
19
+ .cge{position:relative;width:100%;height:100%;min-height:320px;overflow:hidden;font:600 15px/1.3 system-ui,-apple-system,"Segoe UI",sans-serif;user-select:none;-webkit-user-select:none;touch-action:none}
20
+ .cge canvas{position:absolute;inset:0;width:100%;height:100%;display:block}
21
+ .cge-hud{position:absolute;left:12px;right:12px;top:10px;display:flex;justify-content:space-between;gap:12px;pointer-events:none}
22
+ .cge-hud b{font-weight:800}
23
+ .cge-card{position:absolute;inset:0;display:none;align-items:center;justify-content:center;flex-direction:column;gap:14px;text-align:center}
24
+ .cge-card.on{display:flex}
25
+ .cge-card h2{margin:0;font-size:30px;letter-spacing:.01em}
26
+ .cge-card button,.cge-pad button{font:inherit;border:0;border-radius:999px;padding:12px 22px;cursor:pointer}
27
+ .cge-pad{position:absolute;left:0;right:0;bottom:14px;display:none;justify-content:space-between;padding:0 14px;pointer-events:none}
28
+ .cge-pad.on{display:flex}
29
+ .cge-pad button{pointer-events:auto;width:64px;height:64px;padding:0;font-size:22px;opacity:.85}
30
+ .cge-pad div{display:flex;gap:10px}
31
+ .cge-mute{position:absolute;right:10px;bottom:10px;border:0;border-radius:999px;width:36px;height:36px;font-size:16px;cursor:pointer;opacity:.7}
32
+ .cge-mute:hover,.cge-mute:focus-visible{opacity:1}
33
+ .cge-pad.on~.cge-mute{bottom:auto;top:36px}
34
+ `;
35
+
36
+ const DIRKEY = { ArrowLeft: 'left', ArrowRight: 'right', ArrowUp: 'up', ArrowDown: 'down', a: 'left', d: 'right', w: 'up', s: 'down', A: 'left', D: 'right', W: 'up', S: 'down' };
37
+
38
+ function rgba(hex, a) { const n = parseInt(hex.slice(1), 16); return `rgba(${n >> 16},${(n >> 8) & 255},${n & 255},${a})`; }
39
+ function shade(hex, f) { const n = parseInt(hex.slice(1), 16); const c = (v) => Math.max(0, Math.min(255, Math.round(f > 0 ? v + (255 - v) * f : v * (1 + f)))); return '#' + [n >> 16, (n >> 8) & 255, n & 255].map((v) => c(v).toString(16).padStart(2, '0')).join(''); }
40
+ function lum(hex) { const n = parseInt(hex.slice(1), 16); const f = (v) => { v /= 255; return v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4; }; return 0.2126 * f(n >> 16) + 0.7152 * f((n >> 8) & 255) + 0.0722 * f(n & 255); }
41
+ function contrast(a, b) { const x = lum(a), y = lum(b); return (Math.max(x, y) + 0.05) / (Math.min(x, y) + 0.05); }
42
+ /** Each colour far enough from the background to be seen on it (a pale tile on paper, a dark one at night). */
43
+ function legible(palette, bg) {
44
+ const dark = lum(bg) < 0.25;
45
+ return palette.map((c) => { if (!/^#[0-9a-f]{6}$/i.test(c)) return c; let k = c; for (let i = 0; i < 12 && contrast(k, bg) < 1.5; i++) k = shade(k, dark ? 0.12 : -0.1); return k; });
46
+ }
47
+ function round(ctx, x, y, w, h, r) { ctx.beginPath(); ctx.moveTo(x + r, y); ctx.arcTo(x + w, y, x + w, y + h, r); ctx.arcTo(x + w, y + h, x, y + h, r); ctx.arcTo(x, y + h, x, y, r); ctx.arcTo(x, y, x + w, y, r); ctx.closePath(); }
48
+
49
+ /**
50
+ * @param {Element} el
51
+ * @param {object} game game.json
52
+ * @param {object} [rules] rules.js's default export
53
+ * @param {{ level?: number, seed?: any }} [options]
54
+ * @returns {() => void} unmount
55
+ */
56
+ export function mountGame(el, game, rules = {}, options = {}) {
57
+ return mount(() => GameView({ game, rules, ...options }), el);
58
+ }
59
+
60
+ export function GameView({ game, rules = {}, level: startLevel = 0, seed = 1 } = {}) {
61
+ return _component(() => {
62
+ _css('clarity-engine-view', CSS);
63
+ const loaded = loadGame(game, rules);
64
+ const g = loaded.game, style = g.look?.style ?? 'flat', look = lookOf(g);
65
+ const pal = legible(look.palette, look.background);
66
+ const root = document.createElement('div');
67
+ root.className = 'cge cge-' + style;
68
+ root.style.background = look.background;
69
+ root.style.color = look.ink;
70
+ root.tabIndex = 0;
71
+ root.setAttribute('role', 'application');
72
+ root.setAttribute('aria-label', g.title + (g.pitch ? ': ' + g.pitch : ''));
73
+ const canvas = document.createElement('canvas');
74
+ const hud = document.createElement('div'); hud.className = 'cge-hud';
75
+ const left = document.createElement('span'), right = document.createElement('span');
76
+ hud.append(left, right);
77
+ const card = document.createElement('div'); card.className = 'cge-card';
78
+ const cardTitle = document.createElement('h2'), cardText = document.createElement('div'), cardButton = document.createElement('button');
79
+ card.append(cardTitle, cardText, cardButton);
80
+ cardButton.style.background = pal[1] ?? look.ink; cardButton.style.color = look.background;
81
+ const pad = document.createElement('div'); pad.className = 'cge-pad';
82
+ const padL = document.createElement('div'), padR = document.createElement('div');
83
+ const bLeft = document.createElement('button'), bRight = document.createElement('button'), bJump = document.createElement('button');
84
+ bLeft.textContent = '◀'; bRight.textContent = '▶'; bJump.textContent = '▲';
85
+ for (const b of [bLeft, bRight, bJump]) { b.style.background = rgba(look.ink, 0.18); b.style.color = look.ink; b.setAttribute('aria-label', b === bJump ? 'jump' : b === bLeft ? 'left' : 'right'); }
86
+ padL.append(bLeft, bRight); padR.append(bJump); pad.append(padL, padR);
87
+ root.append(canvas, hud, pad, card);
88
+ const live = loaded.kit.continuous;
89
+ const coarse = g.feel?.device === 'phone-first' || (typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches);
90
+ // the kits after the first two are drawn and played by their skins
91
+ let sim;
92
+ // the game's own pictures, where it has them (art.js): a part without one is drawn as its shape
93
+ const art = createArt(g.art, { base: typeof document !== 'undefined' ? document.baseURI : null });
94
+ const env = { get sim() { return sim; }, pal, look, style, rgba, shade, round, lum, canvas, art, act: (name, ...args) => act(name, ...args), tileFill: (...a) => tileFill(...a) };
95
+ const skin = SKINS[loaded.kit.name]?.(env) ?? null;
96
+ if (skin?.pad) {
97
+ padL.replaceChildren(); padR.replaceChildren();
98
+ for (const p of skin.pad) {
99
+ const b = document.createElement('button');
100
+ b.textContent = p.label; b.setAttribute('aria-label', p.aria); b.style.background = rgba(look.ink, 0.18); b.style.color = look.ink;
101
+ const on = (v) => (e) => { e.preventDefault(); if (p.stick) skin.padPress(...p.stick, v); else skin.padPress(p, v); };
102
+ b.addEventListener('pointerdown', on(true)); b.addEventListener('pointerup', on(false)); b.addEventListener('pointerleave', on(false)); b.addEventListener('pointercancel', on(false));
103
+ (p.right ? padR : padL).append(b);
104
+ }
105
+ if (coarse) pad.classList.add('on');
106
+ } else if (live && !skin && coarse) pad.classList.add('on');
107
+
108
+ // the game's own music and effects, from the first press on (browsers keep sound off until then); M mutes
109
+ const sound = createSound(g);
110
+ const mute = document.createElement('button');
111
+ mute.className = 'cge-mute'; mute.style.color = look.ink; mute.style.background = rgba(look.ink, 0.12);
112
+ const showMute = () => { mute.textContent = sound.muted ? '🔇' : '🔊'; mute.setAttribute('aria-label', sound.muted ? 'Sound off: turn it on' : 'Sound on: turn it off'); mute.setAttribute('aria-pressed', String(sound.muted)); };
113
+ showMute();
114
+ mute.addEventListener('click', (e) => { e.stopPropagation(); sound.mute(); if (!sound.muted) sound.start(); showMute(); root.focus(); });
115
+ root.append(mute);
116
+ let heardOnce = false;
117
+ const wake = () => { if (heardOnce) return; heardOnce = true; sound.start(); };
118
+ root.addEventListener('pointerdown', wake); root.addEventListener('keydown', wake);
119
+ let li = Math.min(startLevel, loaded.levels.length - 1), sel = null, shake = 0, flash = [];
120
+ sim = loaded.make(li, seed);
121
+ const held = { left: false, right: false, jump: false };
122
+ const metrics = { start: performance.now(), firstFrame: null, frames: 0, fps: 0, last: performance.now(), firstInput: null };
123
+ const say = (r) => {
124
+ const lv = `Level ${li + 1}/${loaded.levels.length}`;
125
+ if (skin) { left.textContent = `${g.title} · ${lv}`; right.textContent = skin.hud(r); }
126
+ else if (sim.kit.name === 'platformer') { left.textContent = `${g.title} · ${lv}`; right.textContent = `◎ ${r.coins}/${r.need || r.coinsTotal} ♥ ${r.lives}`; }
127
+ else { left.textContent = `${g.title} · ${lv}`; right.textContent = (r.left != null ? `${r.left} moves` : '') + (r.target ? ` ${r.score}/${r.target}` : r.goal === 'lights' ? ` ${r.lit} lit` : ''); }
128
+ if (r.won || r.lost) {
129
+ card.classList.add('on');
130
+ const last = li >= loaded.levels.length - 1;
131
+ cardTitle.textContent = r.won ? (last ? 'All done!' : 'Level done!') : 'Not this time';
132
+ cardText.textContent = r.won ? (r.place ? `place ${r.place} in ${r.t.toFixed(1)} s` : r.used ? `${r.used} moves` : `${r.t?.toFixed?.(1) ?? ''} s`) : r.place ? `place ${r.place}: not this time` : 'Try it again';
133
+ cardButton.textContent = r.won ? (last ? 'Play again' : 'Next level') : 'Retry';
134
+ } else card.classList.remove('on');
135
+ };
136
+ const restart = (next) => {
137
+ if (next) li = (li + 1) % loaded.levels.length;
138
+ sim = loaded.make(li, seed); sel = null; flash = []; say(sim.report());
139
+ sim.on((e) => { sound.hear(e); if (e.type === 'clear' || e.type === 'death' || e.type === 'stomp') shake = 0.25; if (e.type === 'clear' && e.cells) flash.push(...e.cells.map((c) => ({ c, t: 0.35 }))); });
140
+ };
141
+ restart(false);
142
+ const act = (name, ...args) => { if (metrics.firstInput == null) metrics.firstInput = performance.now() - metrics.start; const r = sim.act(name, ...args); say(sim.report()); return r; };
143
+ cardButton.addEventListener('click', () => { const r = sim.report(); restart(r.won); root.focus(); });
144
+
145
+ // ── input ──
146
+ const onKey = (e, down) => {
147
+ if (down && (e.key === 'm' || e.key === 'M')) { sound.mute(); showMute(); return; }
148
+ if (skin?.keys && !card.classList.contains('on') && skin.keys(e, down)) { e.preventDefault(); return; }
149
+ if (skin) {
150
+ if (down && (e.key === 'Enter' || e.key === ' ') && card.classList.contains('on')) { e.preventDefault(); cardButton.click(); }
151
+ else if (down && e.key === 'r') restart(false);
152
+ return;
153
+ }
154
+ if (live) {
155
+ if (['ArrowLeft', 'a', 'A'].includes(e.key)) held.left = down;
156
+ else if (['ArrowRight', 'd', 'D'].includes(e.key)) held.right = down;
157
+ else if ([' ', 'ArrowUp', 'w', 'W'].includes(e.key)) held.jump = down;
158
+ else return;
159
+ e.preventDefault();
160
+ act('input', (held.right ? 1 : 0) - (held.left ? 1 : 0), held.jump);
161
+ } else if (down && DIRKEY[e.key] && (sim.state.goal === 'push' || sim.state.goal === 'slide')) { e.preventDefault(); act('move', DIRKEY[e.key]); }
162
+ else if (down && (e.key === 'Enter' || e.key === ' ') && card.classList.contains('on')) { e.preventDefault(); cardButton.click(); }
163
+ else if (down && e.key === 'r') restart(false);
164
+ };
165
+ root.addEventListener('keydown', (e) => onKey(e, true));
166
+ root.addEventListener('keyup', (e) => onKey(e, false));
167
+ const hold = (b, key) => {
168
+ const set = (v) => (e) => { e.preventDefault(); held[key] = v; act('input', (held.right ? 1 : 0) - (held.left ? 1 : 0), held.jump); };
169
+ b.addEventListener('pointerdown', set(true)); b.addEventListener('pointerup', set(false)); b.addEventListener('pointerleave', set(false)); b.addEventListener('pointercancel', set(false));
170
+ };
171
+ hold(bLeft, 'left'); hold(bRight, 'right'); hold(bJump, 'jump');
172
+ let geo = null, down = null;
173
+ const local = (e) => { const r = canvas.getBoundingClientRect(); return [e.clientX - r.left, e.clientY - r.top]; };
174
+ if (skin?.pointer) {
175
+ canvas.addEventListener('pointerdown', (e) => { root.focus(); canvas.setPointerCapture?.(e.pointerId); skin.pointer.down?.(...local(e), e); });
176
+ canvas.addEventListener('pointermove', (e) => skin.pointer.move?.(...local(e), e));
177
+ canvas.addEventListener('pointerup', (e) => skin.pointer.up?.(...local(e), e));
178
+ }
179
+ canvas.addEventListener('pointerdown', (e) => {
180
+ root.focus();
181
+ if (skin || live || !geo) return;
182
+ const r = canvas.getBoundingClientRect(), x = Math.floor((e.clientX - r.left - geo.ox) / geo.cs), y = Math.floor((e.clientY - r.top - geo.oy) / geo.cs);
183
+ down = { x, y, px: e.clientX, py: e.clientY };
184
+ const s = sim.state;
185
+ if (x < 0 || y < 0 || x >= s.w || y >= s.h) return;
186
+ if (s.goal === 'lights') act('press', x, y);
187
+ else if (s.goal === 'match') {
188
+ if (sel && Math.abs(sel.x - x) + Math.abs(sel.y - y) === 1) { act('swap', sel.x, sel.y, x > sel.x ? 'right' : x < sel.x ? 'left' : y > sel.y ? 'down' : 'up'); sel = null; }
189
+ else sel = { x, y };
190
+ } else if (s.goal === 'slide') {
191
+ const gx = s.gap % s.w, gy = Math.floor(s.gap / s.w);
192
+ if (Math.abs(gx - x) + Math.abs(gy - y) === 1) act('move', x > gx ? 'right' : x < gx ? 'left' : y > gy ? 'down' : 'up');
193
+ }
194
+ });
195
+ canvas.addEventListener('pointerup', (e) => {
196
+ if (skin || !down || live) return;
197
+ const dx = e.clientX - down.px, dy = e.clientY - down.py, s = sim.state;
198
+ if (Math.hypot(dx, dy) < 24) { down = null; return; }
199
+ const dir = Math.abs(dx) > Math.abs(dy) ? (dx > 0 ? 'right' : 'left') : (dy > 0 ? 'down' : 'up');
200
+ if (s.goal === 'match' && down.x >= 0 && down.y >= 0) { act('swap', down.x, down.y, dir); sel = null; }
201
+ else if (s.goal === 'push' || s.goal === 'slide') act('move', dir);
202
+ down = null;
203
+ });
204
+
205
+ // ── drawing ──
206
+ const ctx2 = canvas.getContext('2d');
207
+ let camX = 0, t = 0, padWas = '';
208
+ const draw = (dt) => {
209
+ const w = root.clientWidth || 640, h = root.clientHeight || 480, dpr = Math.min(2, globalThis.devicePixelRatio || 1);
210
+ if (canvas.width !== Math.round(w * dpr) || canvas.height !== Math.round(h * dpr)) { canvas.width = Math.round(w * dpr); canvas.height = Math.round(h * dpr); }
211
+ const c = ctx2; c.setTransform(dpr, 0, 0, dpr, 0, 0); c.clearRect(0, 0, w, h);
212
+ shake = Math.max(0, shake - dt);
213
+ if (shake) c.translate((Math.random() - 0.5) * shake * 10, (Math.random() - 0.5) * shake * 10);
214
+ if (skin) skin.draw(c, w, h, dt); else if (live) drawPlatformer(c, w, h, dt); else drawGrid(c, w, h, dt);
215
+ };
216
+ // a shape finished by the look's recipe: corners, glow, gloss, outline, pattern
217
+ const tileFill = (c, x, y, s, color, kind = 'cell') => {
218
+ const r = s * look.radius;
219
+ c.save();
220
+ if (look.glow) { c.shadowColor = color; c.shadowBlur = s * look.glow; }
221
+ round(c, x, y, s, s, r); c.fillStyle = color; c.fill();
222
+ c.shadowBlur = 0;
223
+ if (look.gloss) { round(c, x + s * 0.12, y + s * 0.08, s * 0.76, s * 0.3, r * 0.6); c.fillStyle = `rgba(255,255,255,${look.gloss})`; c.fill(); }
224
+ if (look.pattern === 'marble' && kind === 'cell') { c.strokeStyle = rgba('#ffffff', 0.45); c.lineWidth = Math.max(1, s * 0.05); for (let k = 1; k <= 2; k++) { c.beginPath(); c.arc(x + s * 0.5, y + s * 0.62, s * 0.14 * k, Math.PI * 1.1, Math.PI * 1.9 + k * 0.4); c.stroke(); } }
225
+ if (look.pattern === 'hatch') { c.strokeStyle = rgba(look.ink, 0.5); c.lineWidth = 1; for (let k = 0.25; k < 1; k += 0.25) { c.beginPath(); c.moveTo(x + s * k, y + s * 0.85); c.lineTo(x + s * (k + 0.15), y + s * 0.65); c.stroke(); } }
226
+ if (look.outline) { c.strokeStyle = rgba(look.ink, look.outline); c.lineWidth = Math.max(1, s * 0.03); round(c, x, y, s, s, r); c.stroke(); }
227
+ if (look.pattern === 'bevel') { c.fillStyle = 'rgba(0,0,0,0.25)'; c.fillRect(x, y + s * 0.82, s, s * 0.18); c.fillStyle = 'rgba(255,255,255,0.25)'; c.fillRect(x, y, s, s * 0.12); }
228
+ c.restore();
229
+ };
230
+ const drawGrid = (c, w, h, dt) => {
231
+ const s = sim.state, top = 48, cs = Math.floor(Math.min((w - 24) / s.w, (h - top - 24) / s.h)), ox = Math.floor((w - cs * s.w) / 2), oy = top + Math.floor((h - top - cs * s.h) / 2);
232
+ geo = { cs, ox, oy };
233
+ const gap = Math.max(2, cs * 0.08), inner = cs - gap;
234
+ flash = flash.filter((f) => (f.t -= dt) > 0);
235
+ for (let y = 0; y < s.h; y++) for (let x = 0; x < s.w; x++) {
236
+ const i = y * s.w + x, px = ox + x * cs + gap / 2, py = oy + y * cs + gap / 2, v = s.cells[i];
237
+ if (s.goal === 'match') { if (v >= 0) tileFill(c, px, py, inner, pal[v % pal.length]); if (sel && sel.x === x && sel.y === y) { c.strokeStyle = look.ink; c.lineWidth = 3; round(c, px - 2, py - 2, inner + 4, inner + 4, inner * 0.2); c.stroke(); } }
238
+ else if (s.goal === 'lights') tileFill(c, px, py, inner, v ? (pal[4] ?? pal[1]) : rgba(look.ink, 0.12), v ? 'cell' : 'off');
239
+ else if (s.goal === 'slide') { if (v) { const tc = pal[(v - 1) % pal.length]; tileFill(c, px, py, inner, tc, 'tile'); c.fillStyle = /^#/.test(tc) && lum(tc) > 0.4 ? '#1d1d24' : '#ffffff'; c.font = `800 ${Math.round(inner * 0.42)}px system-ui,sans-serif`; c.textAlign = 'center'; c.textBaseline = 'middle'; c.fillText(String(v), px + inner / 2, py + inner / 2 + 1); } }
240
+ else if (s.goal === 'push') {
241
+ if (s.walls[i]) tileFill(c, px, py, inner, pal[0], 'wall');
242
+ else { c.fillStyle = rgba(look.ink, 0.06); c.fillRect(px, py, inner, inner); }
243
+ if (s.marks[i]) { c.strokeStyle = pal[1]; c.lineWidth = Math.max(2, inner * 0.08); c.beginPath(); c.arc(px + inner / 2, py + inner / 2, inner * 0.22, 0, Math.PI * 2); c.stroke(); }
244
+ if (s.boxes.includes(i)) tileFill(c, px + inner * 0.1, py + inner * 0.1, inner * 0.8, s.marks[i] ? pal[2] ?? pal[1] : pal[3] ?? pal[1], 'crate');
245
+ if (s.player === i) { c.fillStyle = pal[1]; c.beginPath(); c.arc(px + inner / 2, py + inner / 2, inner * 0.34, 0, Math.PI * 2); c.fill(); c.fillStyle = look.background; for (const ex of [-0.12, 0.12]) { c.beginPath(); c.arc(px + inner * (0.5 + ex), py + inner * 0.44, inner * 0.06, 0, Math.PI * 2); c.fill(); } }
246
+ }
247
+ for (const f of flash) if (f.c === i) { c.fillStyle = rgba('#ffffff', f.t * 2); round(c, px, py, inner, inner, inner * 0.2); c.fill(); }
248
+ }
249
+ };
250
+ const drawPlatformer = (c, w, h, dt) => {
251
+ const s = sim.state, ts = Math.max(18, Math.floor(h / (s.h + 1.5))), viewW = w / ts;
252
+ camX += (Math.max(0, Math.min(s.w - viewW, s.x - viewW * 0.4)) - camX) * Math.min(1, dt * 6);
253
+ const oy = h - s.h * ts - ts * 0.25;
254
+ // far hills, slower than the ground
255
+ for (let layer = 0; layer < 2; layer++) {
256
+ c.fillStyle = rgba(pal[layer === 0 ? 3 : 0] ?? look.ink, layer === 0 ? 0.18 : 0.12);
257
+ c.beginPath(); c.moveTo(0, h);
258
+ for (let x = 0; x <= w + 40; x += 40) { const wx = x / ts + camX * (layer === 0 ? 0.3 : 0.6); c.lineTo(x, oy + ts * (s.h * 0.45 + layer * 1.5) + Math.sin(wx * (0.35 - layer * 0.1) + layer) * ts * 1.2); }
259
+ c.lineTo(w, h); c.closePath(); c.fill();
260
+ }
261
+ const x0 = Math.floor(camX), x1 = Math.ceil(camX + viewW) + 1;
262
+ for (let y = 0; y < s.h; y++) for (let x = x0; x < x1; x++) {
263
+ const v = s.tiles[y * s.w + x]; if (!v) continue;
264
+ const px = (x - camX) * ts, py = oy + y * ts;
265
+ if (v === 1) {
266
+ const above = y > 0 && s.tiles[(y - 1) * s.w + x] === 1;
267
+ if (art?.draw(c, above || !art.has('grass') ? 'ground' : 'grass', px, py, ts + 0.5, ts + 0.5, { t })) continue;
268
+ tileFill(c, px, py, ts + 0.5, above ? shade(pal[0], -0.15) : pal[0], 'ground'); if (!above) { c.fillStyle = pal[2] ?? pal[1]; c.fillRect(px, py, ts + 0.5, ts * 0.18); }
269
+ }
270
+ else if (v === 2) { if (art?.draw(c, 'ledge', px, py, ts + 0.5, ts + 0.5, { t })) continue; c.fillStyle = pal[3] ?? pal[0]; round(c, px, py, ts, ts * 0.3, ts * 0.12); c.fill(); }
271
+ else if (v === 3) { if (art?.draw(c, 'spikes', px, py, ts + 0.5, ts + 0.5, { t })) continue; c.fillStyle = pal[1]; for (let k = 0; k < 3; k++) { c.beginPath(); c.moveTo(px + k * ts / 3, py + ts); c.lineTo(px + (k + 0.5) * ts / 3, py + ts * 0.35); c.lineTo(px + (k + 1) * ts / 3, py + ts); c.fill(); } }
272
+ }
273
+ const sx = (x) => (x - camX) * ts, sy = (y) => oy + y * ts;
274
+ t += dt;
275
+ // a picture of a part, in the cell its feet stand in (false: no picture, the shape is drawn)
276
+ const pic = (role, x, y, o) => !!art && art.draw(c, role, sx(x) - ts / 2, sy(y) + ts * 0.45 - ts, ts, ts, o);
277
+ const open = s.coinsGot >= s.need;
278
+ if (!pic(open && art?.has('doorOpen') ? 'doorOpen' : 'door', s.door.x, s.door.y, { t })) {
279
+ c.fillStyle = pal[2] ?? pal[1];
280
+ round(c, sx(s.door.x) - ts * 0.4, sy(s.door.y) - ts * 0.55, ts * 0.8, ts * 1.05, ts * 0.35); c.fill();
281
+ c.fillStyle = open ? (pal[4] ?? '#ffd23f') : rgba(look.ink, 0.35); c.beginPath(); c.arc(sx(s.door.x), sy(s.door.y), ts * 0.12, 0, Math.PI * 2); c.fill();
282
+ }
283
+ for (const cp of s.checkpoints) { if (pic(cp.on && art?.has('flagOn') ? 'flagOn' : 'flag', cp.x, cp.y, { t })) continue; c.fillStyle = cp.on ? pal[1] : rgba(look.ink, 0.4); c.fillRect(sx(cp.x) - 2, sy(cp.y) - ts * 0.5, 3, ts); c.beginPath(); c.moveTo(sx(cp.x) + 1, sy(cp.y) - ts * 0.5); c.lineTo(sx(cp.x) + ts * 0.45, sy(cp.y) - ts * 0.35); c.lineTo(sx(cp.x) + 1, sy(cp.y) - ts * 0.2); c.fill(); }
284
+ for (const k of s.coins) if (!k.got) { if (pic('coin', k.x, k.y, { t, key: Math.floor(k.x) })) continue; const bob = Math.sin(t * 4 + k.x) * ts * 0.06; c.fillStyle = pal[4] ?? '#ffd23f'; c.beginPath(); c.ellipse(sx(k.x), sy(k.y) + bob, ts * 0.22 * Math.abs(Math.cos(t * 2 + k.x)) + ts * 0.04, ts * 0.24, 0, 0, Math.PI * 2); c.fill(); }
285
+ for (const e of s.enemies) if (e.alive) { if (pic('walker', e.x, e.y, { t, flip: e.vx < 0 })) continue; c.fillStyle = pal[1]; round(c, sx(e.x) - ts * 0.4, sy(e.y) - ts * 0.4, ts * 0.8, ts * 0.85, ts * 0.35); c.fill(); c.fillStyle = look.background; c.beginPath(); c.arc(sx(e.x) + Math.sign(e.vx) * ts * 0.15, sy(e.y) - ts * 0.1, ts * 0.1, 0, Math.PI * 2); c.fill(); }
286
+ // the hero: standing, running, on the way up or on the way down
287
+ if (pic('hero', s.x, s.y, { t, flip: s.facing < 0, state: !s.onGround ? (s.vy < 0 ? 'jump' : 'fall') : Math.abs(s.vx) > 0.3 ? 'run' : 'idle' })) return;
288
+ const squash = s.onGround ? 1 : 1 + Math.min(0.2, Math.abs(s.vy) * 0.01);
289
+ const pw = ts * 0.7 / squash, ph = ts * 0.9 * squash;
290
+ c.fillStyle = pal[3] ?? pal[1]; if (look.glow) { c.shadowColor = c.fillStyle; c.shadowBlur = ts * look.glow * 1.25; }
291
+ round(c, sx(s.x) - pw / 2, sy(s.y) + ts * 0.45 - ph, pw, ph, ts * 0.22); c.fill(); c.shadowBlur = 0;
292
+ c.fillStyle = look.background; c.beginPath(); c.arc(sx(s.x) + s.facing * ts * 0.14, sy(s.y) - ts * 0.12, ts * 0.09, 0, Math.PI * 2); c.fill();
293
+ };
294
+
295
+ // ── the clock: the game steps at 1/60 s, drawn every frame ──
296
+ let acc = 0;
297
+ frame((dt) => {
298
+ // a pad, where one is plugged in
299
+ const pads = typeof navigator !== 'undefined' && navigator.getGamepads ? [...navigator.getGamepads()].filter(Boolean) : [];
300
+ if (live && pads.length && !skin) {
301
+ const p = pads[0], dir = (p.axes[0] > 0.4 || p.buttons[15]?.pressed ? 1 : 0) - (p.axes[0] < -0.4 || p.buttons[14]?.pressed ? 1 : 0), jump = !!(p.buttons[0]?.pressed || p.buttons[12]?.pressed);
302
+ const k = dir + ',' + jump; if (k !== padWas) { padWas = k; act('input', dir, jump); }
303
+ } else if (pads.length && skin && sim.actions.includes('input')) {
304
+ // a stick for the kits that are steered: the left stick (or the cross), A; a car: the triggers
305
+ const p = pads[0], dz = (v) => (Math.abs(v) < 0.25 ? 0 : Math.round(v * 10) / 10);
306
+ const ax = dz(p.axes[0] ?? 0) || (p.buttons[15]?.pressed ? 1 : p.buttons[14]?.pressed ? -1 : 0), ay = dz(p.axes[1] ?? 0) || (p.buttons[13]?.pressed ? 1 : p.buttons[12]?.pressed ? -1 : 0);
307
+ const args = loaded.kit.name === 'racing' ? [ax, p.buttons[7]?.pressed || p.buttons[0]?.pressed ? 1 : p.buttons[6]?.pressed || p.buttons[1]?.pressed ? -1 : 0] : [ax, ay, !!p.buttons[0]?.pressed];
308
+ const k = args.join(','); if (k !== padWas) { padWas = k; act('input', ...args); }
309
+ }
310
+ acc = Math.min(0.25, acc + dt);
311
+ while (acc >= 1 / 60) { sim.step(1 / 60); acc -= 1 / 60; }
312
+ const r = sim.report();
313
+ if (live || r.won || r.lost) say(r);
314
+ draw(dt);
315
+ metrics.frames++;
316
+ const now = performance.now();
317
+ if (metrics.firstFrame == null) metrics.firstFrame = now - metrics.start;
318
+ if (now - metrics.last >= 1000) { metrics.fps = Math.round((metrics.frames * 1000) / (now - metrics.last)); metrics.frames = 0; metrics.last = now; }
319
+ });
320
+
321
+ // ── what an agent may read and do (clarity mcp: clarity_games, clarity_read, clarity_act) ──
322
+ const actionNames = [...sim.actions, 'restart', 'next'];
323
+ root.__clarity_ai__ = {
324
+ component: 'Game',
325
+ readable: { state: () => sim.report(), level: () => li + 1, levels: () => loaded.levels.length, title: () => g.title, legal: () => (sim.legal ? sim.legal() : []) },
326
+ snapshot: () => ({ state: sim.report(), level: li + 1, levels: loaded.levels.length, title: g.title }),
327
+ read(name) { if (this.readable[name]) return this.readable[name](); throw new Error(`[Clarity AI] Game: "${name}" cannot be read (state, level, levels, title, legal)`); },
328
+ actionable: Object.fromEntries(actionNames.map((n) => [n, (...a) => (n === 'restart' ? restart(false) : n === 'next' ? restart(true) : act(n, ...a))])),
329
+ act(name, ...args) { if (this.actionable[name]) return this.actionable[name](...args); throw new Error(`[Clarity AI] Game: no action "${name}". Actions: ${actionNames.join(', ')}`); },
330
+ params: Object.fromEntries(actionNames.map((n) => [n, { swap: ['x', 'y', 'dir'], move: ['dir'], press: ['x', 'y'], input: ['dir', 'jump'], ...(skin?.params ?? {}) }[n] ?? []])),
331
+ docs: { swap: 'Swap a cell with its neighbour (dir: left, right, up, down)', move: 'Move the keeper or the gap (dir: left, right, up, down)', press: 'Press a light: it and its neighbours flip', input: 'Hold a direction (-1, 0, 1) and jump (true/false) until the next input', stop: 'Let go of everything', restart: 'Start this level again', next: 'Go to the next level', ...(skin?.docs ?? {}) },
332
+ batch(fn) { return fn(this); },
333
+ forbidden: [],
334
+ };
335
+ root.__clarityGame = { metrics: () => ({ ...metrics }), sim: () => sim, level: () => li, sound: () => ({ mood: sound.mood, muted: sound.muted, heard: [...sound.heard], running: !!sound.context && sound.context.state }) };
336
+ onDispose(() => { root.__clarityGame = null; sound.close(); });
337
+ say(sim.report());
338
+ return root;
339
+ }, 'Game');
340
+ }