@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/README.md +212 -2
- package/index.d.ts +206 -0
- package/package.json +24 -4
- package/schema.json +628 -0
- package/src/art.js +115 -0
- package/src/bots.js +154 -0
- package/src/cardboard.js +304 -0
- package/src/common.js +100 -0
- package/src/editor.js +285 -0
- package/src/explore.js +258 -0
- package/src/grid.js +375 -0
- package/src/index.js +176 -0
- package/src/make.js +273 -0
- package/src/node.js +61 -0
- package/src/physicstoy.js +268 -0
- package/src/platformer.js +253 -0
- package/src/racing.js +228 -0
- package/src/shmup.js +239 -0
- package/src/skins.js +433 -0
- package/src/sound.js +179 -0
- package/src/topdown.js +319 -0
- package/src/validate.js +225 -0
- package/src/view.js +340 -0
package/src/explore.js
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
1
|
+
// @clarity-js/engine — the explore kit: walk a small world in 3D, find what was lost, ask the one who knows,
|
|
2
|
+
// bring it all back.
|
|
3
|
+
//
|
|
4
|
+
// A level is a height map and what is on it, plain data:
|
|
5
|
+
// { "id": "l1", "size": [36, 36], "heights": "…" (one character a cell, a–z low to high; ~ water),
|
|
6
|
+
// "things": [{ "kind": "item", "x": 12, "y": 30 }, { "kind": "npc", "x": 5, "y": 6, "says": "…" }],
|
|
7
|
+
// "goal": { "x": 4, "y": 4 }, "start": { "x": 5, "y": 5 }, "fog": 7 }
|
|
8
|
+
//
|
|
9
|
+
// Water and slopes too steep to climb stop you; trees (kind "tree") and rocks ("rock") are in the way. You see
|
|
10
|
+
// what is within `fog` cells. An npc, talked to (talk), tells where the nearest item still lost is. Bring every
|
|
11
|
+
// item to the goal. Input is held: input(dx, dy, talk), world directions (dy −1 is north).
|
|
12
|
+
|
|
13
|
+
import { createSim } from '@ozsarman/clarityjs/sim';
|
|
14
|
+
import { clamp, round3, dist, settingsFor, bfs, slide, hooked } from './common.js';
|
|
15
|
+
|
|
16
|
+
export const kit = {
|
|
17
|
+
name: 'explore-3d',
|
|
18
|
+
title: 'Explore in 3D',
|
|
19
|
+
describe: 'Walk a small world drawn in 3D, find what was lost, ask the one who knows, and bring it all back.',
|
|
20
|
+
settings: {
|
|
21
|
+
speed: { value: 3.6, min: 1, max: 10, unit: 'cells/s' },
|
|
22
|
+
climb: { value: 1.6, min: 0.5, max: 6, unit: 'height a cell' },
|
|
23
|
+
fog: { value: 7, min: 2, max: 30, unit: 'cells' },
|
|
24
|
+
},
|
|
25
|
+
level: { size: [20, 20], things: [{ kind: 'item', x: 15, y: 15 }], goal: { x: 3, y: 3 }, start: { x: 4, y: 4 } },
|
|
26
|
+
examples: ['Find the lost lighthouse lamp on a foggy island', 'Gather the scattered pages in a quiet forest', 'Bring the stray lanterns back to the harbour'],
|
|
27
|
+
input: ['keys', 'touch', 'pad'],
|
|
28
|
+
continuous: true,
|
|
29
|
+
controls: 'axes',
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
const R = 0.3;
|
|
33
|
+
|
|
34
|
+
function parse(level, cfg) {
|
|
35
|
+
const [w, h] = level.size ?? kit.level.size;
|
|
36
|
+
const hs = String(level.heights ?? '');
|
|
37
|
+
const height = new Array(w * h).fill(4), water = new Array(w * h).fill(0), block = new Array(w * h).fill(0);
|
|
38
|
+
for (let i = 0; i < w * h; i++) { const c = hs[i]; if (c === '~') { water[i] = 1; height[i] = 0; } else if (c) height[i] = (c.charCodeAt(0) - 97) * 0.5; }
|
|
39
|
+
const items = [], npcs = [], props = [];
|
|
40
|
+
for (const t of level.things ?? []) {
|
|
41
|
+
const x = clamp(Math.floor(t.x), 0, w - 1), y = clamp(Math.floor(t.y), 0, h - 1);
|
|
42
|
+
if (t.kind === 'item') items.push({ x: x + 0.5, y: y + 0.5, got: false, seen: false, name: t.name ?? 'item' });
|
|
43
|
+
else if (t.kind === 'npc') { npcs.push({ x: x + 0.5, y: y + 0.5, says: t.says ?? 'Something glints to the {dir}.', told: false, seen: false }); block[y * w + x] = 1; }
|
|
44
|
+
else { props.push({ kind: t.kind ?? 'tree', x: x + 0.5, y: y + 0.5, s: t.s ?? 1 }); block[y * w + x] = 1; }
|
|
45
|
+
}
|
|
46
|
+
const goal = level.goal ?? kit.level.goal, start = level.start ?? kit.level.start;
|
|
47
|
+
return { w, h, height, water, block, items, npcs, props, goal: { x: Math.floor(goal.x) + 0.5, y: Math.floor(goal.y) + 0.5 }, start: { x: Math.floor(start.x) + 0.5, y: Math.floor(start.y) + 0.5 }, fog: clamp(level.fog ?? cfg.fog, 2, 30) };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const idx = (s, x, y) => y * s.w + x;
|
|
51
|
+
const inside = (s, x, y) => x >= 0 && y >= 0 && x < s.w && y < s.h;
|
|
52
|
+
/** Can one walk from cell a into cell b? (no water, no block, a slope the walker climbs) */
|
|
53
|
+
function passable(s, ax, ay, bx, by) {
|
|
54
|
+
if (!inside(s, bx, by)) return false;
|
|
55
|
+
const j = idx(s, bx, by);
|
|
56
|
+
if (s.water[j] || s.block[j]) return false;
|
|
57
|
+
return !inside(s, ax, ay) || Math.abs(s.height[j] - s.height[idx(s, ax, ay)]) <= s.cfg.climb;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function setup(level, cfg) {
|
|
61
|
+
const m = parse(level, cfg);
|
|
62
|
+
const s = { ...m, cfg, x: m.start.x, y: m.start.y, fx: 0, fy: 1, ix: 0, iy: 0, talkHeld: false, carrying: 0, delivered: 0, hint: null, said: null, seen: new Array(m.w * m.h).fill(0), t: 0, time: Number(level.time ?? 0) || 0, deaths: [], score: 0, won: false, lost: false, steps: 0 };
|
|
63
|
+
look(s);
|
|
64
|
+
return s;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** What the walker sees from where it stands: every cell (and what is on it) within the fog. */
|
|
68
|
+
function look(s) {
|
|
69
|
+
const r = s.fog, cx = Math.floor(s.x), cy = Math.floor(s.y);
|
|
70
|
+
for (let y = Math.max(0, cy - r); y <= Math.min(s.h - 1, cy + r); y++) for (let x = Math.max(0, cx - r); x <= Math.min(s.w - 1, cx + r); x++) if ((x - cx) ** 2 + (y - cy) ** 2 <= r * r) s.seen[idx(s, x, y)] = 1;
|
|
71
|
+
for (const it of s.items) if (!it.seen && dist(it.x, it.y, s.x, s.y) <= r) it.seen = true;
|
|
72
|
+
for (const n of s.npcs) if (!n.seen && dist(n.x, n.y, s.x, s.y) <= r) n.seen = true;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const DIRS = ['east', 'south-east', 'south', 'south-west', 'west', 'north-west', 'north', 'north-east'];
|
|
76
|
+
|
|
77
|
+
function talk(s, ctx) {
|
|
78
|
+
const n = s.npcs.find((k) => dist(k.x, k.y, s.x, s.y) < 1.6);
|
|
79
|
+
if (!n) return false;
|
|
80
|
+
const lost = s.items.filter((it) => !it.got).sort((a, b) => dist(a.x, a.y, n.x, n.y) - dist(b.x, b.y, n.x, n.y))[0];
|
|
81
|
+
if (lost) { lost.seen = true; s.hint = { x: lost.x, y: lost.y }; }
|
|
82
|
+
const a = lost ? Math.atan2(lost.y - n.y, lost.x - n.x) : 0, dir = DIRS[((Math.round(a / (Math.PI / 4)) % 8) + 8) % 8];
|
|
83
|
+
s.said = lost ? n.says.replace('{dir}', dir) : 'You have found everything. Take it home.';
|
|
84
|
+
n.told = true;
|
|
85
|
+
ctx.emit({ type: 'talk', says: s.said });
|
|
86
|
+
return true;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function step(s, dt, ctx) {
|
|
90
|
+
if (s.won || s.lost) return;
|
|
91
|
+
s.t += dt;
|
|
92
|
+
let ix = s.ix, iy = s.iy; const l = Math.hypot(ix, iy); if (l > 1) { ix /= l; iy /= l; }
|
|
93
|
+
if (l > 0.1) { const fl = Math.hypot(ix, iy); s.fx = ix / fl; s.fy = iy / fl; }
|
|
94
|
+
const cx = Math.floor(s.x), cy = Math.floor(s.y);
|
|
95
|
+
const moved = slide(s.x, s.y, ix * s.cfg.speed * dt, iy * s.cfg.speed * dt, R, (x, y) => !(x === cx && y === cy) && !passable(s, cx, cy, x, y));
|
|
96
|
+
if (Math.floor(moved.x) !== cx || Math.floor(moved.y) !== cy) { s.steps++; look(s); }
|
|
97
|
+
s.x = moved.x; s.y = moved.y;
|
|
98
|
+
if (s.talkHeld) { talk(s, ctx); s.talkHeld = false; }
|
|
99
|
+
for (const it of s.items) if (!it.got && dist(it.x, it.y, s.x, s.y) < 0.7) { it.got = true; s.carrying++; s.score += 50; ctx.emit({ type: 'found', name: it.name }); if (s.hint && s.hint.x === it.x && s.hint.y === it.y) s.hint = null; }
|
|
100
|
+
if (s.carrying && dist(s.goal.x, s.goal.y, s.x, s.y) < 1) { s.delivered += s.carrying; s.carrying = 0; ctx.emit({ type: 'delivered', count: s.delivered }); }
|
|
101
|
+
if (s.delivered >= s.items.length) { s.won = true; s.score += Math.max(0, 500 - Math.round(s.t)); ctx.emit({ type: 'won' }); }
|
|
102
|
+
if (s.time && s.t >= s.time && !s.won) { s.lost = true; ctx.emit({ type: 'lost', why: 'time' }); }
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const ACTIONS = {
|
|
106
|
+
/** Hold a direction (dx east, dy south, each −1 … 1) and talk (to whoever is next to you). */
|
|
107
|
+
input(s, ctx, dx = 0, dy = 0, talking = false) { s.ix = clamp(Number(dx) || 0, -1, 1); s.iy = clamp(Number(dy) || 0, -1, 1); if (talking) s.talkHeld = true; },
|
|
108
|
+
talk(s, ctx) { return talk(s, ctx); },
|
|
109
|
+
stop(s) { s.ix = 0; s.iy = 0; },
|
|
110
|
+
};
|
|
111
|
+
|
|
112
|
+
/** The way to the cell that matters now: an item seen, the goal with what is carried, someone to ask, the unknown. */
|
|
113
|
+
function plan(s, { ask = true } = {}) {
|
|
114
|
+
const open = (x, y) => !s.water[idx(s, x, y)] && !s.block[idx(s, x, y)];
|
|
115
|
+
const at = (list) => (x, y) => list.some((o) => Math.floor(o.x) === x && Math.floor(o.y) === y);
|
|
116
|
+
const known = s.items.filter((it) => !it.got && it.seen);
|
|
117
|
+
const climbOpen = (fromOpen) => fromOpen;
|
|
118
|
+
void climbOpen;
|
|
119
|
+
const walk = (goal) => bfsClimb(s, goal);
|
|
120
|
+
if (known.length) { const p = walk(at(known)); if (p) return p; }
|
|
121
|
+
if (s.carrying && (s.carrying + s.delivered >= s.items.length || !known.length)) { const p = walk((x, y) => x === Math.floor(s.goal.x) && y === Math.floor(s.goal.y)); if (p) return p; }
|
|
122
|
+
if (ask) { const n = s.npcs.filter((k) => k.seen && !k.told); if (n.length) { const p = walk((x, y) => n.some((k) => dist(k.x, k.y, x + 0.5, y + 0.5) < 1.5)); if (p) return p; } }
|
|
123
|
+
// the nearest cell not yet seen that can be walked to
|
|
124
|
+
return walk((x, y) => open(x, y) && !s.seen[idx(s, x, y)]) ?? walk((x, y) => open(x, y) && [[1, 0], [-1, 0], [0, 1], [0, -1]].some(([dx, dy]) => inside(s, x + dx, y + dy) && !s.seen[idx(s, x + dx, y + dy)]));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** A breadth-first way that respects slopes. */
|
|
128
|
+
function bfsClimb(s, goal) {
|
|
129
|
+
const w = s.w, h = s.h, sx = Math.floor(s.x), sy = Math.floor(s.y);
|
|
130
|
+
const from = new Int32Array(w * h).fill(-1), start = sy * w + sx; from[start] = start;
|
|
131
|
+
const q = [start];
|
|
132
|
+
for (let qi = 0; qi < q.length; qi++) {
|
|
133
|
+
const i = q[qi], x = i % w, y = (i / w) | 0;
|
|
134
|
+
if (i !== start && goal(x, y)) { const path = []; for (let k = i; k !== start; k = from[k]) path.push({ x: k % w, y: (k / w) | 0 }); return path.reverse(); }
|
|
135
|
+
for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) {
|
|
136
|
+
const nx = x + dx, ny = y + dy, n = ny * w + nx;
|
|
137
|
+
if (!inside(s, nx, ny) || from[n] >= 0) continue;
|
|
138
|
+
if (!passable(s, x, y, nx, ny)) { if (goal(nx, ny) && s.block[n]) { from[n] = i; q.push(n); } continue; }
|
|
139
|
+
from[n] = i; q.push(n);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
return null;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function value(s) {
|
|
146
|
+
if (s.won) return 1e6 - s.t;
|
|
147
|
+
if (s.lost) return -1e6;
|
|
148
|
+
return s.delivered * 300 + s.carrying * 200 + s.seen.reduce((a, b) => a + b, 0) * 0.5;
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export const bots = {
|
|
152
|
+
random(sim, rng, memo) {
|
|
153
|
+
if (!memo.in || rng.chance(0.15)) memo.in = [rng.pick([-1, 0, 1]), rng.pick([-1, 0, 1]), rng.chance(0.1)];
|
|
154
|
+
return { act: 'input', args: memo.in, for: 0.1 };
|
|
155
|
+
},
|
|
156
|
+
greedy(sim, rng, memo) {
|
|
157
|
+
// straight for an item it sees, or home with what it carries; else wander
|
|
158
|
+
const s = sim.state;
|
|
159
|
+
const t = s.items.filter((it) => !it.got && it.seen).sort((a, b) => dist(a.x, a.y, s.x, s.y) - dist(b.x, b.y, s.x, s.y))[0] ?? (s.carrying ? s.goal : null);
|
|
160
|
+
if (!t) { if (!memo.in || rng.chance(0.08)) memo.in = [rng.range(-1, 1), rng.range(-1, 1), true]; return { act: 'input', args: memo.in, for: 0.1 }; }
|
|
161
|
+
const dx = t.x - s.x, dy = t.y - s.y, l = Math.hypot(dx, dy) || 1;
|
|
162
|
+
return { act: 'input', args: [dx / l, dy / l, true], for: 0.1 };
|
|
163
|
+
},
|
|
164
|
+
planner(sim, rng, memo) {
|
|
165
|
+
const s = sim.state;
|
|
166
|
+
if (s.npcs.some((n) => !n.told && dist(n.x, n.y, s.x, s.y) < 1.6) && s.items.some((it) => !it.got && !it.seen)) return { act: 'talk', args: [], for: 0.05 };
|
|
167
|
+
const way = plan(s);
|
|
168
|
+
if (!way || !way.length) return { act: 'input', args: [rng.range(-1, 1), rng.range(-1, 1), false], for: 0.3 };
|
|
169
|
+
const next = way[0], dx = next.x + 0.5 - s.x, dy = next.y + 0.5 - s.y, l = Math.hypot(dx, dy) || 1;
|
|
170
|
+
memo.seen ??= { x: s.x, y: s.y, t: s.t };
|
|
171
|
+
if (dist(s.x, s.y, memo.seen.x, memo.seen.y) > 0.8) memo.seen = { x: s.x, y: s.y, t: s.t };
|
|
172
|
+
if (s.t - memo.seen.t > 1.5) { memo.seen.t = s.t; return { act: 'input', args: [rng.range(-1, 1), rng.range(-1, 1), false], for: 0.25 }; }
|
|
173
|
+
return { act: 'input', args: [dx / l, dy / l, false], for: 0.1 };
|
|
174
|
+
},
|
|
175
|
+
};
|
|
176
|
+
|
|
177
|
+
export function create({ game, level, seed = 1, hooks = {} }) {
|
|
178
|
+
const cfg = settingsFor(kit.settings, game), h = hooked(hooks, ACTIONS);
|
|
179
|
+
const sim = createSim({
|
|
180
|
+
seed,
|
|
181
|
+
setup: (ctx) => { const s = setup(level, cfg); hooks.setup?.(s, ctx, level); return s; },
|
|
182
|
+
step: (s, dt, ctx) => { step(s, dt, ctx); hooks.step?.(s, dt, ctx); h.end(s, ctx); },
|
|
183
|
+
actions: h.actions,
|
|
184
|
+
report: (s) => ({
|
|
185
|
+
won: s.won, lost: s.lost, x: round3(s.x), y: round3(s.y), height: s.height[idx(s, Math.floor(s.x), Math.floor(s.y))], carrying: s.carrying, delivered: s.delivered, items: s.items.length,
|
|
186
|
+
seenItems: s.items.filter((it) => it.seen && !it.got).map((it) => ({ x: it.x, y: it.y })), goal: { ...s.goal }, said: s.said, hint: s.hint, t: round3(s.t), w: s.w, h: s.h,
|
|
187
|
+
score: hooks.score ? hooks.score(s) : s.score, deaths: 0,
|
|
188
|
+
}),
|
|
189
|
+
});
|
|
190
|
+
sim.kit = kit; sim.bots = bots;
|
|
191
|
+
sim.value = () => (hooks.value ? hooks.value(sim.state) : value(sim.state));
|
|
192
|
+
void bfs;
|
|
193
|
+
return sim;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// ─── worlds ──────────────────────────────────────────────────────────────────
|
|
197
|
+
|
|
198
|
+
/** An island: smooth hills from value noise, water round it, trees and rocks, items far from home, one who knows. */
|
|
199
|
+
export function exploreLevel(rng, { size = 32, items = 3, trees = 40, rocks = 12, npcs = 1, fog = 7, says } = {}) {
|
|
200
|
+
const w = size, h = size, n = (Math.ceil(size / 6) + 2);
|
|
201
|
+
const grid = Array.from({ length: n * n }, () => rng());
|
|
202
|
+
const noise = (x, y) => { const gx = (x / w) * (n - 3) + 1, gy = (y / h) * (n - 3) + 1, ix = Math.floor(gx), iy = Math.floor(gy), fx = gx - ix, fy = gy - iy; const sm = (t) => t * t * (3 - 2 * t); const g = (a, b) => grid[clamp(b, 0, n - 1) * n + clamp(a, 0, n - 1)]; return (g(ix, iy) * (1 - sm(fx)) + g(ix + 1, iy) * sm(fx)) * (1 - sm(fy)) + (g(ix, iy + 1) * (1 - sm(fx)) + g(ix + 1, iy + 1) * sm(fx)) * sm(fy); };
|
|
203
|
+
const cells = [];
|
|
204
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
205
|
+
const wob = 1 + (noise(y * 0.7, x * 0.7) - 0.5) * 0.35;
|
|
206
|
+
const edge = (1 - Math.hypot(x - (w - 1) / 2, y - (h - 1) / 2) / (size * 0.47 * wob)) / 0.32;
|
|
207
|
+
const v = noise(x, y) * Math.min(1, edge) * 1.15 - (edge < 1 ? (1 - edge) * 0.4 : 0);
|
|
208
|
+
cells.push(v < 0.12 ? '~' : String.fromCharCode(97 + clamp(Math.round(v * 9), 0, 25)));
|
|
209
|
+
}
|
|
210
|
+
const land = (x, y) => cells[y * w + x] !== '~';
|
|
211
|
+
// home on the lowest open land near a corner; the walkable part from there
|
|
212
|
+
let start = null;
|
|
213
|
+
for (let r = 3; r < size && !start; r++) for (let y = r; y < size - r && !start; y++) for (let x = r; x < size - r && !start; x++) if (land(x, y) && land(x + 1, y) && Math.min(x, y) <= r + 2) start = { x, y };
|
|
214
|
+
start ??= { x: w >> 1, y: h >> 1 };
|
|
215
|
+
const climb = (a, b) => Math.abs((cells[a].charCodeAt(0) - 97) * 0.5 - (cells[b].charCodeAt(0) - 97) * 0.5) <= 1.6;
|
|
216
|
+
const reach = new Map(), q = [start.y * w + start.x]; reach.set(q[0], 0);
|
|
217
|
+
for (let qi = 0; qi < q.length; qi++) { const i = q[qi], x = i % w, y = (i / w) | 0; for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { const nx = x + dx, ny = y + dy, j = ny * w + nx; if (nx < 0 || ny < 0 || nx >= w || ny >= h || reach.has(j) || !land(nx, ny) || !climb(i, j)) continue; reach.set(j, reach.get(i) + 1); q.push(j); } }
|
|
218
|
+
const far = [...reach.entries()].sort((a, b) => b[1] - a[1]).map(([i]) => ({ x: i % w, y: (i / w) | 0 }));
|
|
219
|
+
const things = [], taken = new Set([`${start.x},${start.y}`, `${start.x + 1},${start.y}`]);
|
|
220
|
+
const take = (p) => { const k = `${p.x},${p.y}`; if (taken.has(k)) return false; taken.add(k); return true; };
|
|
221
|
+
// items: far away and apart from each other
|
|
222
|
+
for (const p of far) { if (things.filter((t) => t.kind === 'item').length >= items) break; if (things.some((t) => Math.hypot(t.x - p.x, t.y - p.y) < size / 4)) continue; if (take(p)) things.push({ kind: 'item', x: p.x, y: p.y }); }
|
|
223
|
+
const mid = far.slice(Math.floor(far.length * 0.55), Math.floor(far.length * 0.75));
|
|
224
|
+
for (let i = 0; i < npcs && mid.length; i++) { const p = rng.pick(mid); if (take(p)) things.push({ kind: 'npc', x: p.x, y: p.y, says: says ?? 'I saw something shine to the {dir}.' }); }
|
|
225
|
+
// trees and rocks only where every item and the one who knows can still be walked to from home
|
|
226
|
+
const blocked = new Set(things.filter((t) => t.kind === 'npc').map((t) => t.y * w + t.x));
|
|
227
|
+
const wanted = things.map((t) => t.y * w + t.x);
|
|
228
|
+
const connected = () => {
|
|
229
|
+
const seen = new Set([start.y * w + start.x]), q2 = [start.y * w + start.x];
|
|
230
|
+
for (let qi = 0; qi < q2.length; qi++) { const i = q2[qi], x = i % w, y = (i / w) | 0; for (const [dx, dy] of [[1, 0], [-1, 0], [0, 1], [0, -1]]) { const nx = x + dx, ny = y + dy, j = ny * w + nx; if (nx < 0 || ny < 0 || nx >= w || ny >= h || seen.has(j) || !land(nx, ny) || !climb(i, j)) continue; seen.add(j); if (!blocked.has(j)) q2.push(j); } }
|
|
231
|
+
return wanted.every((j) => seen.has(j));
|
|
232
|
+
};
|
|
233
|
+
const spots = rng.shuffle([...reach.keys()].map((i) => ({ x: i % w, y: (i / w) | 0 })));
|
|
234
|
+
let tr = 0, ro = 0;
|
|
235
|
+
for (const p of spots) {
|
|
236
|
+
if (tr >= trees && ro >= rocks) break;
|
|
237
|
+
const k = `${p.x},${p.y}`; if (taken.has(k) || Math.hypot(p.x - start.x, p.y - start.y) < 2.5) continue;
|
|
238
|
+
blocked.add(p.y * w + p.x);
|
|
239
|
+
if (!connected()) { blocked.delete(p.y * w + p.x); continue; }
|
|
240
|
+
if (tr < trees) { things.push({ kind: 'tree', x: p.x, y: p.y, s: Math.round(rng.range(0.8, 1.3) * 10) / 10 }); tr++; } else { things.push({ kind: 'rock', x: p.x, y: p.y, s: Math.round(rng.range(0.6, 1.1) * 10) / 10 }); ro++; }
|
|
241
|
+
taken.add(k);
|
|
242
|
+
}
|
|
243
|
+
return { size: [w, h], heights: cells.join(''), things, goal: { x: start.x, y: start.y }, start: { x: start.x + 1, y: start.y }, fog };
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/** Easier versions of a level, the smallest change first (for play()'s fixes). */
|
|
247
|
+
export function easier(lv) {
|
|
248
|
+
const fog = lv.fog ?? 7, out = [{ change: { fog: fog + 3 }, say: `sight ${fog} → ${fog + 3} cells` }];
|
|
249
|
+
if (lv.time) out.push({ change: { time: Math.round(lv.time * 1.6) }, say: `time ${lv.time} → ${Math.round(lv.time * 1.6)} s` });
|
|
250
|
+
out.push({ change: { fog: fog + 8, ...(lv.time ? { time: Math.round(lv.time * 2) } : {}) }, say: `sight ${fog} → ${fog + 8} cells` });
|
|
251
|
+
return out;
|
|
252
|
+
}
|
|
253
|
+
export function harder(lv) {
|
|
254
|
+
const fog = lv.fog ?? 7, out = [];
|
|
255
|
+
if (fog > 3) out.push({ change: { fog: fog - 2 }, say: `sight ${fog} → ${fog - 2} cells` });
|
|
256
|
+
out.push({ change: { time: lv.time ? Math.round(lv.time * 0.8) : 240 }, say: lv.time ? `time ${lv.time} → ${Math.round(lv.time * 0.8)} s` : 'a time limit of 240 s' });
|
|
257
|
+
return out;
|
|
258
|
+
}
|
package/src/grid.js
ADDED
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
// @clarity-js/engine — the puzzle-grid kit: a board of cells, one move at a time, and four kinds of goal.
|
|
2
|
+
//
|
|
3
|
+
// match swap two neighbours to line up three or more of a colour; reach `target` points in `moves`
|
|
4
|
+
// push walk a keeper who pushes crates onto marks (a map: # wall, . mark, $ crate, * crate on a mark, @ keeper)
|
|
5
|
+
// lights pressing a cell flips it and its four neighbours; turn every light off
|
|
6
|
+
// slide slide the tiles into order, the gap last
|
|
7
|
+
//
|
|
8
|
+
// Every game is a simulation of the sim kit (createSim): the same seed plays the same board, a bot can
|
|
9
|
+
// try a move and take it back (snapshot/restore), and the page only draws what report() says.
|
|
10
|
+
|
|
11
|
+
import { createSim, createRng } from '@ozsarman/clarityjs/sim';
|
|
12
|
+
|
|
13
|
+
const DIRS = { left: [-1, 0], right: [1, 0], up: [0, -1], down: [0, 1] };
|
|
14
|
+
const DIR_NAMES = Object.keys(DIRS);
|
|
15
|
+
|
|
16
|
+
export const kit = {
|
|
17
|
+
name: 'puzzle-grid',
|
|
18
|
+
title: 'Puzzle on a grid',
|
|
19
|
+
describe: 'A board of cells and one move at a time: match colours, push crates onto marks, switch lights off, or slide tiles into order.',
|
|
20
|
+
goals: ['match', 'push', 'lights', 'slide'],
|
|
21
|
+
settings: {},
|
|
22
|
+
level: {
|
|
23
|
+
match: { size: [7, 7], colors: 5, moves: 20, target: 600 },
|
|
24
|
+
push: { map: ['#######', '# #', '# $. #', '# @ #', '#######'], moves: 40 },
|
|
25
|
+
lights: { size: [5, 5], presses: 6, moves: 30 },
|
|
26
|
+
slide: { size: [3, 3], shuffle: 24, moves: 60 },
|
|
27
|
+
},
|
|
28
|
+
examples: ['A calm marbling puzzle: comb the ink to match the pattern', 'Push the tea glasses onto the tray marks', 'Switch off every lantern in the night market', 'Slide the tiles of a broken mosaic into place'],
|
|
29
|
+
input: ['tap', 'drag', 'arrows'],
|
|
30
|
+
continuous: false,
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
// ─── the board ───────────────────────────────────────────────────────────────
|
|
34
|
+
|
|
35
|
+
const at = (s, x, y) => (x < 0 || y < 0 || x >= s.w || y >= s.h ? null : s.cells[y * s.w + x]);
|
|
36
|
+
const put = (s, x, y, v) => { s.cells[y * s.w + x] = v; };
|
|
37
|
+
|
|
38
|
+
function parseMap(map) {
|
|
39
|
+
const rows = map.map((r) => String(r));
|
|
40
|
+
const h = rows.length, w = Math.max(...rows.map((r) => r.length));
|
|
41
|
+
const walls = [], marks = [], boxes = [];
|
|
42
|
+
let player = null;
|
|
43
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
44
|
+
const c = rows[y][x] ?? ' ';
|
|
45
|
+
walls.push(c === '#');
|
|
46
|
+
marks.push(c === '.' || c === '*' || c === '+');
|
|
47
|
+
if (c === '$' || c === '*') boxes.push(y * w + x);
|
|
48
|
+
if (c === '@' || c === '+') player = y * w + x;
|
|
49
|
+
}
|
|
50
|
+
return { w, h, walls, marks, boxes, player };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
// match: runs of three or more, in rows and in columns
|
|
54
|
+
function runs(s) {
|
|
55
|
+
const hit = new Set();
|
|
56
|
+
for (let y = 0; y < s.h; y++) for (let x = 0; x < s.w; x++) {
|
|
57
|
+
const v = at(s, x, y);
|
|
58
|
+
if (v == null || v < 0) continue;
|
|
59
|
+
if (x <= s.w - 3 && at(s, x + 1, y) === v && at(s, x + 2, y) === v) { let k = x; while (at(s, k, y) === v) hit.add(y * s.w + k++); }
|
|
60
|
+
if (y <= s.h - 3 && at(s, x, y + 1) === v && at(s, x, y + 2) === v) { let k = y; while (at(s, x, k) === v) hit.add(k++ * s.w + x); }
|
|
61
|
+
}
|
|
62
|
+
return hit;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function fillNoRuns(s, rng) {
|
|
66
|
+
for (let y = 0; y < s.h; y++) for (let x = 0; x < s.w; x++) {
|
|
67
|
+
let v, tries = 0;
|
|
68
|
+
do { v = rng.int(s.colors); tries++; }
|
|
69
|
+
while (tries < 20 && ((x >= 2 && at(s, x - 1, y) === v && at(s, x - 2, y) === v) || (y >= 2 && at(s, x, y - 1) === v && at(s, x, y - 2) === v)));
|
|
70
|
+
put(s, x, y, v);
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function swapMakesRun(s, x, y, x2, y2) {
|
|
75
|
+
const a = at(s, x, y), b = at(s, x2, y2);
|
|
76
|
+
if (a == null || b == null || a === b) return false;
|
|
77
|
+
put(s, x, y, b); put(s, x2, y2, a);
|
|
78
|
+
const ok = runs(s).size > 0;
|
|
79
|
+
put(s, x, y, a); put(s, x2, y2, b);
|
|
80
|
+
return ok;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function matchMoves(s) {
|
|
84
|
+
const out = [];
|
|
85
|
+
for (let y = 0; y < s.h; y++) for (let x = 0; x < s.w; x++) {
|
|
86
|
+
if (x < s.w - 1 && swapMakesRun(s, x, y, x + 1, y)) out.push({ act: 'swap', args: [x, y, 'right'] });
|
|
87
|
+
if (y < s.h - 1 && swapMakesRun(s, x, y, x, y + 1)) out.push({ act: 'swap', args: [x, y, 'down'] });
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function settle(s, ctx) {
|
|
93
|
+
let chain = 0, cleared = 0;
|
|
94
|
+
for (;;) {
|
|
95
|
+
const hit = runs(s);
|
|
96
|
+
if (!hit.size) break;
|
|
97
|
+
chain++;
|
|
98
|
+
cleared += hit.size;
|
|
99
|
+
s.score += hit.size * 10 * chain;
|
|
100
|
+
for (const i of hit) s.cells[i] = -1;
|
|
101
|
+
ctx.emit({ type: 'clear', cells: [...hit], chain });
|
|
102
|
+
for (let x = 0; x < s.w; x++) { // gravity, then new pieces from above
|
|
103
|
+
let write = s.h - 1;
|
|
104
|
+
for (let y = s.h - 1; y >= 0; y--) { const v = at(s, x, y); if (v >= 0) { put(s, x, write, v); if (write !== y) put(s, x, y, -1); write--; } }
|
|
105
|
+
for (let y = write; y >= 0; y--) put(s, x, y, ctx.rng.int(s.colors));
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
if (!matchMoves(s).length) { // no move left: shuffle (by the seed) until there is one
|
|
109
|
+
let guard = 0;
|
|
110
|
+
do { ctx.rng.shuffle(s.cells); guard++; } while ((runs(s).size || !matchMoves(s).length) && guard < 200);
|
|
111
|
+
ctx.emit({ type: 'shuffle' });
|
|
112
|
+
}
|
|
113
|
+
return cleared;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
// lights: press flips a cross
|
|
117
|
+
function flip(s, x, y) { for (const [dx, dy] of [[0, 0], [1, 0], [-1, 0], [0, 1], [0, -1]]) { const v = at(s, x + dx, y + dy); if (v != null) put(s, x + dx, y + dy, v ? 0 : 1); } }
|
|
118
|
+
|
|
119
|
+
// ─── the goals ───────────────────────────────────────────────────────────────
|
|
120
|
+
|
|
121
|
+
function setupGoal(level, ctx) {
|
|
122
|
+
const goal = level.goal ?? 'match';
|
|
123
|
+
const base = { ...kit.level[goal], ...level };
|
|
124
|
+
const s = { goal, moves: Number(base.moves ?? 0) || 0, used: 0, score: 0, won: false, lost: false, target: Number(base.target ?? 0) || 0 };
|
|
125
|
+
if (goal === 'match') {
|
|
126
|
+
[s.w, s.h] = base.size ?? [7, 7];
|
|
127
|
+
s.colors = Math.max(3, Math.min(8, base.colors ?? 5));
|
|
128
|
+
s.cells = new Array(s.w * s.h).fill(0);
|
|
129
|
+
fillNoRuns(s, ctx.rng);
|
|
130
|
+
if (!matchMoves(s).length) settle(s, ctx);
|
|
131
|
+
} else if (goal === 'push') {
|
|
132
|
+
const m = parseMap(base.map);
|
|
133
|
+
Object.assign(s, { w: m.w, h: m.h, walls: m.walls, marks: m.marks, boxes: m.boxes, player: m.player });
|
|
134
|
+
if (s.player == null) throw new Error('a push level needs a keeper: @ in its map');
|
|
135
|
+
if (!s.boxes.length || s.boxes.length > s.marks.filter(Boolean).length) throw new Error('a push level needs crates ($) and at least as many marks (.)');
|
|
136
|
+
s.cells = s.walls.map((w) => (w ? 1 : 0));
|
|
137
|
+
} else if (goal === 'lights') {
|
|
138
|
+
[s.w, s.h] = base.size ?? [5, 5];
|
|
139
|
+
s.cells = new Array(s.w * s.h).fill(0);
|
|
140
|
+
const presses = Math.max(1, base.presses ?? Math.round((s.w * s.h) / 4));
|
|
141
|
+
for (let i = 0; i < presses; i++) flip(s, ctx.rng.int(s.w), ctx.rng.int(s.h));
|
|
142
|
+
if (s.cells.every((v) => !v)) flip(s, 0, 0);
|
|
143
|
+
} else if (goal === 'slide') {
|
|
144
|
+
[s.w, s.h] = base.size ?? [3, 3];
|
|
145
|
+
s.cells = Array.from({ length: s.w * s.h }, (_, i) => (i + 1) % (s.w * s.h));
|
|
146
|
+
s.gap = s.w * s.h - 1;
|
|
147
|
+
let last = null;
|
|
148
|
+
for (let i = 0, n = Math.max(2, base.shuffle ?? 24); i < n; i++) {
|
|
149
|
+
const opts = DIR_NAMES.filter((d) => d !== last && slideOk(s, d));
|
|
150
|
+
const d = ctx.rng.pick(opts);
|
|
151
|
+
slideGap(s, d);
|
|
152
|
+
last = { left: 'right', right: 'left', up: 'down', down: 'up' }[d];
|
|
153
|
+
}
|
|
154
|
+
if (solved(s)) { slideGap(s, slideOk(s, 'left') ? 'left' : 'up'); }
|
|
155
|
+
} else throw new Error(`no goal "${goal}" in the puzzle-grid kit (it has ${kit.goals.join(', ')})`);
|
|
156
|
+
return s;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
function slideOk(s, d) { const [dx, dy] = DIRS[d]; const x = (s.gap % s.w) + dx, y = Math.floor(s.gap / s.w) + dy; return x >= 0 && y >= 0 && x < s.w && y < s.h; }
|
|
160
|
+
function slideGap(s, d) { const [dx, dy] = DIRS[d]; const to = s.gap + dx + dy * s.w; s.cells[s.gap] = s.cells[to]; s.cells[to] = 0; s.gap = to; }
|
|
161
|
+
|
|
162
|
+
function solved(s) {
|
|
163
|
+
if (s.goal === 'match') return s.target > 0 && s.score >= s.target;
|
|
164
|
+
if (s.goal === 'push') return s.boxes.every((b) => s.marks[b]);
|
|
165
|
+
if (s.goal === 'lights') return s.cells.every((v) => !v);
|
|
166
|
+
if (s.goal === 'slide') return s.cells.every((v, i) => v === (i + 1) % (s.w * s.h));
|
|
167
|
+
return false;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function legal(s) {
|
|
171
|
+
if (s.won || s.lost) return [];
|
|
172
|
+
if (s.goal === 'match') return matchMoves(s);
|
|
173
|
+
if (s.goal === 'push') return DIR_NAMES.filter((d) => pushOk(s, d)).map((d) => ({ act: 'move', args: [d] }));
|
|
174
|
+
if (s.goal === 'lights') { const out = []; for (let y = 0; y < s.h; y++) for (let x = 0; x < s.w; x++) out.push({ act: 'press', args: [x, y] }); return out; }
|
|
175
|
+
if (s.goal === 'slide') return DIR_NAMES.filter((d) => slideOk(s, d)).map((d) => ({ act: 'move', args: [d] }));
|
|
176
|
+
return [];
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function pushOk(s, d) {
|
|
180
|
+
const [dx, dy] = DIRS[d], px = s.player % s.w, py = Math.floor(s.player / s.w);
|
|
181
|
+
const nx = px + dx, ny = py + dy;
|
|
182
|
+
if (nx < 0 || ny < 0 || nx >= s.w || ny >= s.h || s.walls[ny * s.w + nx]) return false;
|
|
183
|
+
const n = ny * s.w + nx;
|
|
184
|
+
if (!s.boxes.includes(n)) return true;
|
|
185
|
+
const bx = nx + dx, by = ny + dy;
|
|
186
|
+
if (bx < 0 || by < 0 || bx >= s.w || by >= s.h) return false;
|
|
187
|
+
const b = by * s.w + bx;
|
|
188
|
+
return !s.walls[b] && !s.boxes.includes(b);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function spend(s, ctx) {
|
|
192
|
+
s.used++;
|
|
193
|
+
if (solved(s)) { s.won = true; ctx.emit({ type: 'won', moves: s.used }); }
|
|
194
|
+
else if (s.moves && s.used >= s.moves) { s.lost = true; ctx.emit({ type: 'lost', why: 'moves' }); }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const ACTIONS = {
|
|
198
|
+
/** Swap a cell with its neighbour (match). dir: left, right, up, down. A swap that lines nothing up is refused. */
|
|
199
|
+
swap(s, ctx, x, y, dir) {
|
|
200
|
+
if (s.goal !== 'match' || s.won || s.lost) return false;
|
|
201
|
+
const [dx, dy] = DIRS[dir] ?? [0, 0];
|
|
202
|
+
if (!swapMakesRun(s, x, y, x + dx, y + dy)) { ctx.emit({ type: 'refused', x, y, dir }); return false; }
|
|
203
|
+
const a = at(s, x, y); put(s, x, y, at(s, x + dx, y + dy)); put(s, x + dx, y + dy, a);
|
|
204
|
+
ctx.emit({ type: 'swap', x, y, dir });
|
|
205
|
+
settle(s, ctx);
|
|
206
|
+
spend(s, ctx);
|
|
207
|
+
return true;
|
|
208
|
+
},
|
|
209
|
+
/** Move: the keeper (push) or the gap (slide). dir: left, right, up, down. */
|
|
210
|
+
move(s, ctx, dir) {
|
|
211
|
+
if (s.won || s.lost || !DIRS[dir]) return false;
|
|
212
|
+
if (s.goal === 'push') {
|
|
213
|
+
if (!pushOk(s, dir)) return false;
|
|
214
|
+
const [dx, dy] = DIRS[dir], n = s.player + dx + dy * s.w, i = s.boxes.indexOf(n);
|
|
215
|
+
if (i >= 0) { s.boxes[i] = n + dx + dy * s.w; ctx.emit({ type: 'push', from: n, to: s.boxes[i] }); }
|
|
216
|
+
s.player = n;
|
|
217
|
+
} else if (s.goal === 'slide') {
|
|
218
|
+
if (!slideOk(s, dir)) return false;
|
|
219
|
+
slideGap(s, dir);
|
|
220
|
+
} else return false;
|
|
221
|
+
spend(s, ctx);
|
|
222
|
+
return true;
|
|
223
|
+
},
|
|
224
|
+
/** Press a cell (lights): it and its four neighbours flip. */
|
|
225
|
+
press(s, ctx, x, y) {
|
|
226
|
+
if (s.goal !== 'lights' || s.won || s.lost || at(s, x, y) == null) return false;
|
|
227
|
+
flip(s, x, y);
|
|
228
|
+
ctx.emit({ type: 'press', x, y });
|
|
229
|
+
spend(s, ctx);
|
|
230
|
+
return true;
|
|
231
|
+
},
|
|
232
|
+
};
|
|
233
|
+
|
|
234
|
+
// ─── a game of this kit ──────────────────────────────────────────────────────
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* @param {{ game: object, level: object, seed?: any, hooks?: object }} options
|
|
238
|
+
* hooks: the game's rules.js — setup(state, ctx), step(state, dt, ctx), actions { name(state, ctx, …) },
|
|
239
|
+
* won(state), lost(state), score(state): each takes the kit's place where it is given.
|
|
240
|
+
*/
|
|
241
|
+
export function create({ level, seed = 1, hooks = {} }) {
|
|
242
|
+
const userActions = hooks.actions ?? {};
|
|
243
|
+
const wrap = Object.fromEntries(Object.entries(userActions).map(([k, f]) => [k, (s, ctx, ...a) => { const r = f(s, ctx, ...a); check(s, ctx); return r; }]));
|
|
244
|
+
const check = (s, ctx) => {
|
|
245
|
+
if (s.won || s.lost) return;
|
|
246
|
+
if (hooks.won?.(s)) { s.won = true; ctx.emit({ type: 'won', moves: s.used }); }
|
|
247
|
+
else if (hooks.lost?.(s)) { s.lost = true; ctx.emit({ type: 'lost', why: 'rules' }); }
|
|
248
|
+
};
|
|
249
|
+
const kitActions = Object.fromEntries(Object.entries(ACTIONS).map(([k, f]) => [k, (s, ctx, ...a) => { const r = f(s, ctx, ...a); check(s, ctx); return r; }]));
|
|
250
|
+
const sim = createSim({
|
|
251
|
+
seed,
|
|
252
|
+
setup: (ctx) => { const s = setupGoal(level, ctx); hooks.setup?.(s, ctx, level); return s; },
|
|
253
|
+
step: (s, dt, ctx) => { hooks.step?.(s, dt, ctx); check(s, ctx); },
|
|
254
|
+
actions: { ...kitActions, ...wrap },
|
|
255
|
+
report: (s) => report(s, hooks),
|
|
256
|
+
});
|
|
257
|
+
sim.legal = () => legal(sim.state);
|
|
258
|
+
sim.value = () => value(sim.state, hooks);
|
|
259
|
+
sim.kit = kit;
|
|
260
|
+
return sim;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function report(s, hooks) {
|
|
264
|
+
const r = {
|
|
265
|
+
goal: s.goal, w: s.w, h: s.h, cells: [...s.cells], won: s.won, lost: s.lost,
|
|
266
|
+
moves: s.moves, used: s.used, left: s.moves ? s.moves - s.used : null,
|
|
267
|
+
score: hooks.score ? hooks.score(s) : s.score, target: s.target || null,
|
|
268
|
+
};
|
|
269
|
+
if (s.goal === 'push') Object.assign(r, { player: s.player, boxes: [...s.boxes], marks: s.marks.map((m, i) => (m ? i : -1)).filter((i) => i >= 0), onMarks: s.boxes.filter((b) => s.marks[b]).length });
|
|
270
|
+
if (s.goal === 'lights') r.lit = s.cells.filter(Boolean).length;
|
|
271
|
+
if (s.goal === 'slide') r.inPlace = s.cells.filter((v, i) => v && v === i + 1).length;
|
|
272
|
+
if (s.goal === 'match') r.colors = s.colors;
|
|
273
|
+
return r;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
/** How near the goal (higher is nearer): what a greedy bot climbs. */
|
|
277
|
+
function value(s, hooks) {
|
|
278
|
+
if (s.won) return 1e9 - s.used;
|
|
279
|
+
if (s.lost) return -1e9;
|
|
280
|
+
if (hooks.value) return hooks.value(s);
|
|
281
|
+
if (s.goal === 'match') return s.score;
|
|
282
|
+
if (s.goal === 'lights') return -s.cells.filter(Boolean).length;
|
|
283
|
+
if (s.goal === 'slide') { let d = 0; s.cells.forEach((v, i) => { if (!v) return; const t = v - 1; d += Math.abs((t % s.w) - (i % s.w)) + Math.abs(Math.floor(t / s.w) - Math.floor(i / s.w)); }); return -d; }
|
|
284
|
+
if (s.goal === 'push') {
|
|
285
|
+
const marks = s.marks.map((m, i) => (m ? i : -1)).filter((i) => i >= 0);
|
|
286
|
+
let d = 0;
|
|
287
|
+
for (const b of s.boxes) d += Math.min(...marks.map((m) => Math.abs((m % s.w) - (b % s.w)) + Math.abs(Math.floor(m / s.w) - Math.floor(b / s.w))));
|
|
288
|
+
const px = s.player % s.w, py = Math.floor(s.player / s.w);
|
|
289
|
+
const loose = s.boxes.filter((b) => !s.marks[b]).map((b) => Math.abs((b % s.w) - px) + Math.abs(Math.floor(b / s.w) - py));
|
|
290
|
+
return -d * 10 - (loose.length ? Math.min(...loose) : 0);
|
|
291
|
+
}
|
|
292
|
+
return 0;
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
// ─── solving: what the planner bot uses ──────────────────────────────────────
|
|
296
|
+
|
|
297
|
+
/** Lights out by algebra (each press is its own inverse): the presses that switch everything off, or null. */
|
|
298
|
+
export function solveLights(cells, w, h) {
|
|
299
|
+
const n = w * h, rows = [];
|
|
300
|
+
for (let i = 0; i < n; i++) {
|
|
301
|
+
const row = new Uint8Array(n + 1), x = i % w, y = Math.floor(i / w);
|
|
302
|
+
for (const [dx, dy] of [[0, 0], [1, 0], [-1, 0], [0, 1], [0, -1]]) { const xx = x + dx, yy = y + dy; if (xx >= 0 && yy >= 0 && xx < w && yy < h) row[yy * w + xx] = 1; }
|
|
303
|
+
row[n] = cells[i] ? 1 : 0;
|
|
304
|
+
rows.push(row);
|
|
305
|
+
}
|
|
306
|
+
let r = 0; const pivots = [];
|
|
307
|
+
for (let c = 0; c < n && r < n; c++) {
|
|
308
|
+
let p = r; while (p < n && !rows[p][c]) p++;
|
|
309
|
+
if (p === n) continue;
|
|
310
|
+
[rows[r], rows[p]] = [rows[p], rows[r]];
|
|
311
|
+
for (let k = 0; k < n; k++) if (k !== r && rows[k][c]) for (let j = c; j <= n; j++) rows[k][j] ^= rows[r][j];
|
|
312
|
+
pivots.push(c); r++;
|
|
313
|
+
}
|
|
314
|
+
for (let k = r; k < n; k++) if (rows[k][n]) return null;
|
|
315
|
+
const press = new Uint8Array(n);
|
|
316
|
+
pivots.forEach((c, i) => { press[c] = rows[i][n]; });
|
|
317
|
+
return [...press].map((v, i) => (v ? i : -1)).filter((i) => i >= 0);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/**
|
|
321
|
+
* The shortest moves to the goal from where the game is, by search (push and slide), or null when it is
|
|
322
|
+
* not found within `budget` positions.
|
|
323
|
+
*/
|
|
324
|
+
export function search(sim, { budget = 60000 } = {}) {
|
|
325
|
+
const s0 = sim.state;
|
|
326
|
+
if (s0.goal === 'lights') { const p = solveLights(s0.cells, s0.w, s0.h); return p && p.map((i) => ({ act: 'press', args: [i % s0.w, Math.floor(i / s0.w)] })); }
|
|
327
|
+
if (s0.goal !== 'push' && s0.goal !== 'slide') return null;
|
|
328
|
+
const key = (s) => (s.goal === 'push' ? s.player + '|' + [...s.boxes].sort((a, b) => a - b).join(',') : s.cells.join(','));
|
|
329
|
+
const h = (s) => -value(s, {});
|
|
330
|
+
const start = sim.snapshot();
|
|
331
|
+
const seen = new Map([[key(s0), null]]);
|
|
332
|
+
// best-first on (moves so far + estimate): A* for slide, greedy-weighted for push
|
|
333
|
+
const open = [{ snap: start, path: [], f: h(s0) }];
|
|
334
|
+
let n = 0;
|
|
335
|
+
while (open.length && n < budget) {
|
|
336
|
+
let bi = 0; for (let i = 1; i < open.length; i++) if (open[i].f < open[bi].f) bi = i;
|
|
337
|
+
const cur = open[bi]; open[bi] = open[open.length - 1]; open.pop();
|
|
338
|
+
n++;
|
|
339
|
+
sim.restore(cur.snap);
|
|
340
|
+
for (const m of legal(sim.state)) {
|
|
341
|
+
sim.restore(cur.snap);
|
|
342
|
+
const saveLog = sim.log.length;
|
|
343
|
+
sim.act(m.act, ...m.args);
|
|
344
|
+
sim.log.length = saveLog;
|
|
345
|
+
const s = sim.state;
|
|
346
|
+
if (s.won) { sim.restore(start); return [...cur.path, m]; }
|
|
347
|
+
if (s.lost) continue;
|
|
348
|
+
const k = key(s);
|
|
349
|
+
if (seen.has(k)) continue;
|
|
350
|
+
seen.set(k, null);
|
|
351
|
+
const path = [...cur.path, m];
|
|
352
|
+
open.push({ snap: sim.snapshot(), path, f: path.length * (s.goal === 'push' ? 0.5 : 1) + h(s) / (s.goal === 'push' ? 10 : 1) });
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
sim.restore(start);
|
|
356
|
+
return null;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
/** Easier and harder versions of a level, the smallest change first (play()'s fixes, the editor's buttons). */
|
|
360
|
+
export function easier(lv) {
|
|
361
|
+
const goal = lv.goal ?? 'match', out = [];
|
|
362
|
+
if (goal === 'match' && lv.target) out.push({ change: { target: Math.round(lv.target * 0.8 / 10) * 10 }, say: `target ${lv.target} → ${Math.round(lv.target * 0.8 / 10) * 10}` });
|
|
363
|
+
if (lv.moves) out.push({ change: { moves: Math.ceil(lv.moves * 1.25) }, say: `moves ${lv.moves} → ${Math.ceil(lv.moves * 1.25)}` });
|
|
364
|
+
if (goal === 'slide' && lv.shuffle) out.push({ change: { shuffle: Math.max(4, Math.round(lv.shuffle * 0.75)) }, say: `shuffle ${lv.shuffle} → ${Math.max(4, Math.round(lv.shuffle * 0.75))}` });
|
|
365
|
+
if (goal === 'lights' && lv.presses > 1) out.push({ change: { presses: lv.presses - 1 }, say: `presses ${lv.presses} → ${lv.presses - 1}` });
|
|
366
|
+
return out;
|
|
367
|
+
}
|
|
368
|
+
export function harder(lv) {
|
|
369
|
+
const goal = lv.goal ?? 'match', out = [];
|
|
370
|
+
if (goal === 'match') out.push({ change: { target: Math.round(((lv.target ?? 600) * 1.2) / 10) * 10 }, say: `target ${lv.target ?? 600} → ${Math.round(((lv.target ?? 600) * 1.2) / 10) * 10}` });
|
|
371
|
+
if (goal === 'lights') out.push({ change: { presses: (lv.presses ?? 6) + 2 }, say: `presses ${lv.presses ?? 6} → ${(lv.presses ?? 6) + 2}` });
|
|
372
|
+
if (goal === 'slide') out.push({ change: { shuffle: (lv.shuffle ?? 24) + 8 }, say: `shuffle ${lv.shuffle ?? 24} → ${(lv.shuffle ?? 24) + 8}` });
|
|
373
|
+
if (lv.moves) out.push({ change: { moves: Math.max(1, Math.floor(lv.moves * 0.8)) }, say: `moves ${lv.moves} → ${Math.max(1, Math.floor(lv.moves * 0.8))}` });
|
|
374
|
+
return out;
|
|
375
|
+
}
|