@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/common.js ADDED
@@ -0,0 +1,100 @@
1
+ // @clarity-js/engine — what the kits share: settings clamped to their range, maps of strings, ways through a
2
+ // grid, small arithmetic. No DOM; plain data in, plain data out.
3
+
4
+ export const DT = 1 / 60;
5
+ export const clamp = (v, lo, hi) => (v < lo ? lo : v > hi ? hi : v);
6
+ export const round3 = (v) => Math.round(v * 1000) / 1000;
7
+ export const dist = (ax, ay, bx, by) => Math.hypot(ax - bx, ay - by);
8
+ export const median = (l) => { const s = [...l].sort((a, b) => a - b); return s.length ? (s.length % 2 ? s[s.length >> 1] : (s[(s.length >> 1) - 1] + s[s.length >> 1]) / 2) : 0; };
9
+
10
+ /** The game's settings for a kit, each within its range, the kit's value where the game has none. */
11
+ export function settingsFor(kitSettings, game) {
12
+ const out = {};
13
+ for (const [k, d] of Object.entries(kitSettings)) {
14
+ const v = Number(game?.settings?.[k]);
15
+ out[k] = Number.isFinite(v) ? clamp(v, d.min ?? -Infinity, d.max ?? Infinity) : d.value;
16
+ }
17
+ return out;
18
+ }
19
+
20
+ /** A map of strings → { w, h, at(x, y) → char, find(char) → [{ x, y }] }. */
21
+ export function readMap(map) {
22
+ const rows = (map ?? []).map(String);
23
+ const h = rows.length, w = Math.max(0, ...rows.map((r) => r.length));
24
+ return {
25
+ w, h, rows,
26
+ at: (x, y) => (y < 0 || y >= h || x < 0 || x >= w ? '#' : rows[y][x] ?? ' '),
27
+ find: (c) => { const out = []; for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) if (rows[y][x] === c) out.push({ x, y }); return out; },
28
+ };
29
+ }
30
+
31
+ /**
32
+ * The shortest way through a grid of cells, four ways, from (sx, sy) to the nearest cell `goal(x, y)` says
33
+ * yes to. `open(x, y)` says whether a cell can be walked. → [{ x, y }, …] (the cells after the start) or null.
34
+ */
35
+ export function bfs(w, h, sx, sy, open, goal, limit = 1e5) {
36
+ sx = Math.floor(sx); sy = Math.floor(sy);
37
+ if (sx < 0 || sy < 0 || sx >= w || sy >= h) return null;
38
+ const from = new Int32Array(w * h).fill(-1), start = sy * w + sx;
39
+ from[start] = start;
40
+ const queue = [start];
41
+ for (let qi = 0; qi < queue.length && qi < limit; qi++) {
42
+ const i = queue[qi], x = i % w, y = (i / w) | 0;
43
+ if (i !== start && goal(x, y)) {
44
+ const path = [];
45
+ for (let k = i; k !== start; k = from[k]) path.push({ x: k % w, y: (k / w) | 0 });
46
+ return path.reverse();
47
+ }
48
+ for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
49
+ const nx = x + dx, ny = y + dy, n = ny * w + nx;
50
+ if (nx < 0 || ny < 0 || nx >= w || ny >= h || from[n] >= 0 || !open(nx, ny)) continue;
51
+ from[n] = i; queue.push(n);
52
+ }
53
+ }
54
+ return null;
55
+ }
56
+
57
+ /** Cells a circle of radius r at (x, y) overlaps → is any of them solid? */
58
+ export function circleHits(x, y, r, solid) {
59
+ for (let cy = Math.floor(y - r); cy <= Math.floor(y + r); cy++) for (let cx = Math.floor(x - r); cx <= Math.floor(x + r); cx++) {
60
+ if (!solid(cx, cy)) continue;
61
+ const nx = clamp(x, cx, cx + 1), ny = clamp(y, cy, cy + 1);
62
+ if ((nx - x) ** 2 + (ny - y) ** 2 < r * r) return true;
63
+ }
64
+ return false;
65
+ }
66
+
67
+ /** Move a circle by (dx, dy) through a grid, one axis at a time, stopping at solid cells. → { x, y, hitX, hitY } */
68
+ export function slide(x, y, dx, dy, r, solid) {
69
+ let hitX = false, hitY = false;
70
+ const steps = Math.max(1, Math.ceil(Math.max(Math.abs(dx), Math.abs(dy)) / (r * 0.5)));
71
+ for (let i = 0; i < steps; i++) {
72
+ const nx = x + dx / steps;
73
+ if (!circleHits(nx, y, r, solid)) x = nx; else hitX = true;
74
+ const ny = y + dy / steps;
75
+ if (!circleHits(x, ny, r, solid)) y = ny; else hitY = true;
76
+ }
77
+ return { x, y, hitX, hitY };
78
+ }
79
+
80
+ /** Try a decision on a copy of the game and play `seconds` on: what sim.value() says then. The game is put back. */
81
+ export function lookAhead(sim, decide, seconds, after) {
82
+ const snap = sim.snapshot(), n = sim.log.length;
83
+ decide();
84
+ for (let t = 0; t < seconds && !sim.state.won && !sim.state.lost; t += DT) { after?.(t); sim.step(DT); }
85
+ const v = sim.value();
86
+ sim.restore(snap); sim.log.length = n;
87
+ return v;
88
+ }
89
+
90
+ /** Keep the hooks a game gives on top of a kit: setup after the kit's, step after the kit's, won/lost as extra ends. */
91
+ export function hooked(hooks, kitActions) {
92
+ return {
93
+ actions: { ...kitActions, ...(hooks.actions ?? {}) },
94
+ end(s, ctx) {
95
+ if (s.won || s.lost) return;
96
+ if (hooks.won?.(s)) { s.won = true; ctx.emit({ type: 'won' }); }
97
+ else if (hooks.lost?.(s)) { s.lost = true; ctx.emit({ type: 'lost', why: 'rules' }); }
98
+ },
99
+ };
100
+ }
package/src/editor.js ADDED
@@ -0,0 +1,285 @@
1
+ // @clarity-js/engine/editor — a level editor in the page. Maps of characters (platformer, top-down, push
2
+ // puzzles) are painted cell by cell; every other level is a form of its numbers. Play tries the level where it is
3
+ // edited; Ask the bots plays it with the bots and says how often each one finishes it, and what to change.
4
+ // game.json is the only thing it writes: what it hands back (onChange, download) is the game as the engine reads it.
5
+ //
6
+ // import { mountEditor } from '@clarity-js/engine/editor'
7
+ // mountEditor(document.getElementById('editor'), game, rules, { onChange: (game) => save(game) })
8
+
9
+ import { mount, _component, onDispose, _css } from '@ozsarman/clarityjs/runtime';
10
+ import { loadGame, play, validateGame, levelChanges } from './index.js';
11
+ import { mountGame } from './view.js';
12
+ import { lookOf } from './make.js';
13
+
14
+ const CSS = `
15
+ .cge-ed{display:grid;grid-template-columns:minmax(0,1fr) 260px;gap:14px;font:14px/1.4 system-ui,-apple-system,"Segoe UI",sans-serif;color:#1f2933}
16
+ .cge-ed *{box-sizing:border-box}
17
+ .cge-ed-main{display:flex;flex-direction:column;gap:10px;min-width:0}
18
+ .cge-ed-bar{display:flex;flex-wrap:wrap;gap:6px;align-items:center}
19
+ .cge-ed button{font:inherit;font-weight:600;border:1px solid #d5dbe1;background:#fff;border-radius:8px;padding:6px 11px;cursor:pointer;color:inherit}
20
+ .cge-ed button[aria-pressed=true]{background:#1f2933;color:#fff;border-color:#1f2933}
21
+ .cge-ed button:disabled{opacity:.45;cursor:default}
22
+ .cge-ed-stage{position:relative;height:440px;border:1px solid #d5dbe1;border-radius:10px;overflow:hidden;background:#f7f8fa}
23
+ .cge-ed-stage canvas{width:100%;height:100%;display:block;touch-action:none;cursor:crosshair}
24
+ .cge-ed-side{display:flex;flex-direction:column;gap:12px}
25
+ .cge-ed-side h3{margin:0 0 6px;font-size:13px;font-weight:700;color:#52606d}
26
+ .cge-ed-tiles{display:grid;grid-template-columns:repeat(2,1fr);gap:5px}
27
+ .cge-ed-tiles button{display:flex;gap:7px;align-items:center;text-align:left;padding:5px 7px;font-weight:500}
28
+ .cge-ed-tiles i{display:inline-grid;place-items:center;width:22px;height:22px;border-radius:5px;font:700 12px ui-monospace,monospace;font-style:normal;flex:none}
29
+ .cge-ed-form label{display:grid;grid-template-columns:1fr 92px;gap:6px;align-items:center;margin-bottom:6px;font-size:13px}
30
+ .cge-ed-form input,.cge-ed-form textarea{font:inherit;font-size:13px;border:1px solid #d5dbe1;border-radius:6px;padding:4px 6px;width:100%}
31
+ .cge-ed-form textarea{grid-column:1/-1;height:120px;font-family:ui-monospace,monospace;font-size:12px}
32
+ .cge-ed-out{font-size:13px;margin:0;padding-left:16px}
33
+ .cge-ed-out li{margin:2px 0}
34
+ .cge-ed-bad{color:#b42318}
35
+ .cge-ed-ok{color:#1a7f37}
36
+ .cge-ed-ask{display:flex;gap:6px;margin-bottom:6px}
37
+ .cge-ed-ask input{flex:1;min-width:0;font:inherit;font-size:13px;border:1px solid #d5dbe1;border-radius:6px;padding:5px 7px}
38
+ @media (max-width:760px){.cge-ed{grid-template-columns:1fr}.cge-ed-stage{height:360px}}
39
+ `;
40
+
41
+ /** What each map character is, per kit: its label and how it is drawn in the editor. */
42
+ export const TILES = {
43
+ platformer: [['#', 'Ground', 0], ['-', 'Ledge', 3], ['@', 'Start', 2], ['D', 'Door', 2], ['o', 'Coin', 4], ['E', 'Walker', 1], ['^', 'Spikes', 1], ['C', 'Checkpoint', 3], [' ', 'Air', -1]],
44
+ 'top-down': [['#', 'Wall', 0], ['.', 'Floor', -1], ['@', 'Start', 2], ['X', 'Way out', 2], ['E', 'Chaser', 1], ['S', 'Sentry', 1], ['k', 'Key', 4], ['L', 'Locked door', 4], ['o', 'Gem', 3], ['h', 'Heart', 1]],
45
+ push: [['#', 'Wall', 0], [' ', 'Floor', -1], ['@', 'Keeper', 2], ['$', 'Crate', 3], ['.', 'Mark', 4], ['*', 'Crate on mark', 1]],
46
+ };
47
+
48
+ const mapKind = (game, level) => (game.kit === 'platformer' ? 'platformer' : game.kit === 'top-down' ? 'top-down' : game.kit === 'puzzle-grid' && level?.goal === 'push' ? 'push' : null);
49
+ const clone = (x) => JSON.parse(JSON.stringify(x));
50
+
51
+ /**
52
+ * @param {Element} el
53
+ * @param {object} game game.json
54
+ * @param {object} [rules] rules.js's default export (for Play and the bots)
55
+ * @param {{ onChange?: (game: object) => void, level?: number }} [options]
56
+ * @returns {() => void} unmount
57
+ */
58
+ export function mountEditor(el, game, rules = {}, options = {}) {
59
+ return mount(() => LevelEditor({ game, rules, ...options }), el);
60
+ }
61
+
62
+ export function LevelEditor({ game: start, rules = {}, onChange, level: startLevel = 0 } = {}) {
63
+ return _component(() => {
64
+ _css('clarity-engine-editor', CSS);
65
+ let game = clone(start), li = Math.min(startLevel, (game.levels?.length ?? 1) - 1), tile = null, painting = false, playing = null;
66
+ const undo = [], redo = [];
67
+ const h = (tag, props = {}, ...kids) => { const e = document.createElement(tag); for (const [k, v] of Object.entries(props)) { if (k.startsWith('on')) e.addEventListener(k.slice(2), v); else if (v != null) e.setAttribute(k, v); } e.append(...kids.flat().filter((k) => k != null)); return e; };
68
+ const root = h('div', { class: 'cge-ed' });
69
+ const levelsBar = h('div', { class: 'cge-ed-bar', role: 'group', 'aria-label': 'Levels' });
70
+ const tools = h('div', { class: 'cge-ed-bar' });
71
+ const canvas = h('canvas', { 'aria-label': 'The level: click or drag to paint the chosen tile; right-click clears' });
72
+ const stage = h('div', { class: 'cge-ed-stage' }, canvas);
73
+ const side = h('div', { class: 'cge-ed-side' });
74
+ const tilesBox = h('div'), formBox = h('div', { class: 'cge-ed-form' }), botsOut = h('ul', { class: 'cge-ed-out', 'aria-live': 'polite' }), problems = h('ul', { class: 'cge-ed-out' });
75
+ // what is asked of the agent, and what it did
76
+ const requests = [], askInput = h('input', { placeholder: 'Make this level harder…', 'aria-label': 'A request for the agent' }), askList = h('ul', { class: 'cge-ed-out', 'aria-live': 'polite' });
77
+ let nextId = 1;
78
+ const askForm = h('form', { class: 'cge-ed-ask', onsubmit: (e) => { e.preventDefault(); const text = askInput.value.trim(); if (!text) return; requests.push({ id: nextId++, level: li, text, done: false, answer: null }); askInput.value = ''; renderAsk(); } }, askInput, h('button', { type: 'submit' }, 'Ask'));
79
+ const renderAsk = () => askList.replaceChildren(...requests.slice(-5).map((r) => h('li', { class: r.done ? 'cge-ed-ok' : '' }, `${r.done ? '✓' : '…'} ${r.text}${r.answer ? ' — ' + r.answer : r.done ? '' : ' (waiting for the agent)'}`)));
80
+ side.append(tilesBox, formBox, h('div', {}, h('h3', {}, 'The bots'), botsOut), h('div', {}, h('h3', {}, 'Ask the agent'), askForm, askList), h('div', {}, h('h3', {}, 'Checks'), problems));
81
+ root.append(h('div', { class: 'cge-ed-main' }, levelsBar, tools, stage), side);
82
+
83
+ const lv = () => game.levels[li];
84
+ const pal = lookOf(game).palette;
85
+ const changed = (record = true) => {
86
+ if (record) redo.length = 0;
87
+ const v = validateGame(game);
88
+ problems.replaceChildren(...(v.ok && !v.warnings.length ? [h('li', { class: 'cge-ed-ok' }, 'game.json has no mistakes')] : [...v.errors.map((e) => h('li', { class: 'cge-ed-bad' }, `${e.path || '(top)'}: ${e.message}${e.fix ? ' — ' + e.fix : ''}`)), ...v.warnings.map((w) => h('li', {}, `${w.path}: ${w.message}`))]));
89
+ onChange?.(clone(game));
90
+ renderBars(); render();
91
+ };
92
+ const snapshot = () => { undo.push(JSON.stringify(game)); if (undo.length > 200) undo.shift(); };
93
+
94
+ // ── levels and tools ──
95
+ const renderBars = () => {
96
+ levelsBar.replaceChildren(
97
+ ...game.levels.map((l, i) => h('button', { 'aria-pressed': String(i === li), onclick: () => { stopPlay(); li = i; renderAll(); } }, l.id ?? `l${i + 1}`)),
98
+ h('button', { title: 'A copy of this level, after it', onclick: () => { snapshot(); const copy = clone(lv()); copy.id = `l${game.levels.length + 1}`; game.levels.splice(li + 1, 0, copy); li++; changed(); renderAll(); } }, '+ Level'),
99
+ h('button', { disabled: game.levels.length < 2 ? '' : null, onclick: () => { if (game.levels.length < 2) return; snapshot(); game.levels.splice(li, 1); li = Math.max(0, li - 1); changed(); renderAll(); } }, 'Delete'),
100
+ );
101
+ const kind = mapKind(game, lv());
102
+ tools.replaceChildren(
103
+ h('button', { disabled: undo.length ? null : '', onclick: () => { if (!undo.length) return; redo.push(JSON.stringify(game)); game = JSON.parse(undo.pop()); li = Math.min(li, game.levels.length - 1); changed(false); renderAll(); } }, 'Undo'),
104
+ h('button', { disabled: redo.length ? null : '', onclick: () => { if (!redo.length) return; undo.push(JSON.stringify(game)); game = JSON.parse(redo.pop()); changed(false); renderAll(); } }, 'Redo'),
105
+ ...(kind ? [
106
+ h('button', { title: 'One column more on the right', onclick: () => resize(1, 0) }, '+ Column'), h('button', { onclick: () => resize(-1, 0) }, '− Column'),
107
+ h('button', { title: 'One row more at the top', onclick: () => resize(0, 1) }, '+ Row'), h('button', { onclick: () => resize(0, -1) }, '− Row'),
108
+ ] : []),
109
+ h('button', { title: 'The kit\'s smallest change that makes it easier', disabled: levelChanges(game, lv(), 'easier').length ? null : '', onclick: () => change('easier') }, 'Easier'),
110
+ h('button', { title: 'The kit\'s smallest change that makes it harder', disabled: levelChanges(game, lv(), 'harder').length ? null : '', onclick: () => change('harder') }, 'Harder'),
111
+ h('button', { 'aria-pressed': String(!!playing), onclick: () => (playing ? stopPlay() : startPlay()) }, playing ? 'Back to editing' : 'Play'),
112
+ h('button', { onclick: askBots }, 'Ask the bots'),
113
+ h('button', { onclick: download }, 'Download game.json'),
114
+ );
115
+ };
116
+ const renderSide = () => {
117
+ const kind = mapKind(game, lv());
118
+ tilesBox.replaceChildren();
119
+ formBox.replaceChildren();
120
+ if (kind) {
121
+ tile ??= TILES[kind][0][0];
122
+ if (!TILES[kind].some((t) => t[0] === tile)) tile = TILES[kind][0][0];
123
+ tilesBox.append(h('h3', {}, 'Tiles'), h('div', { class: 'cge-ed-tiles', role: 'group', 'aria-label': 'Tiles' }, TILES[kind].map(([ch, label, ci]) => {
124
+ const sw = h('i', {}, ch === ' ' ? '' : ch); sw.style.background = ci < 0 ? '#ffffff' : pal[ci % pal.length]; sw.style.color = ci < 0 ? '#52606d' : '#ffffff'; sw.style.border = '1px solid #d5dbe1';
125
+ return h('button', { 'aria-pressed': String(tile === ch), onclick: () => { tile = ch; renderSide(); } }, sw, label);
126
+ })));
127
+ }
128
+ // every other field of the level, as a number or as JSON
129
+ const l = lv();
130
+ formBox.append(h('h3', {}, kind ? 'This level' : 'This level\'s numbers'));
131
+ for (const [k, v] of Object.entries(l)) {
132
+ if (k === 'map' || k === 'heights') continue;
133
+ if (typeof v === 'number') formBox.append(h('label', {}, k, h('input', { type: 'number', value: String(v), step: Number.isInteger(v) ? '1' : '0.01', onchange: (e) => { const n = Number(e.target.value); if (!Number.isFinite(n)) return; snapshot(); l[k] = n; changed(); } })));
134
+ else if (typeof v === 'string') formBox.append(h('label', {}, k, h('input', { value: v, onchange: (e) => { snapshot(); l[k] = e.target.value; changed(); } })));
135
+ }
136
+ const rest = Object.fromEntries(Object.entries(l).filter(([k, v]) => typeof v === 'object' && v !== null && k !== 'map'));
137
+ if (Object.keys(rest).length) {
138
+ const ta = h('textarea', { 'aria-label': 'The rest of the level, as JSON', spellcheck: 'false' }); ta.value = JSON.stringify(rest, null, 1);
139
+ ta.addEventListener('change', () => { try { const o = JSON.parse(ta.value); snapshot(); Object.assign(l, o); changed(); } catch (e) { problems.prepend(h('li', { class: 'cge-ed-bad' }, 'That is not JSON: ' + e.message)); } });
140
+ formBox.append(h('label', {}, ta));
141
+ }
142
+ };
143
+
144
+ // ── the map ──
145
+ let geo = null;
146
+ const map = () => lv().map;
147
+ const resize = (dw, dh) => {
148
+ const m = map(); if (!m) return;
149
+ snapshot();
150
+ const fill = mapKind(game, lv()) === 'top-down' ? '#' : ' ';
151
+ let rows = m.map((r) => (dw > 0 ? r + fill.repeat(dw) : dw < 0 ? r.slice(0, Math.max(2, r.length + dw)) : r));
152
+ if (dh > 0) rows = [...Array.from({ length: dh }, () => fill.repeat(rows[0].length)), ...rows];
153
+ if (dh < 0 && rows.length > 2) rows = rows.slice(-dh);
154
+ lv().map = rows; changed();
155
+ };
156
+ const paint = (x, y, ch) => {
157
+ const m = map(); if (!m || y < 0 || y >= m.length || x < 0) return false;
158
+ const row = m[y].padEnd(x + 1, ' ');
159
+ if (row[x] === ch) return false;
160
+ // one start, one door, one way out: painting another moves it
161
+ if ('@DX'.includes(ch)) for (let k = 0; k < m.length; k++) if (m[k].includes(ch)) m[k] = m[k].replaceAll(ch, mapKind(game, lv()) === 'top-down' ? '.' : ' ');
162
+ const r2 = m[y].padEnd(x + 1, ' ');
163
+ m[y] = r2.slice(0, x) + ch + r2.slice(x + 1);
164
+ return true;
165
+ };
166
+ const at = (e) => { if (!geo) return null; const r = canvas.getBoundingClientRect(); return { x: Math.floor((e.clientX - r.left - geo.ox) / geo.cs), y: Math.floor((e.clientY - r.top - geo.oy) / geo.cs) }; };
167
+ canvas.addEventListener('contextmenu', (e) => e.preventDefault());
168
+ canvas.addEventListener('pointerdown', (e) => {
169
+ if (playing || !map()) return;
170
+ const p = at(e); if (!p) return;
171
+ snapshot(); painting = e.button === 2 ? 'erase' : 'paint'; canvas.setPointerCapture?.(e.pointerId);
172
+ const empty = mapKind(game, lv()) === 'top-down' ? '.' : ' ';
173
+ if (paint(p.x, p.y, painting === 'erase' ? empty : tile)) { render(); } else undo.pop();
174
+ });
175
+ canvas.addEventListener('pointermove', (e) => {
176
+ if (!painting || '@DX'.includes(tile)) return;
177
+ const p = at(e); if (!p) return;
178
+ const empty = mapKind(game, lv()) === 'top-down' ? '.' : ' ';
179
+ if (paint(p.x, p.y, painting === 'erase' ? empty : tile)) render();
180
+ });
181
+ const endPaint = () => { if (painting) { painting = false; changed(); } };
182
+ canvas.addEventListener('pointerup', endPaint); canvas.addEventListener('pointercancel', endPaint);
183
+
184
+ const render = () => {
185
+ if (playing) return;
186
+ const w = stage.clientWidth || 640, hh = stage.clientHeight || 440, dpr = Math.min(2, globalThis.devicePixelRatio || 1);
187
+ canvas.width = Math.round(w * dpr); canvas.height = Math.round(hh * dpr);
188
+ const c = canvas.getContext('2d'); c.setTransform(dpr, 0, 0, dpr, 0, 0); c.clearRect(0, 0, w, hh);
189
+ const m = map(), kind = mapKind(game, lv());
190
+ if (!m || !kind) {
191
+ c.fillStyle = '#52606d'; c.font = '600 15px system-ui,sans-serif'; c.textAlign = 'center';
192
+ c.fillText(`A ${game.kit}${lv().goal ? ' (' + lv().goal + ')' : ''} level is its numbers: change them on the right, then Play.`, w / 2, hh / 2, w - 40);
193
+ geo = null; return;
194
+ }
195
+ const cols = Math.max(...m.map((r) => r.length)), rows = m.length, cs = Math.max(8, Math.floor(Math.min((w - 20) / cols, (hh - 20) / rows))), ox = Math.floor((w - cs * cols) / 2), oy = Math.floor((hh - cs * rows) / 2);
196
+ geo = { cs, ox, oy };
197
+ const info = Object.fromEntries(TILES[kind].map(([ch, , ci]) => [ch, ci]));
198
+ for (let y = 0; y < rows; y++) for (let x = 0; x < cols; x++) {
199
+ const ch = m[y][x] ?? ' ', ci = info[ch] ?? -1, px = ox + x * cs, py = oy + y * cs;
200
+ c.fillStyle = (x + y) % 2 ? '#ffffff' : '#f1f3f5'; c.fillRect(px, py, cs, cs);
201
+ if (ci >= 0) { c.fillStyle = pal[ci % pal.length]; const inset = ch === '#' ? 0 : cs * 0.12; c.fillRect(px + inset, py + inset, cs - inset * 2, cs - inset * 2); }
202
+ if (ch !== '#' && ch !== ' ' && ch !== '.' && cs >= 14) { c.fillStyle = '#ffffff'; c.font = `700 ${Math.round(cs * 0.5)}px ui-monospace,monospace`; c.textAlign = 'center'; c.textBaseline = 'middle'; c.fillText(ch, px + cs / 2, py + cs / 2 + 1); }
203
+ }
204
+ c.strokeStyle = 'rgba(31,41,51,.08)'; c.lineWidth = 1;
205
+ for (let x = 0; x <= cols; x++) { c.beginPath(); c.moveTo(ox + x * cs + 0.5, oy); c.lineTo(ox + x * cs + 0.5, oy + rows * cs); c.stroke(); }
206
+ for (let y = 0; y <= rows; y++) { c.beginPath(); c.moveTo(ox, oy + y * cs + 0.5); c.lineTo(ox + cols * cs, oy + y * cs + 0.5); c.stroke(); }
207
+ };
208
+
209
+ // ── easier, harder; the agent's answer ──
210
+ function change(way) {
211
+ const c = levelChanges(game, lv(), way)[0];
212
+ if (!c) return;
213
+ snapshot(); Object.assign(lv(), clone(c.change));
214
+ changed(); renderSide();
215
+ botsOut.replaceChildren(h('li', {}, `${way === 'harder' ? 'Harder' : 'Easier'}: ${c.say}.`));
216
+ setTimeout(askBots, 0);
217
+ }
218
+ function setLevel(index, level, note = '', request = null) {
219
+ const i = Number.isInteger(index) ? index : li;
220
+ if (!game.levels[i]) throw new Error(`[Clarity AI] LevelEditor: no level ${i} (there are ${game.levels.length})`);
221
+ const next = clone(game); next.levels[i] = typeof level === 'string' ? JSON.parse(level) : clone(level);
222
+ const v = validateGame(next);
223
+ if (!v.ok) throw new Error('[Clarity AI] LevelEditor: that level has mistakes: ' + v.errors.map((e) => `${e.path}: ${e.message}${e.fix ? ' (' + e.fix + ')' : ''}`).join('; '));
224
+ snapshot(); game = next; li = i;
225
+ const r = requests.find((q) => q.id === request) ?? requests.find((q) => !q.done && q.level === i);
226
+ if (r) { r.done = true; r.answer = note || 'done'; }
227
+ botsOut.replaceChildren(h('li', {}, `The agent changed ${game.levels[i].id ?? 'level ' + (i + 1)}${note ? ': ' + note : ''}. Undo takes it back.`));
228
+ changed(); renderAll(); renderAsk();
229
+ return { level: i, ok: true };
230
+ }
231
+ root.__clarity_ai__ = {
232
+ component: 'LevelEditor',
233
+ readable: { game: () => clone(game), level: () => li, requests: () => requests.filter((r) => !r.done).map((r) => ({ ...r })), kit: () => game.kit },
234
+ snapshot: () => ({ level: li, levels: game.levels.length, kit: game.kit, requests: requests.filter((r) => !r.done).map((r) => ({ id: r.id, level: r.level, text: r.text })) }),
235
+ read(name) { if (this.readable[name]) return this.readable[name](); throw new Error(`[Clarity AI] LevelEditor: "${name}" cannot be read (game, level, requests, kit)`); },
236
+ actionable: { setLevel, answer: (request, text) => { const r = requests.find((q) => q.id === request); if (!r) throw new Error(`[Clarity AI] LevelEditor: no request ${request}`); r.done = true; r.answer = String(text); renderAsk(); return true; }, select: (i) => { li = Math.max(0, Math.min(game.levels.length - 1, i)); renderAll(); return li; } },
237
+ act(name, ...args) { if (this.actionable[name]) return this.actionable[name](...args); throw new Error(`[Clarity AI] LevelEditor: no action "${name}" (setLevel, answer, select)`); },
238
+ params: { setLevel: ['index', 'level', 'note', 'request'], answer: ['request', 'text'], select: ['index'] },
239
+ docs: { setLevel: 'Put a new level (its game.json object) at index; it is checked first, comes in as a step Undo takes back, and answers the request it names (or the oldest on that level)', answer: 'Answer a request in words, without changing the level', select: 'Show another level' },
240
+ batch(fn) { return fn(this); },
241
+ forbidden: [],
242
+ };
243
+
244
+ // ── play, the bots, download ──
245
+ const only = () => ({ ...clone(game), levels: [clone(lv())] });
246
+ function startPlay() {
247
+ const v = validateGame(only());
248
+ if (!v.ok) { changed(false); return; }
249
+ canvas.style.display = 'none';
250
+ const box = h('div'); box.style.cssText = 'position:absolute;inset:0';
251
+ stage.append(box);
252
+ playing = { box, unmount: mountGame(box, only(), rules) };
253
+ box.firstElementChild?.focus();
254
+ renderBars();
255
+ }
256
+ function stopPlay() { if (!playing) return; playing.unmount(); playing.box.remove(); playing = null; canvas.style.display = ''; renderBars(); render(); }
257
+ function askBots() {
258
+ const v = validateGame(only());
259
+ if (!v.ok) { botsOut.replaceChildren(h('li', { class: 'cge-ed-bad' }, 'Fix the mistakes first (Checks, below).')); return; }
260
+ botsOut.replaceChildren(h('li', {}, 'Playing…'));
261
+ setTimeout(() => {
262
+ try {
263
+ const report = play(loadGame(only(), rules), { seeds: 3 });
264
+ const l = report.levels[0];
265
+ botsOut.replaceChildren(
266
+ ...Object.entries(l.bots).map(([b, x]) => h('li', {}, `${b}: ${Math.round(x.rate * 100)}% finished${x.time != null ? `, ${x.time} s` : x.moves != null ? `, ${x.moves} moves` : ''}`)),
267
+ ...report.checks.filter((k) => !k.name.startsWith('gets harder')).map((k) => h('li', { class: k.pass ? 'cge-ed-ok' : k.soft ? '' : 'cge-ed-bad' }, `${k.pass ? '✓' : k.soft ? '·' : '✗'} ${k.name.replace(/^l\d+ /, 'it ')}${k.fix ? ' — ' + k.fix.say : ''}`)),
268
+ );
269
+ } catch (e) { botsOut.replaceChildren(h('li', { class: 'cge-ed-bad' }, e.message)); }
270
+ }, 30);
271
+ }
272
+ function download() {
273
+ const a = h('a', { href: URL.createObjectURL(new Blob([JSON.stringify(game, null, 2) + '\n'], { type: 'application/json' })), download: 'game.json' });
274
+ a.click(); setTimeout(() => URL.revokeObjectURL(a.href), 1000);
275
+ }
276
+
277
+ const renderAll = () => { renderBars(); renderSide(); render(); };
278
+ const ro = typeof ResizeObserver === 'function' ? new ResizeObserver(() => render()) : null;
279
+ ro?.observe(stage);
280
+ onDispose(() => { ro?.disconnect(); if (playing) playing.unmount(); });
281
+ root.__clarityEditor = { game: () => clone(game), level: () => li, paint: (x, y, ch) => { snapshot(); const ok = paint(x, y, ch); changed(); return ok; }, select: (i) => { li = i; renderAll(); }, ask: askBots, play: startPlay, stop: stopPlay, change, requests: () => requests.map((r) => ({ ...r })) };
282
+ queueMicrotask(() => { renderAll(); changed(false); });
283
+ return root;
284
+ }, 'LevelEditor');
285
+ }