@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/topdown.js ADDED
@@ -0,0 +1,319 @@
1
+ // @clarity-js/engine — the top-down kit: walk four ways through rooms, swing at what chases you, find the key,
2
+ // reach the way out.
3
+ //
4
+ // A level is a map, one string a row:
5
+ // # wall . or space: floor @ where you start X the way out (the goal)
6
+ // E a chaser S a sentry (stands, throws at you when it sees you)
7
+ // k a key L a locked door (a key opens it) h a heart o a gem
8
+ //
9
+ // Input is held, as a stick: input(dx, dy, attack) with dx, dy from −1 to 1 and attack true while pressed;
10
+ // attack(dx, dy) swings once toward a direction. `level.gems` asks for that many gems before the way out opens.
11
+
12
+ import { createSim } from '@ozsarman/clarityjs/sim';
13
+ import { DT, clamp, round3, dist, settingsFor, readMap, bfs, slide, lookAhead, hooked } from './common.js';
14
+
15
+ export const kit = {
16
+ name: 'top-down',
17
+ title: 'Top-down',
18
+ describe: 'Walk four ways through rooms, swing at what chases you, find the key and reach the way out.',
19
+ settings: {
20
+ speed: { value: 4.2, min: 1, max: 12, unit: 'tiles/s' },
21
+ hp: { value: 5, min: 1, max: 20 },
22
+ reach: { value: 1.25, min: 0.6, max: 3, unit: 'tiles' },
23
+ cooldown: { value: 0.35, min: 0.1, max: 2, unit: 's' },
24
+ enemySpeed: { value: 2.4, min: 0, max: 10, unit: 'tiles/s' },
25
+ sight: { value: 6, min: 1, max: 20, unit: 'tiles' },
26
+ enemyHp: { value: 2, min: 1, max: 10 },
27
+ },
28
+ level: { map: ['###########', '#@...#...X#', '#.E..L..E.#', '#..k.#....#', '###########'] },
29
+ examples: ['A twin-stick dungeon crawl in neon halls', 'Find the key in a maze of overgrown ruins', 'Clear the haunted cellar room by room'],
30
+ input: ['keys', 'touch', 'pad'],
31
+ continuous: true,
32
+ controls: 'axes',
33
+ };
34
+
35
+ const R = 0.32; // the walker's radius, in tiles
36
+
37
+ function parse(map) {
38
+ const m = readMap(map);
39
+ const walls = new Array(m.w * m.h).fill(0); // 0 floor, 1 wall, 2 locked door
40
+ const s = { w: m.w, h: m.h, enemies: [], keys: [], gems: [], hearts: [], exit: null, start: null };
41
+ for (let y = 0; y < m.h; y++) for (let x = 0; x < m.w; x++) {
42
+ const c = m.at(x, y), i = y * m.w + x, at = { x: x + 0.5, y: y + 0.5 };
43
+ if (c === '#') walls[i] = 1;
44
+ else if (c === 'L') walls[i] = 2;
45
+ else if (c === '@') s.start = at;
46
+ else if (c === 'X') s.exit = at;
47
+ else if (c === 'E' || c === 'S') s.enemies.push({ ...at, kind: c === 'E' ? 'chaser' : 'sentry', hp: 0, alive: true, cool: 0, vx: 0, vy: 0, home: { ...at }, seen: false });
48
+ else if (c === 'k') s.keys.push({ ...at, got: false });
49
+ else if (c === 'o') s.gems.push({ ...at, got: false });
50
+ else if (c === 'h') s.hearts.push({ ...at, got: false });
51
+ }
52
+ if (!s.start) throw new Error('a top-down level needs a start: @ in its map');
53
+ if (!s.exit) throw new Error('a top-down level needs a way out: X in its map');
54
+ return { ...s, walls };
55
+ }
56
+
57
+ const wallAt = (s, x, y) => (x < 0 || y < 0 || x >= s.w || y >= s.h ? 1 : s.walls[y * s.w + x]);
58
+ const solid = (s) => (x, y) => wallAt(s, x, y) !== 0;
59
+
60
+ /** Can a straight line from a to b pass without a wall? (for sight and throws) */
61
+ function clear(s, ax, ay, bx, by) {
62
+ const n = Math.ceil(dist(ax, ay, bx, by) * 3);
63
+ for (let i = 1; i < n; i++) { const t = i / n; if (wallAt(s, Math.floor(ax + (bx - ax) * t), Math.floor(ay + (by - ay) * t))) return false; }
64
+ return true;
65
+ }
66
+
67
+ function setup(level, cfg, rng) {
68
+ const m = parse(level.map);
69
+ for (const e of m.enemies) { e.hp = e.kind === 'sentry' ? Math.max(1, cfg.enemyHp - 1) : cfg.enemyHp; e.phase = rng() * 6.283; e.cool = rng() * 1.2; }
70
+ return {
71
+ ...m, cfg, x: m.start.x, y: m.start.y, fx: 0, fy: 1, ix: 0, iy: 0, attackHeld: false,
72
+ hp: cfg.hp, hurt: 0, cool: 0, swing: 0, carrying: 0, gemsGot: 0, needGems: Number(level.gems ?? 0) || 0,
73
+ shots: [], deaths: [], score: 0, won: false, lost: false, t: 0, time: Number(level.time ?? 0) || 0, best: 0,
74
+ };
75
+ }
76
+
77
+ function hit(s, ctx, why, dmg = 1) {
78
+ if (s.hurt > 0 || s.won || s.lost) return;
79
+ s.hp -= dmg; s.hurt = 1;
80
+ s.deaths.push({ x: round3(s.x), y: round3(s.y), why, t: round3(s.t) });
81
+ ctx.emit({ type: 'hurt', why, hp: s.hp });
82
+ if (s.hp <= 0) { s.lost = true; ctx.emit({ type: 'lost', why }); }
83
+ }
84
+
85
+ function swing(s, ctx, dx, dy) {
86
+ if (s.cool > 0) return false;
87
+ const l = Math.hypot(dx, dy);
88
+ if (l > 0.01) { s.fx = dx / l; s.fy = dy / l; }
89
+ s.cool = s.cfg.cooldown; s.swing = 0.15;
90
+ ctx.emit({ type: 'swing', x: s.x, y: s.y, fx: s.fx, fy: s.fy });
91
+ for (const e of s.enemies) {
92
+ if (!e.alive) continue;
93
+ const ex = e.x - s.x, ey = e.y - s.y, d = Math.hypot(ex, ey);
94
+ if (d > s.cfg.reach + 0.3 || (d > 0.4 && (ex * s.fx + ey * s.fy) / d < 0.2)) continue;
95
+ e.hp--; e.vx = ex / (d || 1) * 6; e.vy = ey / (d || 1) * 6; e.cool = Math.max(e.cool, 0.4);
96
+ ctx.emit({ type: 'strike', x: e.x, y: e.y });
97
+ if (e.hp <= 0) { e.alive = false; s.score += 50; ctx.emit({ type: 'defeat', x: e.x, y: e.y }); }
98
+ }
99
+ return true;
100
+ }
101
+
102
+ function step(s, dt, ctx) {
103
+ if (s.won || s.lost) return;
104
+ const cfg = s.cfg;
105
+ s.t += dt; s.hurt = Math.max(0, s.hurt - dt); s.cool = Math.max(0, s.cool - dt); s.swing = Math.max(0, s.swing - dt);
106
+ // the walker
107
+ let ix = s.ix, iy = s.iy; const l = Math.hypot(ix, iy);
108
+ if (l > 1) { ix /= l; iy /= l; }
109
+ if (l > 0.1) { const fl = Math.hypot(ix, iy); s.fx = ix / fl; s.fy = iy / fl; }
110
+ const moved = slide(s.x, s.y, ix * cfg.speed * dt, iy * cfg.speed * dt, R, solid(s));
111
+ s.x = moved.x; s.y = moved.y;
112
+ if (s.attackHeld) swing(s, ctx, s.fx, s.fy);
113
+ // a locked door touched with a key in hand opens
114
+ if (s.carrying > 0) for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
115
+ const cx = Math.floor(s.x + dx * (R + 0.15)), cy = Math.floor(s.y + dy * (R + 0.15));
116
+ if (wallAt(s, cx, cy) === 2) { s.walls[cy * s.w + cx] = 0; s.carrying--; ctx.emit({ type: 'unlock', x: cx, y: cy }); break; }
117
+ }
118
+ for (const k of s.keys) if (!k.got && dist(k.x, k.y, s.x, s.y) < 0.6) { k.got = true; s.carrying++; ctx.emit({ type: 'key' }); }
119
+ for (const g of s.gems) if (!g.got && dist(g.x, g.y, s.x, s.y) < 0.6) { g.got = true; s.gemsGot++; s.score += 10; ctx.emit({ type: 'gem' }); }
120
+ for (const h of s.hearts) if (!h.got && s.hp < cfg.hp && dist(h.x, h.y, s.x, s.y) < 0.6) { h.got = true; s.hp++; ctx.emit({ type: 'heal' }); }
121
+ // what is against you
122
+ for (const e of s.enemies) {
123
+ if (!e.alive) continue;
124
+ e.cool = Math.max(0, e.cool - dt);
125
+ const d = dist(e.x, e.y, s.x, s.y);
126
+ const sees = d < cfg.sight && clear(s, e.x, e.y, s.x, s.y);
127
+ if (sees) e.seen = true;
128
+ let vx = e.vx * Math.max(0, 1 - dt * 8), vy = e.vy * Math.max(0, 1 - dt * 8); // a knock fades
129
+ if (e.kind === 'chaser') {
130
+ const tx = e.seen ? s.x : e.home.x + Math.sin(s.t * 0.7 + e.phase) * 1.2, ty = e.seen ? s.y : e.home.y + Math.cos(s.t * 0.6 + e.phase) * 1.2;
131
+ const ex = tx - e.x, ey = ty - e.y, el = Math.hypot(ex, ey) || 1;
132
+ if (e.cool <= 0.2) { vx += ex / el * cfg.enemySpeed * (e.seen ? 1 : 0.4); vy += ey / el * cfg.enemySpeed * (e.seen ? 1 : 0.4); }
133
+ if (e.seen && d > cfg.sight * 1.6) e.seen = false;
134
+ if (d < R + 0.36 && e.cool <= 0) { hit(s, ctx, 'chaser'); e.cool = 0.8; }
135
+ } else if (sees && e.cool <= 0) {
136
+ const ex = s.x - e.x, ey = s.y - e.y, el = Math.hypot(ex, ey) || 1;
137
+ s.shots.push({ x: e.x, y: e.y, vx: ex / el * 5, vy: ey / el * 5, life: 3 });
138
+ e.cool = 1.6; ctx.emit({ type: 'throw', x: e.x, y: e.y });
139
+ }
140
+ const em = slide(e.x, e.y, vx * dt, vy * dt, 0.3, solid(s));
141
+ e.x = em.x; e.y = em.y; if (e.kind === 'chaser' && e.cool > 0.2) { e.vx = vx; e.vy = vy; } else { e.vx *= 0.9; e.vy *= 0.9; }
142
+ }
143
+ for (const sh of s.shots) {
144
+ sh.x += sh.vx * dt; sh.y += sh.vy * dt; sh.life -= dt;
145
+ if (wallAt(s, Math.floor(sh.x), Math.floor(sh.y))) sh.life = 0;
146
+ else if (dist(sh.x, sh.y, s.x, s.y) < R + 0.12) { sh.life = 0; hit(s, ctx, 'throw'); }
147
+ }
148
+ s.shots = s.shots.filter((sh) => sh.life > 0);
149
+ // the way out
150
+ if (s.gemsGot >= s.needGems && dist(s.x, s.y, s.exit.x, s.exit.y) < 0.6) { s.won = true; s.score += Math.max(0, 300 - Math.round(s.t * 2)) + s.hp * 20; ctx.emit({ type: 'won' }); }
151
+ if (s.time && s.t >= s.time && !s.won) { s.lost = true; ctx.emit({ type: 'lost', why: 'time' }); }
152
+ }
153
+
154
+ const ACTIONS = {
155
+ /** Hold a direction (dx, dy from −1 to 1) and the attack button. */
156
+ input(s, ctx, dx = 0, dy = 0, attack = false) { s.ix = clamp(Number(dx) || 0, -1, 1); s.iy = clamp(Number(dy) || 0, -1, 1); s.attackHeld = !!attack; },
157
+ /** Swing once, toward a direction (the way you face when none is given). */
158
+ attack(s, ctx, dx, dy) { return swing(s, ctx, dx ?? s.fx, dy ?? s.fy); },
159
+ stop(s) { s.ix = 0; s.iy = 0; s.attackHeld = false; },
160
+ };
161
+
162
+ /** The cell to go to next: a key while a locked door is between, gems still asked for, else the way out. */
163
+ function target(s) {
164
+ const open = (x, y) => wallAt(s, x, y) === 0;
165
+ const openKey = (x, y) => wallAt(s, x, y) === 0 || (s.carrying > 0 && wallAt(s, x, y) === 2);
166
+ const toExit = bfs(s.w, s.h, s.x, s.y, openKey, (x, y) => x === Math.floor(s.exit.x) && y === Math.floor(s.exit.y));
167
+ if (s.gemsGot < s.needGems) {
168
+ const g = bfs(s.w, s.h, s.x, s.y, openKey, (x, y) => s.gems.some((k) => !k.got && Math.floor(k.x) === x && Math.floor(k.y) === y));
169
+ if (g) return g;
170
+ }
171
+ if (toExit) return toExit;
172
+ const key = bfs(s.w, s.h, s.x, s.y, open, (x, y) => s.keys.some((k) => !k.got && Math.floor(k.x) === x && Math.floor(k.y) === y));
173
+ if (key) return key;
174
+ return bfs(s.w, s.h, s.x, s.y, (x, y) => wallAt(s, x, y) !== 1, (x, y) => wallAt(s, x, y) === 2);
175
+ }
176
+
177
+ function value(s) {
178
+ if (s.won) return 1e6 + s.hp * 1000 - s.t;
179
+ if (s.lost) return -1e6;
180
+ const way = target(s);
181
+ return -(way ? way.length : 50) * 10 + s.hp * 40 + s.carrying * 30 + s.gemsGot * 30 - s.enemies.filter((e) => e.alive).length * 3;
182
+ }
183
+
184
+ export const bots = {
185
+ random(sim, rng, memo) {
186
+ if (!memo.in || rng.chance(0.2)) memo.in = [rng.pick([-1, 0, 1]), rng.pick([-1, 0, 1]), rng.chance(0.3)];
187
+ return { act: 'input', args: memo.in, for: 0.1 };
188
+ },
189
+ greedy(sim) {
190
+ // straight for what it wants, swinging at what is close: no way round walls
191
+ const s = sim.state, goal = s.gemsGot < s.needGems ? s.gems.find((g) => !g.got) : s.keys.find((k) => !k.got) && s.walls.includes(2) && !s.carrying ? s.keys.find((k) => !k.got) : s.exit;
192
+ const near = s.enemies.find((e) => e.alive && dist(e.x, e.y, s.x, s.y) < s.cfg.reach + 0.2);
193
+ const dx = (goal?.x ?? s.x) - s.x, dy = (goal?.y ?? s.y) - s.y, l = Math.hypot(dx, dy) || 1;
194
+ return { act: 'input', args: [dx / l, dy / l, !!near], for: 0.1 };
195
+ },
196
+ planner(sim, rng, memo) {
197
+ const s = sim.state;
198
+ // a chaser close by: face it and swing; one at a distance that sees us: wait for it with the sword out
199
+ const foes = s.enemies.filter((e) => e.alive && dist(e.x, e.y, s.x, s.y) < 2.2 && clear(s, s.x, s.y, e.x, e.y)).sort((a, b) => dist(a.x, a.y, s.x, s.y) - dist(b.x, b.y, s.x, s.y));
200
+ if (foes.length) {
201
+ const e = foes[0], dx = e.x - s.x, dy = e.y - s.y, d = Math.hypot(dx, dy) || 1;
202
+ if (d < s.cfg.reach + 0.2 && s.cool <= 0) return { act: 'attack', args: [dx / d, dy / d], for: 0.05 };
203
+ // keep the distance of a swing: step back when hurt, else close in
204
+ const k = s.hurt > 0.5 ? -0.6 : d > s.cfg.reach ? 1 : 0;
205
+ return { act: 'input', args: [dx / d * k, dy / d * k, false], for: 0.05 };
206
+ }
207
+ // a sentry that sees us and is reachable: go and strike it; else the way
208
+ const way = target(s);
209
+ memo.seen ??= { x: s.x, y: s.y, t: s.t };
210
+ if (dist(s.x, s.y, memo.seen.x, memo.seen.y) > 1) memo.seen = { x: s.x, y: s.y, t: s.t };
211
+ if (!way || !way.length) return { act: 'input', args: [rng.range(-1, 1), rng.range(-1, 1), false], for: 0.2 };
212
+ const next = way[Math.min(1, way.length - 1)], tx = next.x + 0.5, ty = next.y + 0.5;
213
+ let dx = tx - s.x, dy = ty - s.y;
214
+ // dodge a throw coming at us
215
+ for (const sh of s.shots) {
216
+ const rx = s.x - sh.x, ry = s.y - sh.y, ahead = (rx * sh.vx + ry * sh.vy) / 25;
217
+ if (ahead > 0 && ahead < 0.6) { const px = -sh.vy, py = sh.vx; const side = Math.sign(rx * px + ry * py) || 1; dx += px * side * 0.4; dy += py * side * 0.4; }
218
+ }
219
+ const l = Math.hypot(dx, dy) || 1;
220
+ const stuck = s.t - memo.seen.t > 2;
221
+ return { act: 'input', args: stuck ? [rng.range(-1, 1), rng.range(-1, 1), false] : [dx / l, dy / l, false], for: stuck ? 0.3 : 0.1 };
222
+ },
223
+ };
224
+
225
+ export function create({ game, level, seed = 1, hooks = {} }) {
226
+ const cfg = settingsFor(kit.settings, game), h = hooked(hooks, ACTIONS);
227
+ const sim = createSim({
228
+ seed,
229
+ setup: (ctx) => { const s = setup(level, cfg, ctx.rng); hooks.setup?.(s, ctx, level); return s; },
230
+ step: (s, dt, ctx) => { step(s, dt, ctx); hooks.step?.(s, dt, ctx); h.end(s, ctx); },
231
+ actions: h.actions,
232
+ report: (s) => ({
233
+ won: s.won, lost: s.lost, x: round3(s.x), y: round3(s.y), hp: s.hp, keys: s.carrying, gems: s.gemsGot, needGems: s.needGems,
234
+ enemies: s.enemies.filter((e) => e.alive).length, exit: { x: s.exit.x, y: s.exit.y }, t: round3(s.t), w: s.w, h: s.h,
235
+ score: hooks.score ? hooks.score(s) : s.score, deaths: s.deaths.length,
236
+ }),
237
+ });
238
+ sim.kit = kit; sim.bots = bots;
239
+ sim.value = () => (hooks.value ? hooks.value(sim.state) : value(sim.state));
240
+ return sim;
241
+ }
242
+
243
+ // ─── levels ──────────────────────────────────────────────────────────────────
244
+
245
+ /**
246
+ * Rooms joined by corridors, walked from the start to the way out; a locked door on the way with its key in a
247
+ * room before it; chasers, sentries, gems and a heart in the rooms. → the map
248
+ */
249
+ export function topdownLevel(rng, { rooms = 4, chasers = 2, sentries = 0, gems = 3, locked = true, room = [7, 5] } = {}) {
250
+ const gw = Math.max(2, Math.ceil(Math.sqrt(rooms + 1))), gh = gw;
251
+ const [rw, rh] = room, cw = rw + 3, ch = rh + 3;
252
+ // a walk over a grid of rooms
253
+ const cells = [{ x: 0, y: rng.int(0, gh - 1) }], seen = new Set([`${cells[0].x},${cells[0].y}`]);
254
+ while (cells.length < rooms) {
255
+ const last = cells[cells.length - 1];
256
+ const next = rng.shuffle([[1, 0], [0, 1], [0, -1], [-1, 0], [1, 0]]).map(([dx, dy]) => ({ x: last.x + dx, y: last.y + dy })).find((c) => c.x >= 0 && c.y >= 0 && c.x < gw && c.y < gh && !seen.has(`${c.x},${c.y}`));
257
+ if (!next) break;
258
+ seen.add(`${next.x},${next.y}`); cells.push(next);
259
+ }
260
+ const W = gw * cw + 1, H = gh * ch + 1;
261
+ const g = Array.from({ length: H }, () => new Array(W).fill('#'));
262
+ const origin = (c) => ({ x: c.x * cw + 2, y: c.y * ch + 2 });
263
+ for (const c of cells) { const o = origin(c); for (let y = 0; y < rh; y++) for (let x = 0; x < rw; x++) g[o.y + y][o.x + x] = '.'; }
264
+ const doorAt = [];
265
+ for (let i = 1; i < cells.length; i++) {
266
+ const a = origin(cells[i - 1]), b = origin(cells[i]);
267
+ const ax = a.x + (rw >> 1), ay = a.y + (rh >> 1), bx = b.x + (rw >> 1), by = b.y + (rh >> 1);
268
+ let x = ax, y = ay;
269
+ const cells_ = [];
270
+ while (x !== bx) { x += Math.sign(bx - x); if (g[y][x] === '#') { g[y][x] = '.'; cells_.push({ x, y }); } }
271
+ while (y !== by) { y += Math.sign(by - y); if (g[y][x] === '#') { g[y][x] = '.'; cells_.push({ x, y }); } }
272
+ doorAt.push(cells_[Math.floor(cells_.length / 2)] ?? null);
273
+ }
274
+ const free = (c) => { const o = origin(c), out = []; for (let y = 0; y < rh; y++) for (let x = 0; x < rw; x++) if (g[o.y + y][o.x + x] === '.') out.push({ x: o.x + x, y: o.y + y }); return rng.shuffle(out); };
275
+ const put = (c, ch_) => { const f = free(c).find((p) => g[p.y][p.x] === '.'); if (f) g[f.y][f.x] = ch_; return f; };
276
+ const first = cells[0], last = cells[cells.length - 1];
277
+ const s0 = origin(first); g[s0.y + (rh >> 1)][s0.x + 1] = '@';
278
+ const e0 = origin(last); g[e0.y + (rh >> 1)][e0.x + rw - 2] = 'X';
279
+ // a locked door on the last corridor, its key in a room before it (not the first, when there are three or more)
280
+ if (locked && cells.length >= 2 && doorAt[doorAt.length - 1]) {
281
+ const d = doorAt[doorAt.length - 1]; g[d.y][d.x] = 'L';
282
+ const keyRoom = cells[cells.length >= 3 ? rng.int(1, cells.length - 2) : 0];
283
+ put(keyRoom, 'k');
284
+ }
285
+ const middle = cells.slice(1);
286
+ for (let i = 0; i < chasers; i++) put(middle.length ? middle[i % middle.length] : last, 'E');
287
+ for (let i = 0; i < sentries; i++) put(middle.length ? middle[(i + 1) % middle.length] : last, 'S');
288
+ for (let i = 0; i < gems; i++) put(cells[i % cells.length], 'o');
289
+ if (cells.length >= 3) put(cells[Math.floor(cells.length / 2)], 'h');
290
+ // trim the empty edge
291
+ const rows = g.map((r) => r.join(''));
292
+ const used = rows.map((r) => /[^#]/.test(r));
293
+ const top = Math.max(0, used.indexOf(true) - 1), bottom = Math.min(rows.length, used.lastIndexOf(true) + 2);
294
+ const sliced = rows.slice(top, bottom);
295
+ let left = Infinity, right = 0;
296
+ for (const r of sliced) { const m = /[^#]/.exec(r); if (m) { left = Math.min(left, m.index); right = Math.max(right, r.search(/[^#]#*$/) + 1); } }
297
+ return sliced.map((r) => r.slice(Math.max(0, left - 1), right + 1));
298
+ }
299
+
300
+ /** Easier versions of a level, the smallest change first (for play()'s fixes). */
301
+ export function easier(lv) {
302
+ const map = lv.map ?? [], out = [];
303
+ let once = false;
304
+ const fewer = map.map((r) => r.replace(/E/, (m) => (once ? m : ((once = true), '.'))));
305
+ if (once) out.push({ change: { map: fewer }, say: 'one chaser fewer' });
306
+ if (/[ES]/.test(map.join(''))) out.push({ change: { map: map.map((r) => r.replace(/[ES]/g, '.')) }, say: 'without its chasers and sentries' });
307
+ if (lv.time) out.push({ change: { time: Math.round(lv.time * 1.5) }, say: `time ${lv.time} → ${Math.round(lv.time * 1.5)} s` });
308
+ if (lv.gems) out.push({ change: { gems: Math.max(0, lv.gems - 1) }, say: `gems asked ${lv.gems} → ${lv.gems - 1}` });
309
+ return out;
310
+ }
311
+ export function harder(lv) {
312
+ const map = (lv.map ?? []).map(String), out = [];
313
+ const floor = []; map.forEach((r, y) => [...r].forEach((c, x) => { if (c === '.') floor.push({ x, y }); }));
314
+ const s = map.findIndex((r) => r.includes('@')), sx = s >= 0 ? map[s].indexOf('@') : 0;
315
+ const far = floor.filter((p) => Math.abs(p.x - sx) + Math.abs(p.y - s) > 6);
316
+ if (far.length) { const p = far[Math.floor(far.length / 2)]; const m = [...map]; m[p.y] = m[p.y].slice(0, p.x) + 'E' + m[p.y].slice(p.x + 1); out.push({ change: { map: m }, say: 'a chaser more' }); }
317
+ if (lv.time) out.push({ change: { time: Math.max(10, Math.round(lv.time * 0.8)) }, say: `time ${lv.time} → ${Math.max(10, Math.round(lv.time * 0.8))} s` });
318
+ return out;
319
+ }
@@ -0,0 +1,225 @@
1
+ // @clarity-js/engine — game.json checked against the schema, with the place of each mistake (its path and, when
2
+ // the text is given, its line) and what to write instead. No dependency: the rules are the schema's, by hand.
3
+
4
+ import { ART_ROLES, checkArt } from './art.js';
5
+
6
+ export const KITS = ['puzzle-grid', 'platformer', 'top-down', 'shmup', 'racing', 'card-board', 'explore-3d', 'physics-toy', 'blank'];
7
+ export const STYLES = ['paper-marbling', 'pixel', 'neon-night', 'ink-sketch', 'toy-plastic', 'pastel', 'flat', 'low-poly-diorama'];
8
+ const num = (v) => typeof v === 'number' && Number.isFinite(v);
9
+ const pair = (v) => Array.isArray(v) && v.length === 2 && v.every(num);
10
+ const GOALS = ['match', 'push', 'lights', 'slide'];
11
+ const HEX = /^#[0-9a-fA-F]{6}$/;
12
+
13
+ /** Where each value starts in the JSON text, by its path ('levels[0].moves'): for line numbers. */
14
+ export function jsonPlaces(text) {
15
+ const places = new Map();
16
+ let i = 0;
17
+ const ws = () => { while (i < text.length && /\s/.test(text[i])) i++; };
18
+ const str = () => { const s = i; i++; while (i < text.length && text[i] !== '"') { if (text[i] === '\\') i++; i++; } i++; return JSON.parse(text.slice(s, i)); };
19
+ const value = (path) => {
20
+ ws(); places.set(path, i);
21
+ const c = text[i];
22
+ if (c === '{') {
23
+ i++; ws();
24
+ if (text[i] === '}') { i++; return; }
25
+ for (;;) { ws(); const k = str(); ws(); i++; value(path ? `${path}.${k}` : k); ws(); if (text[i] === ',') { i++; continue; } i++; return; }
26
+ }
27
+ if (c === '[') {
28
+ i++; ws();
29
+ if (text[i] === ']') { i++; return; }
30
+ for (let n = 0; ; n++) { value(`${path}[${n}]`); ws(); if (text[i] === ',') { i++; continue; } i++; return; }
31
+ }
32
+ if (c === '"') { str(); return; }
33
+ while (i < text.length && !/[\s,\]}]/.test(text[i])) i++;
34
+ };
35
+ try { value(''); } catch { /* a broken text: JSON.parse has said where */ }
36
+ return places;
37
+ }
38
+
39
+ const lineOf = (text, at) => (at == null ? null : text.slice(0, at).split('\n').length);
40
+
41
+ /**
42
+ * @param {object|string} input the game (or its text: then mistakes have lines)
43
+ * @returns {{ ok: boolean, errors: Array<{ path: string, message: string, fix?: string, line?: number }>, warnings: Array<…>, game: object|null }}
44
+ */
45
+ export function validateGame(input) {
46
+ const errors = [], warnings = [];
47
+ let game = input, text = null;
48
+ if (typeof input === 'string') {
49
+ text = input;
50
+ try { game = JSON.parse(input); } catch (e) {
51
+ const m = /position (\d+)/.exec(e.message), l = /line (\d+)/.exec(e.message);
52
+ return { ok: false, errors: [{ path: '', message: 'game.json is not JSON: ' + e.message, line: l ? Number(l[1]) : m ? lineOf(text, Number(m[1])) : null, fix: 'a missing comma or quote, or a comma before } or ]' }], warnings, game: null };
53
+ }
54
+ }
55
+ const err = (path, message, fix) => errors.push({ path, message, ...(fix ? { fix } : {}) });
56
+ const warn = (path, message, fix) => warnings.push({ path, message, ...(fix ? { fix } : {}) });
57
+ if (!game || typeof game !== 'object' || Array.isArray(game)) err('', 'game.json holds one object', '{ "engine": 1, "title": "…", "kit": "puzzle-grid", "rules": "rules.js" }');
58
+ else {
59
+ if (game.engine !== 1) err('engine', `engine must be 1 (got ${JSON.stringify(game.engine)})`, '"engine": 1');
60
+ if (typeof game.title !== 'string' || !game.title.trim()) err('title', 'title is missing', '"title": "Ink Tide"');
61
+ else if (game.title.length > 60) err('title', `title is ${game.title.length} characters; at most 60`);
62
+ if (!KITS.includes(game.kit)) err('kit', `kit must be one of ${KITS.join(', ')} (got ${JSON.stringify(game.kit)})`, '"kit": "platformer"');
63
+ if (typeof game.rules !== 'string' || !/\.m?js$/.test(game.rules)) err('rules', 'rules names the rules file', '"rules": "rules.js"');
64
+ if (game.pitch != null && typeof game.pitch !== 'string') err('pitch', 'pitch is a sentence');
65
+ const look = game.look;
66
+ if (look != null) {
67
+ if (typeof look !== 'object') err('look', 'look is an object: { style, palette }');
68
+ else {
69
+ if (look.style != null && !STYLES.includes(look.style)) err('look.style', `no style "${look.style}"`, `one of ${STYLES.join(', ')}`);
70
+ for (const [k, hi] of [['radius', 0.5], ['glow', 1], ['gloss', 1], ['outline', 1], ['shade', 1]]) if (look[k] != null && !(num(look[k]) && look[k] >= 0 && look[k] <= hi)) err(`look.${k}`, `${k} is 0 to ${hi}`);
71
+ if (look.pattern != null && !['marble', 'hatch', 'bevel'].includes(look.pattern)) err('look.pattern', `no pattern "${look.pattern}"`, 'marble, hatch, bevel or null');
72
+ for (const k of ['background', 'ink']) if (look[k] != null && !HEX.test(look[k])) err(`look.${k}`, `"${look[k]}" is not a colour`, 'write it as #rrggbb');
73
+ if (look.palette != null) {
74
+ if (!Array.isArray(look.palette) || look.palette.length < 2 || look.palette.length > 8) err('look.palette', 'palette is 2 to 8 colours');
75
+ else look.palette.forEach((c, i) => { if (!HEX.test(c)) err(`look.palette[${i}]`, `"${c}" is not a colour`, 'write it as #rrggbb'); });
76
+ }
77
+ }
78
+ }
79
+ const feel = game.feel;
80
+ if (feel?.pace != null && !['calm', 'steady', 'fast'].includes(feel.pace)) err('feel.pace', `pace is calm, steady or fast (got "${feel.pace}")`);
81
+ if (game.settings != null && (typeof game.settings !== 'object' || Array.isArray(game.settings))) err('settings', 'settings is an object of numbers');
82
+ else for (const [k, v] of Object.entries(game.settings ?? {})) if (typeof v !== 'number' || !Number.isFinite(v)) err(`settings.${k}`, `${k} must be a number`);
83
+ if (game.kit !== 'blank') {
84
+ if (!Array.isArray(game.levels) || !game.levels.length) err('levels', 'levels is a list with at least one level', LEVEL_EXAMPLE[game.kit] ?? LEVEL_EXAMPLE['puzzle-grid']);
85
+ else {
86
+ const ids = new Set();
87
+ game.levels.forEach((lv, n) => {
88
+ const p = `levels[${n}]`;
89
+ if (!lv || typeof lv !== 'object') { err(p, 'a level is an object'); return; }
90
+ if (lv.id != null) { if (ids.has(lv.id)) err(`${p}.id`, `two levels are called "${lv.id}"`); ids.add(lv.id); }
91
+ if (lv.moves != null && (!Number.isInteger(lv.moves) || lv.moves < 1)) err(`${p}.moves`, `moves cannot be ${JSON.stringify(lv.moves)}; at least 1`, '"moves": 12');
92
+ if (game.kit === 'puzzle-grid') {
93
+ const goal = lv.goal ?? 'match';
94
+ if (!GOALS.includes(goal)) err(`${p}.goal`, `goal is one of ${GOALS.join(', ')} (got "${goal}")`);
95
+ if (goal === 'push') { if (lv.map != null) mapCheck(lv.map, `${p}.map`, { need: { '@': 1 }, chars: '#.$*@+ ', err, kind: 'push' }); }
96
+ else if (lv.size != null) {
97
+ const ok = Array.isArray(lv.size) && lv.size.length === 2 && lv.size.every((v) => Number.isInteger(v) && v >= 2 && v <= 12);
98
+ if (!ok) err(`${p}.size`, 'size is [columns, rows], each 2 to 12', '"size": [6, 6]');
99
+ if (ok && goal === 'match' && (lv.size[0] < 4 || lv.size[1] < 4)) err(`${p}.size`, 'a match board is at least 4 × 4');
100
+ }
101
+ if (goal === 'match' && lv.target != null && (!(lv.target > 0))) err(`${p}.target`, 'target is the points to reach, more than 0');
102
+ if (goal === 'match' && lv.colors != null && !(Number.isInteger(lv.colors) && lv.colors >= 3 && lv.colors <= 8)) err(`${p}.colors`, 'colors is 3 to 8');
103
+ }
104
+ if (game.kit === 'top-down') {
105
+ mapCheck(lv.map, `${p}.map`, { need: { '@': 1, X: 1 }, chars: '#.@XESkLho ', err, kind: 'top-down' });
106
+ const all = (lv.map ?? []).join(''), keys = all.split('k').length - 1, doors = all.split('L').length - 1;
107
+ if (doors > keys) err(`${p}.map`, `${doors} locked doors and ${keys} keys: a key for every door`);
108
+ if (lv.gems != null && lv.gems > all.split('o').length - 1) err(`${p}.gems`, `the way out wants ${lv.gems} gems and the map has ${all.split('o').length - 1}`);
109
+ }
110
+ if (game.kit === 'shmup') {
111
+ if (lv.length != null && !(num(lv.length) && lv.length >= 5)) err(`${p}.length`, 'length is seconds, at least 5', '"length": 30');
112
+ if (lv.waves != null) {
113
+ if (!Array.isArray(lv.waves)) err(`${p}.waves`, 'waves is a list', '"waves": [{ "t": 2, "kind": "line", "n": 5 }]');
114
+ else lv.waves.forEach((w, k) => {
115
+ if (!w || !num(w.t)) err(`${p}.waves[${k}]`, 'a wave has t: when it comes, in seconds', '{ "t": 2, "kind": "line", "n": 5 }');
116
+ else if (w.kind != null && !['line', 'vee', 'sine', 'dive', 'column'].includes(w.kind)) err(`${p}.waves[${k}].kind`, `no wave "${w.kind}"`, 'line, vee, sine, dive or column');
117
+ });
118
+ }
119
+ if (lv.boss != null && !(lv.boss && num(lv.boss.hp) && lv.boss.hp > 0)) err(`${p}.boss`, 'a boss has hp, more than 0', '"boss": { "hp": 60, "pattern": "ring" }');
120
+ if (lv.boss?.pattern != null && !['ring', 'spiral', 'fan'].includes(lv.boss.pattern)) err(`${p}.boss.pattern`, `no pattern "${lv.boss.pattern}"`, 'ring, spiral or fan');
121
+ }
122
+ if (game.kit === 'racing') {
123
+ if (lv.track != null && !(Array.isArray(lv.track) && lv.track.length >= 4 && lv.track.every(pair))) err(`${p}.track`, 'the track is four or more points [x, y]', '"track": [[0, -40], [38, -12], [24, 34], [-26, 30]]');
124
+ if (lv.width != null && !(num(lv.width) && lv.width >= 3 && lv.width <= 30)) err(`${p}.width`, 'width is 3 to 30');
125
+ if (lv.laps != null && !(Number.isInteger(lv.laps) && lv.laps >= 1 && lv.laps <= 9)) err(`${p}.laps`, 'laps is 1 to 9');
126
+ if (lv.rivals != null && !(Number.isInteger(lv.rivals) && lv.rivals >= 0 && lv.rivals <= 7)) err(`${p}.rivals`, 'rivals is 0 to 7');
127
+ if (lv.rivalPace != null && !(num(lv.rivalPace) && lv.rivalPace >= 0.3 && lv.rivalPace <= 1.1)) err(`${p}.rivalPace`, 'rivalPace is 0.3 to 1.1: a share of the fastest the bends allow');
128
+ if (lv.place != null && !(Number.isInteger(lv.place) && lv.place >= 1 && lv.place <= (lv.rivals ?? 3) + 1)) err(`${p}.place`, `place is 1 to ${(lv.rivals ?? 3) + 1}: where to finish (or better)`);
129
+ }
130
+ if (game.kit === 'card-board') {
131
+ const goal = lv.goal ?? 'shed';
132
+ if (!['shed', 'line'].includes(goal)) err(`${p}.goal`, `goal is shed or line (got "${goal}")`);
133
+ if (goal === 'line') {
134
+ const ok = lv.size == null || (Array.isArray(lv.size) && lv.size.length === 2 && lv.size.every((v) => Number.isInteger(v) && v >= 4 && v <= 10));
135
+ if (!ok) err(`${p}.size`, 'size is [columns, rows], each 4 to 10', '"size": [7, 6]');
136
+ if (lv.inRow != null && !(Number.isInteger(lv.inRow) && lv.inRow >= 3 && lv.inRow <= 6)) err(`${p}.inRow`, 'inRow is 3 to 6');
137
+ if (lv.rival != null && !(Number.isInteger(lv.rival) && lv.rival >= 0 && lv.rival <= 5)) err(`${p}.rival`, 'rival is how many moves it looks ahead: 0 to 5');
138
+ } else {
139
+ for (const [k, lo, hi] of [['colors', 2, 6], ['ranks', 3, 12], ['hand', 2, 12], ['rivals', 1, 3], ['rival', 0, 2], ['wilds', 0, 8], ['extra', -3, 4]]) if (lv[k] != null && !(Number.isInteger(lv[k]) && lv[k] >= lo && lv[k] <= hi)) err(`${p}.${k}`, `${k} is ${lo} to ${hi}`);
140
+ }
141
+ }
142
+ if (game.kit === 'explore-3d') {
143
+ const size = lv.size ?? [20, 20];
144
+ if (!(Array.isArray(size) && size.length === 2 && size.every((v) => Number.isInteger(v) && v >= 8 && v <= 96))) err(`${p}.size`, 'size is [columns, rows], each 8 to 96', '"size": [32, 32]');
145
+ else {
146
+ if (lv.heights != null && (typeof lv.heights !== 'string' || lv.heights.length !== size[0] * size[1] || /[^a-z~]/.test(lv.heights))) err(`${p}.heights`, `heights is one character a cell (${size[0] * size[1]} of them), a to z or ~ for water`);
147
+ const inside = (o) => o && num(o.x) && num(o.y) && o.x >= 0 && o.y >= 0 && o.x < size[0] && o.y < size[1];
148
+ if (!Array.isArray(lv.things) || !lv.things.some((t) => t?.kind === 'item')) err(`${p}.things`, 'the world needs at least one thing to find', '"things": [{ "kind": "item", "x": 12, "y": 9 }]');
149
+ else lv.things.forEach((t, k) => { if (!['item', 'npc', 'tree', 'rock'].includes(t?.kind)) err(`${p}.things[${k}].kind`, `no kind "${t?.kind}"`, 'item, npc, tree or rock'); else if (!inside(t)) err(`${p}.things[${k}]`, 'x and y inside the world'); });
150
+ for (const k of ['goal', 'start']) if (lv[k] != null && !inside(lv[k])) err(`${p}.${k}`, `${k} is { x, y } inside the world`);
151
+ }
152
+ }
153
+ if (game.kit === 'physics-toy') {
154
+ const goal = lv.goal ?? 'topple';
155
+ if (!['topple', 'stack'].includes(goal)) err(`${p}.goal`, `goal is topple or stack (got "${goal}")`);
156
+ const quad = (v, n) => Array.isArray(v) && v.length === n && v.every(num);
157
+ if (goal === 'topple') {
158
+ if (lv.blocks != null && !(Array.isArray(lv.blocks) && lv.blocks.every((b) => quad(b, 4)))) err(`${p}.blocks`, 'blocks are [x, y, width, height], each', '"blocks": [[10, 0.5, 0.4, 1]]');
159
+ if (lv.targets != null && !(Array.isArray(lv.targets) && lv.targets.length && lv.targets.every((b) => quad(b, 3)))) err(`${p}.targets`, 'targets are [x, y, size], at least one', '"targets": [[10, 1.6, 0.5]]');
160
+ if (lv.shots != null && !(Number.isInteger(lv.shots) && lv.shots >= 1 && lv.shots <= 12)) err(`${p}.shots`, 'shots is 1 to 12');
161
+ } else {
162
+ if (lv.pieces != null && !(Array.isArray(lv.pieces) && lv.pieces.length && lv.pieces.every((b) => quad(b, 2)))) err(`${p}.pieces`, 'pieces are [width, height], at least one', '"pieces": [[2, 0.5], [1.5, 0.5]]');
163
+ if (lv.height != null && !(num(lv.height) && lv.height > 0)) err(`${p}.height`, 'height is how high the stack must stand, more than 0');
164
+ }
165
+ }
166
+ if (game.kit === 'platformer') {
167
+ mapCheck(lv.map, `${p}.map`, { need: { '@': 1, D: 1 }, chars: '#-@oE^DC .', err, kind: 'platformer' });
168
+ if (lv.coins != null) { const total = (lv.map ?? []).join('').split('o').length - 1; if (lv.coins > total) err(`${p}.coins`, `the door wants ${lv.coins} coins and the map has ${total}`); }
169
+ if (lv.time != null && !(lv.time > 0)) err(`${p}.time`, 'time is seconds, more than 0');
170
+ }
171
+ });
172
+ }
173
+ }
174
+ const sound = game.sound;
175
+ if (sound != null) {
176
+ if (typeof sound !== 'object' || Array.isArray(sound)) err('sound', 'sound is an object: { music, sfx, volume }', '"sound": { "music": "calm", "sfx": true }');
177
+ else {
178
+ if (sound.music != null && !['calm', 'tense', 'playful', 'none'].includes(sound.music)) err('sound.music', `no music "${sound.music}"`, 'calm, tense, playful or none');
179
+ if (sound.sfx != null && typeof sound.sfx !== 'boolean') err('sound.sfx', 'sfx is true or false');
180
+ if (sound.volume != null && !(num(sound.volume) && sound.volume >= 0 && sound.volume <= 1)) err('sound.volume', 'volume is 0 to 1');
181
+ }
182
+ }
183
+ const checks = game.checks;
184
+ if (checks != null) {
185
+ if (checks.bots != null && (!Array.isArray(checks.bots) || checks.bots.some((b) => !['random', 'greedy', 'planner'].includes(b)))) err('checks.bots', 'bots are random, greedy and planner');
186
+ if (checks.finish != null && parseFinish(checks.finish) == null) err('checks.finish', `finish is a share the planner must finish, as ">= 0.7" (got ${JSON.stringify(checks.finish)})`);
187
+ }
188
+ // art: pictures in place of the kit's shapes (art.js)
189
+ if (game.art != null) {
190
+ if (!ART_ROLES[game.kit] && KITS.includes(game.kit)) warn('art', `the ${game.kit} kit draws its own shapes: art is read by ${Object.keys(ART_ROLES).join(', ')}`);
191
+ else for (const [path, message, fix] of checkArt(game.art, game.kit)) err(path, message, fix);
192
+ }
193
+ for (const k of Object.keys(game)) if (!['engine', 'title', 'pitch', 'kit', 'look', 'feel', 'rules', 'settings', 'levels', 'sound', 'text', 'checks', 'splash', 'credits', 'art'].includes(k)) warn(k, `"${k}" is not a field of game.json; it is kept and not read`);
194
+ const words = `${game.title ?? ''} ${game.pitch ?? ''}`.toLowerCase();
195
+ if (/\b(mario|zelda|pok[eé]mon|pikachu|sonic|tetris|pac-?man|minecraft|fortnite|angry birds|candy crush)\b/.test(words)) warn('pitch', 'it names a game or a character of someone else: make your own (its style can inspire, its characters, names and art cannot be used)');
196
+ }
197
+ if (text) { const places = jsonPlaces(text); for (const e of [...errors, ...warnings]) { const at = places.get(e.path) ?? places.get(e.path.replace(/\.[^.[]+$|\[\d+\]$/, '')); if (at != null) e.line = lineOf(text, at); } }
198
+ return { ok: errors.length === 0, errors, warnings, game: errors.length ? null : game };
199
+ }
200
+
201
+ const LEVEL_EXAMPLE = {
202
+ 'puzzle-grid': '"levels": [{ "id": "l1", "goal": "match", "size": [7, 7], "moves": 20, "target": 600 }]',
203
+ platformer: '"levels": [{ "id": "l1", "map": ["@ D", "#######"] }]',
204
+ 'top-down': '"levels": [{ "id": "l1", "map": ["#######", "#@...X#", "#######"] }]',
205
+ shmup: '"levels": [{ "id": "l1", "length": 30, "waves": [{ "t": 2, "kind": "line", "n": 5 }], "boss": { "hp": 40 } }]',
206
+ racing: '"levels": [{ "id": "l1", "track": [[0, -40], [38, -12], [24, 34], [-26, 30]], "laps": 2 }]',
207
+ 'card-board': '"levels": [{ "id": "l1", "goal": "shed", "hand": 6, "rival": 1 }]',
208
+ 'explore-3d': '"levels": [{ "id": "l1", "size": [20, 20], "things": [{ "kind": "item", "x": 15, "y": 15 }] }]',
209
+ 'physics-toy': '"levels": [{ "id": "l1", "goal": "topple", "targets": [[10, 1.6, 0.5]], "shots": 3 }]',
210
+ };
211
+
212
+ function mapCheck(map, path, { need, chars, err, kind }) {
213
+ if (!Array.isArray(map) || !map.length || map.some((r) => typeof r !== 'string')) { err(path, `a ${kind} level has a map: one string a row`); return; }
214
+ const all = map.join('');
215
+ for (const [c, n] of Object.entries(need)) { const k = all.split(c).length - 1 + (c === '@' ? all.split('+').length - 1 : 0); if (k !== n) err(path, `the map has ${k} "${c}"; it needs ${n}`); }
216
+ map.forEach((row, y) => { for (const c of row) if (!chars.includes(c)) { err(`${path}[${y}]`, `"${c}" means nothing in a ${kind} map`, `use ${[...chars].filter((x) => x !== ' ').join(' ')} and spaces`); break; } });
217
+ if (kind === 'push') { const boxes = (all.match(/[$*]/g) ?? []).length, marks = (all.match(/[.*+]/g) ?? []).length; if (!boxes) err(path, 'the map has no crate ($)'); if (marks < boxes) err(path, `${boxes} crates and ${marks} marks: a mark for every crate`); }
218
+ }
219
+
220
+ /** ">= 0.7" | 0.7 → 0.7 */
221
+ export function parseFinish(v) {
222
+ if (typeof v === 'number') return v >= 0 && v <= 1 ? v : null;
223
+ const m = /^\s*>=?\s*(0(?:\.\d+)?|1(?:\.0+)?)\s*$/.exec(String(v));
224
+ return m ? Number(m[1]) : null;
225
+ }