@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/art.js ADDED
@@ -0,0 +1,115 @@
1
+ // @clarity-js/engine — art: a game's own pictures in place of the kits' shapes.
2
+ //
3
+ // game.json:
4
+ // "art": {
5
+ // "sheet": "art/sheet.png", a picture, by its address from the page (or a data: address)
6
+ // "frame": [16, 16], cut as a grid, numbered across and then down from 0 — or
7
+ // "frames": { "hero0": [0, 0, 16, 24] } rectangles by name: [x, y, width, height]
8
+ // "fps": 8, "smooth": false, how fast frames follow each other; false keeps hard pixels (pixel art)
9
+ // "sprites": {
10
+ // "coin": [10, 11, 12, 13], a part of the game: one frame, or frames shown in turn
11
+ // "hero": { "idle": 0, "run": [1, 2, 3, 4], "jump": 5, "size": [1, 1.5], "fps": 12 } or a list for each thing it does
12
+ // }
13
+ // }
14
+ //
15
+ // A part that has no picture is drawn as the kit's shape, as before: art can come one piece at a
16
+ // time. Which parts a kit has: ART_ROLES. `clarity gen sprite` makes sheets.
17
+
18
+ /** The parts of each kit that a picture can stand for (and, for the ones that do several things, what they do). */
19
+ export const ART_ROLES = {
20
+ platformer: { hero: ['idle', 'run', 'jump', 'fall'], walker: [], coin: [], ground: [], grass: [], ledge: [], spikes: [], door: [], doorOpen: [], flag: [], flagOn: [] },
21
+ 'top-down': { hero: ['idle', 'walk', 'attack', 'hurt'], chaser: [], sentry: [], wall: [], wallFront: [], floor: [], locked: [], exit: [], exitOpen: [], key: [], gem: [], heart: [], shot: [] },
22
+ shmup: { ship: [], foe: ['line', 'vee', 'sine', 'dive', 'column'], boss: [], shot: [], bullet: [], item: [] },
23
+ };
24
+
25
+ const list = (v) => (v == null ? null : Array.isArray(v) ? v : [v]);
26
+
27
+ /**
28
+ * A game's art, ready to draw. spec: game.json's "art". options: base (where a relative address starts: the page),
29
+ * image (a picture already loaded, in place of fetching `sheet`), onLoad() when the picture has arrived.
30
+ * → null when the game has no art, or { ready, has(role), frames(role, state), draw(c, role, x, y, w, h, options) }
31
+ */
32
+ export function createArt(spec, { base = null, image = null, onLoad = null } = {}) {
33
+ if (!spec || typeof spec !== 'object' || (!spec.sheet && !image)) return null;
34
+ const fps = Number(spec.fps) || 8, roles = spec.sprites ?? {}, named = spec.frames ?? null, grid = spec.frame ?? null;
35
+ let img = image, ready = !!image, failed = false;
36
+ if (!img && typeof Image !== 'undefined') {
37
+ img = new Image();
38
+ img.onload = () => { ready = true; onLoad?.(); };
39
+ img.onerror = () => { failed = true; console.warn(`[clarity-engine] the art's picture did not load: ${spec.sheet} (the shapes are drawn instead)`); };
40
+ try { img.src = base ? new URL(spec.sheet, base).href : spec.sheet; } catch { img.src = spec.sheet; }
41
+ }
42
+ // where a frame is in the picture: [x, y, w, h]
43
+ const rect = (f) => {
44
+ if (named && named[f]) return named[f];
45
+ if (typeof f !== 'number' || !grid) return null;
46
+ const fw = grid[0], fh = grid[1], cols = Math.max(1, Math.floor((img.naturalWidth || img.width) / fw));
47
+ return [(f % cols) * fw, Math.floor(f / cols) * fh, fw, fh];
48
+ };
49
+ const of = (role, state) => {
50
+ const r = roles[role];
51
+ if (r == null) return null;
52
+ if (typeof r !== 'object' || Array.isArray(r)) return { frames: list(r), fps, size: null };
53
+ // what it is doing now; failing that, standing still; failing that, the first thing it can do
54
+ const pick = (state != null && r[state] != null ? r[state] : null) ?? r.idle ?? r.frames ?? Object.entries(r).find(([k, v]) => k !== 'fps' && k !== 'size' && v != null)?.[1];
55
+ return pick == null ? null : { frames: list(pick), fps: Number(r.fps) || fps, size: r.size ?? null };
56
+ };
57
+ return {
58
+ get ready() { return ready && !failed; },
59
+ /** Whether a part has a picture (once the sheet has loaded). */
60
+ has(role) { return ready && !failed && roles[role] != null; },
61
+ /** The frames a part shows (doing `state`), and how fast: { frames, fps, size } or null. */
62
+ frames: of,
63
+ /**
64
+ * Draw a part in a box. options: state (what it is doing: "run"), t (seconds: which frame of several), flip
65
+ * (mirrored left to right), key (a number that sets each one's frames off from its neighbours').
66
+ * A part's `size` [w, h] makes the picture that many boxes wide and high, standing on the box's lower edge.
67
+ * → false when there is no picture for it: draw the shape instead.
68
+ */
69
+ draw(c, role, x, y, w, h, { state = null, t = 0, flip = false, key = 0 } = {}) {
70
+ if (!ready || failed) return false;
71
+ const a = of(role, state);
72
+ if (!a || !a.frames.length) return false;
73
+ const r = rect(a.frames[Math.floor(Math.max(0, t) * a.fps + key) % a.frames.length]);
74
+ if (!r) return false;
75
+ if (a.size) { const nw = w * a.size[0], nh = h * a.size[1]; x += (w - nw) / 2; y += h - nh; w = nw; h = nh; }
76
+ const smooth = c.imageSmoothingEnabled;
77
+ c.imageSmoothingEnabled = !!spec.smooth;
78
+ if (flip) { c.save(); c.translate(x + w, y); c.scale(-1, 1); c.drawImage(img, r[0], r[1], r[2], r[3], 0, 0, w, h); c.restore(); }
79
+ else c.drawImage(img, r[0], r[1], r[2], r[3], x, y, w, h);
80
+ c.imageSmoothingEnabled = smooth;
81
+ return true;
82
+ },
83
+ };
84
+ }
85
+
86
+ /** What is wrong with a game's "art", as [path, message, fix?] rows (none: it is fine). kit: the game's kit, for the names of its parts. */
87
+ export function checkArt(art, kit) {
88
+ const out = [], bad = (p, m, f) => out.push([p, m, f]);
89
+ if (art == null) return out;
90
+ if (typeof art !== 'object' || Array.isArray(art)) { bad('art', 'art is an object: { sheet, frame, sprites }'); return out; }
91
+ if (typeof art.sheet !== 'string' || !art.sheet) bad('art.sheet', 'sheet is the address of a picture', '"sheet": "art/sheet.png"');
92
+ const isRect = (r, n) => Array.isArray(r) && r.length === n && r.every((v) => typeof v === 'number' && v >= 0);
93
+ if (art.frame == null && art.frames == null) bad('art.frame', 'say how the picture is cut: frame: [width, height], or frames: { name: [x, y, width, height] }', '"frame": [16, 16]');
94
+ if (art.frame != null && !(isRect(art.frame, 2) && art.frame[0] > 0 && art.frame[1] > 0)) bad('art.frame', 'frame is [width, height] in pixels', '"frame": [16, 16]');
95
+ if (art.frames != null) {
96
+ if (typeof art.frames !== 'object' || Array.isArray(art.frames)) bad('art.frames', 'frames is { name: [x, y, width, height] }');
97
+ else for (const [k, r] of Object.entries(art.frames)) if (!isRect(r, 4)) bad(`art.frames.${k}`, 'a frame is [x, y, width, height] in pixels');
98
+ }
99
+ if (art.fps != null && !(typeof art.fps === 'number' && art.fps > 0 && art.fps <= 60)) bad('art.fps', 'fps is a number from 1 to 60');
100
+ const known = ART_ROLES[kit] ?? null, sprites = art.sprites;
101
+ if (sprites == null || typeof sprites !== 'object' || Array.isArray(sprites)) { bad('art.sprites', 'sprites says which frames stand for which part of the game', known ? `"sprites": { "${Object.keys(known)[0]}": 0 }` : undefined); return out; }
102
+ const isFrame = (f) => (typeof f === 'number' && f >= 0 && Number.isInteger(f) && art.frame != null) || (typeof f === 'string' && art.frames != null && typeof art.frames === 'object' && f in art.frames);
103
+ const frames = (p, v) => { for (const f of list(v)) if (!isFrame(f)) bad(p, typeof f === 'string' ? `no frame is called "${f}"` : `"${f}" is not a frame: a number counts the grid's frames from 0, a name is one of art.frames`); };
104
+ for (const [role, v] of Object.entries(sprites)) {
105
+ if (known && !(role in known)) { bad(`art.sprites.${role}`, `the ${kit} kit has no part called "${role}"`, 'one of ' + Object.keys(known).join(', ')); continue; }
106
+ if (v == null || typeof v !== 'object' || Array.isArray(v)) { if (v != null) frames(`art.sprites.${role}`, v); continue; }
107
+ for (const [state, f] of Object.entries(v)) {
108
+ if (state === 'fps') { if (!(typeof f === 'number' && f > 0 && f <= 60)) bad(`art.sprites.${role}.fps`, 'fps is a number from 1 to 60'); }
109
+ else if (state === 'size') { if (!isRect(f, 2)) bad(`art.sprites.${role}.size`, 'size is [width, height] in cells', '"size": [1, 1.5]'); }
110
+ else if (known && known[role].length && !known[role].includes(state) && state !== 'idle' && state !== 'frames') bad(`art.sprites.${role}.${state}`, `"${role}" does not do "${state}"`, 'one of ' + known[role].join(', '));
111
+ else frames(`art.sprites.${role}.${state}`, f);
112
+ }
113
+ }
114
+ return out;
115
+ }
package/src/bots.js ADDED
@@ -0,0 +1,154 @@
1
+ // @clarity-js/engine — bots that play a game by its rules (never by its page): thousands of moves a second.
2
+ //
3
+ // random any legal move (or any input): the game must not break, whatever is pressed
4
+ // greedy the move that does best right now: is the game easy?
5
+ // planner looks ahead (search, or tries each input and plays on): can the game be finished?
6
+
7
+ import { createRng } from '@ozsarman/clarityjs/sim';
8
+ import { search } from './grid.js';
9
+
10
+ const DT = 1 / 60;
11
+
12
+ function tryMove(sim, m) {
13
+ const snap = sim.snapshot(), n = sim.log.length;
14
+ sim.act(m.act, ...m.args);
15
+ const v = sim.value();
16
+ sim.restore(snap); sim.log.length = n;
17
+ return v;
18
+ }
19
+
20
+ // ─── turn by turn (puzzle-grid) ──────────────────────────────────────────────
21
+
22
+ const turnBots = {
23
+ random(sim, rng) { const l = sim.legal(); return l.length ? rng.pick(l) : null; },
24
+ greedy(sim, rng) {
25
+ const l = sim.legal();
26
+ if (!l.length) return null;
27
+ let best = -Infinity, pick = [];
28
+ for (const m of l) { const v = tryMove(sim, m); if (v > best + 1e-9) { best = v; pick = [m]; } else if (Math.abs(v - best) <= 1e-9) pick.push(m); }
29
+ return rng.pick(pick);
30
+ },
31
+ planner(sim, rng, memo) {
32
+ const s = sim.state;
33
+ if (s.goal === 'push' || s.goal === 'slide' || s.goal === 'lights') {
34
+ if (!memo.failed && (!memo.plan || memo.at !== sim.log.length)) {
35
+ const found = search(sim, { budget: memo.budget ?? 40000 });
36
+ if (!found) memo.failed = true;
37
+ memo.plan = found ?? []; memo.at = sim.log.length;
38
+ }
39
+ const m = memo.plan.shift();
40
+ if (m) { memo.at = sim.log.length + 1; return m; }
41
+ return turnBots.greedy(sim, rng);
42
+ }
43
+ // match: two moves ahead, by the points they make
44
+ const l = sim.legal();
45
+ if (!l.length) return null;
46
+ let best = -Infinity, pick = l[0];
47
+ for (const m of l) {
48
+ const snap = sim.snapshot(), n = sim.log.length;
49
+ sim.act(m.act, ...m.args);
50
+ let v = sim.value();
51
+ if (!sim.state.won && !sim.state.lost) { const l2 = sim.legal(); let b2 = -Infinity; for (const m2 of l2.slice(0, 40)) b2 = Math.max(b2, tryMove(sim, m2)); if (Number.isFinite(b2)) v = v * 0.4 + b2 * 0.6; }
52
+ sim.restore(snap); sim.log.length = n;
53
+ if (v > best) { best = v; pick = m; }
54
+ }
55
+ return pick;
56
+ },
57
+ };
58
+
59
+ // ─── in real time (platformer) ───────────────────────────────────────────────
60
+
61
+ function reflex(sim, memo) {
62
+ const k = sim.sense();
63
+ const jump = k.wall || k.gap || k.spikes || k.walker || k.doorAbove;
64
+ if (jump && k.onGround) memo.hold = 0.32;
65
+ memo.hold = Math.max(0, (memo.hold ?? 0) - 0.1);
66
+ return { dir: k.dir, jump: memo.hold > 0 };
67
+ }
68
+
69
+ function holdFor(sim, dir, jump, seconds) {
70
+ sim.act('input', dir, jump);
71
+ for (let t = 0; t < seconds && !sim.state.won && !sim.state.lost; t += DT) sim.step(DT);
72
+ }
73
+
74
+ const liveBots = {
75
+ random(sim, rng, memo) { if (!memo.in || rng.chance(0.3)) memo.in = { dir: rng.pick([-1, 0, 1, 1]), jump: rng.chance(0.3) }; return memo.in; },
76
+ greedy(sim, rng, memo) { return reflex(sim, memo); },
77
+ planner(sim, rng, memo) {
78
+ // each input held for a moment (a short hop, a full jump, none), then played on by reflex: the best end wins
79
+ const st = sim.state;
80
+ memo.seen ??= { x: st.x, t: st.t };
81
+ const stuck = st.t - memo.seen.t > 3;
82
+ if (Math.abs(st.x - memo.seen.x) > 1.5) memo.seen = { x: st.x, t: st.t };
83
+ let best = -Infinity, pick = null;
84
+ for (const dir of [1, -1, 0]) for (const hop of [0, 0.08, 0.3]) {
85
+ const snap = sim.snapshot(), n = sim.log.length, m = { hold: 0 };
86
+ if (hop) { holdFor(sim, dir, true, hop); holdFor(sim, dir, false, 0.3 - hop); } else holdFor(sim, dir, false, 0.3);
87
+ for (let i = 0; i < 12 && !sim.state.won && !sim.state.lost; i++) { const r = reflex(sim, m); holdFor(sim, r.dir, r.jump, 0.1); }
88
+ let v = sim.value();
89
+ if (stuck) v += rng() * 200; // round and round in one place: try something else
90
+ sim.restore(snap); sim.log.length = n;
91
+ if (v > best) { best = v; pick = { dir, hop }; }
92
+ }
93
+ memo.queue = pick.hop ? [{ dir: pick.dir, jump: true }, ...(pick.hop > 0.1 ? [{ dir: pick.dir, jump: true }, { dir: pick.dir, jump: true }] : [])] : [];
94
+ return memo.queue.shift() ?? { dir: pick.dir, jump: false };
95
+ },
96
+ };
97
+
98
+ export const BOTS = ['random', 'greedy', 'planner'];
99
+
100
+ /**
101
+ * Play one game with a bot. → { bot, seed, won, lost, t, moves, score, deaths, error }
102
+ * @param {() => object} make makes the game's simulation (create() of its kit, at this seed)
103
+ * @param {{ bot: string, seed?: any, seconds?: number, turns?: number, budget?: number }} options
104
+ */
105
+ export function runBot(make, { bot = 'planner', seed = 1, seconds = 120, turns = 400, budget } = {}) {
106
+ const rng = createRng('bot/' + bot + '/' + seed);
107
+ let sim;
108
+ try { sim = make(seed); } catch (e) { return { bot, seed, won: false, lost: false, error: 'it does not start: ' + e.message }; }
109
+ const memo = { budget };
110
+ const out = (extra = {}) => {
111
+ const r = sim.report();
112
+ return { bot, seed, won: !!r.won, lost: !!r.lost, t: Math.round((sim.state.t ?? sim.t) * 100) / 100, moves: sim.log.length, score: r.score ?? 0, deaths: sim.state.deaths ? sim.state.deaths.map((d) => ({ x: d.x, y: d.y, why: d.why })) : [], progress: r.progress, ...extra };
113
+ };
114
+ try {
115
+ const own = sim.bots?.[bot];
116
+ if (sim.bots && !own) throw new Error(`no bot "${bot}" (${Object.keys(sim.bots).join(', ')})`);
117
+ if (own && sim.kit.continuous) {
118
+ // the kit's own bot: a decision ({ act, args, for: seconds }) and the game played on for that long
119
+ for (let t = 0; t < seconds && !sim.state.won && !sim.state.lost;) {
120
+ const d = memo.queue?.length ? memo.queue.shift() : own(sim, rng, memo);
121
+ if (d?.act) sim.act(d.act, ...(d.args ?? []));
122
+ const f = d?.for ?? 0.1;
123
+ for (let k = 0; k < f - 1e-9 && !sim.state.won && !sim.state.lost; k += DT) sim.step(DT);
124
+ t += f;
125
+ }
126
+ } else if (own) {
127
+ for (let i = 0; i < turns && !sim.state.won && !sim.state.lost; i++) {
128
+ const d = own(sim, rng, memo);
129
+ if (!d) break;
130
+ sim.act(d.act, ...(d.args ?? []));
131
+ sim.step(DT);
132
+ }
133
+ } else if (sim.kit.continuous) {
134
+ const pick = liveBots[bot];
135
+ if (!pick) throw new Error(`no bot "${bot}" (${BOTS.join(', ')})`);
136
+ for (let t = 0; t < seconds && !sim.state.won && !sim.state.lost; t += 0.1) {
137
+ const d = memo.queue?.length ? memo.queue.shift() : pick(sim, rng, memo);
138
+ holdFor(sim, d.dir, d.jump, 0.1);
139
+ }
140
+ } else {
141
+ const pick = turnBots[bot];
142
+ if (!pick) throw new Error(`no bot "${bot}" (${BOTS.join(', ')})`);
143
+ for (let i = 0; i < turns && !sim.state.won && !sim.state.lost; i++) {
144
+ const m = pick(sim, rng, memo);
145
+ if (!m) break;
146
+ sim.act(m.act, ...m.args);
147
+ sim.step(DT);
148
+ }
149
+ }
150
+ return out();
151
+ } catch (e) {
152
+ return out({ error: String(e?.message ?? e) });
153
+ }
154
+ }
@@ -0,0 +1,304 @@
1
+ // @clarity-js/engine — the card-and-board kit: turns, a hand or a board, and a rival that thinks.
2
+ //
3
+ // Two rule sets (a level's `goal`):
4
+ // shed a deck of `colors` × numbers 1 … `ranks` (twice each). Play a card of the top card's colour or number,
5
+ // or draw one. The first to empty their hand wins. Wilds (`wilds` of them) go on anything and name a
6
+ // colour. Rivals: `rivals` of them, `rival` 0 (plays any card) … 2 (keeps its options, plays wilds late).
7
+ // line a board `size` [columns, rows]; drop a token into a column; `inRow` in a row (across, up, or slanting)
8
+ // wins. The rival looks `rival` moves ahead (0: anywhere it can, 1, 2, 3 …). A full board is a draw: lost.
9
+ //
10
+ // Turn by turn: play(i[, color]), draw() for shed; drop(column) for line. The rivals answer at once.
11
+
12
+ import { createSim } from '@ozsarman/clarityjs/sim';
13
+ import { clamp, settingsFor, hooked } from './common.js';
14
+
15
+ export const kit = {
16
+ name: 'card-board',
17
+ title: 'Cards and boards',
18
+ describe: 'Turns, a hand of cards or a board of tokens, and a rival that thinks: shed your hand first, or line up your tokens first.',
19
+ goals: ['shed', 'line'],
20
+ settings: {},
21
+ level: {
22
+ shed: { colors: 4, ranks: 8, hand: 6, rivals: 1, rival: 1, wilds: 2 },
23
+ line: { size: [7, 6], inRow: 4, rival: 2 },
24
+ },
25
+ examples: ['A card game of sea charts: match the colour or the number, empty your hand first', 'Four in a row with lanterns against a careful rival', 'A quick card duel in a tea house'],
26
+ input: ['tap', 'keys'],
27
+ continuous: false,
28
+ };
29
+
30
+ // ─── shed ────────────────────────────────────────────────────────────────────
31
+
32
+ function deal(level, rng) {
33
+ const colors = clamp(level.colors ?? 4, 2, 6), ranks = clamp(level.ranks ?? 8, 3, 12);
34
+ const deck = [];
35
+ for (let c = 0; c < colors; c++) for (let r = 1; r <= ranks; r++) deck.push({ c, r }, { c, r });
36
+ for (let i = 0; i < clamp(level.wilds ?? 2, 0, 8); i++) deck.push({ c: -1, r: 0 });
37
+ rng.shuffle(deck);
38
+ const hand = clamp(level.hand ?? 6, 2, 12), rivals = clamp(level.rivals ?? 1, 1, 3);
39
+ const hands = Array.from({ length: rivals + 1 }, (_, p) => deck.splice(0, hand + (p > 0 ? clamp(level.extra ?? 0, -3, 4) : 0)));
40
+ let top = deck.findIndex((k) => k.c >= 0);
41
+ const pile = [deck.splice(top, 1)[0]];
42
+ return { colors, ranks, deck, hands, pile, color: pile[0].c, turn: 0, rival: clamp(level.rival ?? 1, 0, 2), passes: 0 };
43
+ }
44
+
45
+ const fits = (g, k) => k.c < 0 || k.c === g.color || k.r === g.pile[g.pile.length - 1].r;
46
+
47
+ function drawCard(g, rng) {
48
+ if (!g.deck.length) { const keep = g.pile.pop(); g.deck = rng.shuffle(g.pile); g.pile = [keep]; }
49
+ return g.deck.pop() ?? null;
50
+ }
51
+
52
+ /** A rival's turn: by its level, the card it plays (or a draw). */
53
+ function rivalShed(g, p, rng) {
54
+ const hand = g.hands[p], ok = hand.map((k, i) => (fits(g, k) ? i : -1)).filter((i) => i >= 0);
55
+ if (!ok.length) { const k = drawCard(g, rng); if (k) { hand.push(k); if (fits(g, k) && g.rival > 0) return playShed(g, p, hand.length - 1, mostColor(hand, g)); } return null; }
56
+ let i = g.rival === 0 ? rng.pick(ok) : bestShed(g, hand, ok, g.rival);
57
+ return playShed(g, p, i, mostColor(hand, g));
58
+ }
59
+
60
+ function mostColor(hand, g) { const n = new Array(g.colors).fill(0); for (const k of hand) if (k.c >= 0) n[k.c]++; return n.indexOf(Math.max(...n)); }
61
+
62
+ /** The card that keeps most options: one of the colour held most, wilds last (level 2 also saves them). */
63
+ function bestShed(g, hand, ok, level) {
64
+ const n = new Array(g.colors).fill(0); for (const k of hand) if (k.c >= 0) n[k.c]++;
65
+ let best = ok[0], bv = -Infinity;
66
+ for (const i of ok) {
67
+ const k = hand[i];
68
+ let v = k.c < 0 ? (level >= 2 ? -5 : -1) : n[k.c] + (hand.some((o, j) => j !== i && o.r === k.r) ? 0.5 : 0) + k.r * 0.01;
69
+ if (v > bv) { bv = v; best = i; }
70
+ }
71
+ return best;
72
+ }
73
+
74
+ function playShed(g, p, i, color) {
75
+ const [k] = g.hands[p].splice(i, 1);
76
+ g.pile.push(k);
77
+ g.color = k.c < 0 ? clamp(color ?? 0, 0, g.colors - 1) : k.c;
78
+ return k;
79
+ }
80
+
81
+ // ─── line ────────────────────────────────────────────────────────────────────
82
+
83
+ function lineSetup(level) {
84
+ const [w, h] = level.size ?? [7, 6];
85
+ return { w: clamp(w, 4, 10), h: clamp(h, 4, 10), inRow: clamp(level.inRow ?? 4, 3, 6), cells: new Array(clamp(w, 4, 10) * clamp(h, 4, 10)).fill(0), rival: clamp(level.rival ?? 2, 0, 5), last: -1 };
86
+ }
87
+
88
+ const colFree = (b, x) => b.cells[x] === 0;
89
+ function dropIn(b, x, who) { for (let y = b.h - 1; y >= 0; y--) if (b.cells[y * b.w + x] === 0) { b.cells[y * b.w + x] = who; b.last = y * b.w + x; return y; } return -1; }
90
+ function undrop(b, x) { for (let y = 0; y < b.h; y++) if (b.cells[y * b.w + x] !== 0) { b.cells[y * b.w + x] = 0; return; } }
91
+
92
+ function winner(b) {
93
+ const { w, h, cells, inRow } = b;
94
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
95
+ const v = cells[y * w + x]; if (!v) continue;
96
+ for (const [dx, dy] of [[1, 0], [0, 1], [1, 1], [1, -1]]) {
97
+ let k = 1; while (k < inRow) { const nx = x + dx * k, ny = y + dy * k; if (nx < 0 || ny < 0 || nx >= w || ny >= h || cells[ny * w + nx] !== v) break; k++; }
98
+ if (k >= inRow) return v;
99
+ }
100
+ }
101
+ return cells.every((v) => v) ? 3 : 0;
102
+ }
103
+
104
+ /** How good the board is for `who`: open runs of two and three, weighted, minus the other side's. */
105
+ function judge(b, who) {
106
+ const { w, h, cells, inRow } = b; let score = 0;
107
+ for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) for (const [dx, dy] of [[1, 0], [0, 1], [1, 1], [1, -1]]) {
108
+ let mine = 0, theirs = 0, ok = true;
109
+ for (let k = 0; k < inRow; k++) { const nx = x + dx * k, ny = y + dy * k; if (nx < 0 || ny < 0 || nx >= w || ny >= h) { ok = false; break; } const v = cells[ny * w + nx]; if (v === who) mine++; else if (v) theirs++; }
110
+ if (!ok || (mine && theirs)) continue;
111
+ score += [0, 1, 6, 40, 400, 4000][mine] - [0, 1, 7, 50, 500, 5000][theirs];
112
+ }
113
+ for (let y = 0; y < h; y++) if (cells[y * w + (w >> 1)] === who) score += 3;
114
+ return score;
115
+ }
116
+
117
+ /** Look `depth` moves ahead (alpha-beta), centre columns first. → { col, v } */
118
+ function minimax(b, depth, who, alpha = -Infinity, beta = Infinity) {
119
+ const win = winner(b), other = who === 1 ? 2 : 1;
120
+ if (win === who) return { v: 1e6 + depth }; if (win === other) return { v: -1e6 - depth }; if (win === 3) return { v: 0 };
121
+ if (depth === 0) return { v: judge(b, who) };
122
+ const order = [...Array(b.w).keys()].sort((a, c) => Math.abs(a - (b.w - 1) / 2) - Math.abs(c - (b.w - 1) / 2));
123
+ let best = { col: order.find((x) => colFree(b, x)) ?? 0, v: -Infinity };
124
+ for (const x of order) {
125
+ if (!colFree(b, x)) continue;
126
+ dropIn(b, x, who);
127
+ const v = -minimax(b, depth - 1, other, -beta, -alpha).v;
128
+ undrop(b, x);
129
+ if (v > best.v) best = { col: x, v };
130
+ alpha = Math.max(alpha, v); if (alpha >= beta) break;
131
+ }
132
+ return best;
133
+ }
134
+
135
+ function rivalLine(b, rng) {
136
+ const free = [...Array(b.w).keys()].filter((x) => colFree(b, x));
137
+ if (!free.length) return -1;
138
+ let x = rng.pick(free);
139
+ if (b.rival > 0) {
140
+ // the best moves by its look ahead; among those about as good, one by chance (so games differ)
141
+ const scored = free.map((c) => { dropIn(b, c, 2); const v = winner(b) === 2 ? 1e7 : -minimax(b, b.rival - 1, 1).v; undrop(b, c); return { c, v }; });
142
+ const top = Math.max(...scored.map((m) => m.v));
143
+ x = rng.pick(scored.filter((m) => m.v >= top - Math.max(5, Math.abs(top) * 0.05)).map((m) => m.c));
144
+ }
145
+ dropIn(b, x, 2);
146
+ return x;
147
+ }
148
+
149
+ // ─── the game ────────────────────────────────────────────────────────────────
150
+
151
+ function setup(level, rng) {
152
+ const goal = level.goal ?? 'shed';
153
+ const base = { ...kit.level[goal], ...level };
154
+ const s = { goal, won: false, lost: false, used: 0, score: 0, t: 0, deaths: [] };
155
+ if (goal === 'line') Object.assign(s, { board: lineSetup(base) });
156
+ else Object.assign(s, { cards: deal(base, rng) });
157
+ return s;
158
+ }
159
+
160
+ function end(s, ctx) {
161
+ if (s.goal === 'line') {
162
+ const w = winner(s.board);
163
+ if (w === 1) { s.won = true; s.score = 1000 - s.used * 20; ctx.emit({ type: 'won' }); }
164
+ else if (w === 2) { s.lost = true; ctx.emit({ type: 'lost', why: 'rival' }); }
165
+ else if (w === 3) { s.lost = true; ctx.emit({ type: 'lost', why: 'draw' }); }
166
+ return;
167
+ }
168
+ const g = s.cards;
169
+ if (!g.hands[0].length) { s.won = true; s.score = 1000 - s.used * 10 + g.hands.slice(1).reduce((n, h) => n + h.length * 20, 0); ctx.emit({ type: 'won' }); }
170
+ else if (g.hands.slice(1).some((h) => !h.length)) { s.lost = true; ctx.emit({ type: 'lost', why: 'rival' }); }
171
+ else if (g.passes > 12) { s.lost = true; ctx.emit({ type: 'lost', why: 'stuck' }); }
172
+ }
173
+
174
+ function rivalsAnswer(s, ctx) {
175
+ if (s.won || s.lost) return;
176
+ if (s.goal === 'line') { const x = rivalLine(s.board, ctx.rng); ctx.emit({ type: 'rival', col: x }); end(s, ctx); return; }
177
+ const g = s.cards;
178
+ for (let p = 1; p < g.hands.length && !s.won && !s.lost; p++) {
179
+ const k = rivalShed(g, p, ctx.rng);
180
+ g.passes = k ? 0 : g.passes + 1;
181
+ ctx.emit({ type: 'rival', player: p, card: k });
182
+ end(s, ctx);
183
+ }
184
+ }
185
+
186
+ const ACTIONS = {
187
+ /** shed: play the i-th card of your hand (a wild names a colour). */
188
+ play(s, ctx, i, color) {
189
+ if (s.goal !== 'shed' || s.won || s.lost) return false;
190
+ const g = s.cards, k = g.hands[0][i];
191
+ if (!k || !fits(g, k)) return false;
192
+ playShed(g, 0, i, color ?? mostColor(g.hands[0].filter((_, j) => j !== i), g));
193
+ s.used++; g.passes = 0; ctx.emit({ type: 'play', card: k });
194
+ end(s, ctx); rivalsAnswer(s, ctx);
195
+ return true;
196
+ },
197
+ /** shed: draw a card (and the turn passes). */
198
+ draw(s, ctx) {
199
+ if (s.goal !== 'shed' || s.won || s.lost) return false;
200
+ const k = drawCard(s.cards, ctx.rng); if (k) s.cards.hands[0].push(k);
201
+ s.used++; s.cards.passes++; ctx.emit({ type: 'draw' });
202
+ rivalsAnswer(s, ctx);
203
+ return true;
204
+ },
205
+ /** line: drop a token into a column (0 is the left). */
206
+ drop(s, ctx, col) {
207
+ if (s.goal !== 'line' || s.won || s.lost) return false;
208
+ const b = s.board, x = Math.round(col);
209
+ if (x < 0 || x >= b.w || !colFree(b, x)) return false;
210
+ dropIn(b, x, 1); s.used++; ctx.emit({ type: 'drop', col: x });
211
+ end(s, ctx); rivalsAnswer(s, ctx);
212
+ return true;
213
+ },
214
+ };
215
+
216
+ function legal(s) {
217
+ if (s.won || s.lost) return [];
218
+ if (s.goal === 'line') return [...Array(s.board.w).keys()].filter((x) => colFree(s.board, x)).map((x) => ({ act: 'drop', args: [x] }));
219
+ const g = s.cards, out = g.hands[0].map((k, i) => (fits(g, k) ? { act: 'play', args: [i] } : null)).filter(Boolean);
220
+ return [...out, { act: 'draw', args: [] }];
221
+ }
222
+
223
+ function value(s) {
224
+ if (s.won) return 1e6 - s.used;
225
+ if (s.lost) return -1e6;
226
+ if (s.goal === 'line') return judge(s.board, 1);
227
+ const g = s.cards; return -g.hands[0].length * 10 + Math.min(...g.hands.slice(1).map((h) => h.length)) * 4;
228
+ }
229
+
230
+ export const bots = {
231
+ random(sim, rng) { const l = sim.legal(); return l.length ? rng.pick(l) : null; },
232
+ greedy(sim, rng) {
233
+ const s = sim.state;
234
+ if (s.goal === 'line') { const b = s.board; const free = [...Array(b.w).keys()].filter((x) => colFree(b, x)); let best = free[0], bv = -Infinity; for (const x of free) { dropIn(b, x, 1); const v = winner(b) === 1 ? 1e9 : judge(b, 1); undrop(b, x); if (v > bv) { bv = v; best = x; } } return { act: 'drop', args: [best] }; }
235
+ const g = s.cards, ok = g.hands[0].map((k, i) => (fits(g, k) ? i : -1)).filter((i) => i >= 0);
236
+ return ok.length ? { act: 'play', args: [ok[0]] } : { act: 'draw', args: [] };
237
+ },
238
+ planner(sim) {
239
+ const s = sim.state;
240
+ if (s.goal === 'line') return { act: 'drop', args: [minimax(s.board, Math.max(5, s.board.rival + 3), 1).col] };
241
+ const g = s.cards, hand = g.hands[0], ok = hand.map((k, i) => (fits(g, k) ? i : -1)).filter((i) => i >= 0);
242
+ if (!ok.length) return { act: 'draw', args: [] };
243
+ if (ok.length === 1 && hand[ok[0]].c >= 0) return { act: 'play', args: [ok[0]] };
244
+ // each card it could play (a wild once for each colour), played out a few times to the end by both sides
245
+ // with the deck shuffled anew each time: the move that wins most
246
+ const cands = [];
247
+ for (const i of ok) { if (hand[i].c < 0) for (let c = 0; c < g.colors; c++) cands.push([i, c]); else cands.push([i, hand[i].c]); }
248
+ let best = -Infinity, pick = cands[0];
249
+ for (const m of cands) {
250
+ let v = 0;
251
+ for (let k = 0; k < 6; k++) {
252
+ const snap = sim.snapshot(), n = sim.log.length;
253
+ sim.rng.state = (snap.rng ^ Math.imul(k + 1, 0x9E3779B1)) | 0;
254
+ sim.act('play', ...m);
255
+ for (let turn = 0; turn < 60 && !sim.state.won && !sim.state.lost; turn++) {
256
+ const gg = sim.state.cards, hh = gg.hands[0], oo = hh.map((c, j) => (fits(gg, c) ? j : -1)).filter((j) => j >= 0);
257
+ if (oo.length) { const j = bestShed(gg, hh, oo, 2); sim.act('play', j, mostColor(hh.filter((_, q) => q !== j), gg)); } else sim.act('draw');
258
+ }
259
+ v += sim.state.won ? 1 : sim.state.lost ? 0 : 0.5;
260
+ v -= sim.state.cards.hands[0].length * 0.001;
261
+ sim.restore(snap); sim.log.length = n;
262
+ }
263
+ if (v > best) { best = v; pick = m; }
264
+ }
265
+ return { act: 'play', args: pick };
266
+ },
267
+ };
268
+
269
+ export function create({ game, level, seed = 1, hooks = {} }) {
270
+ const h = hooked(hooks, ACTIONS);
271
+ const sim = createSim({
272
+ seed,
273
+ setup: (ctx) => { const s = setup(level, ctx.rng); hooks.setup?.(s, ctx, level); return s; },
274
+ step: (s, dt, ctx) => { s.t += dt; hooks.step?.(s, dt, ctx); h.end(s, ctx); },
275
+ actions: h.actions,
276
+ report: (s) => {
277
+ const r = { goal: s.goal, won: s.won, lost: s.lost, used: s.used, score: hooks.score ? hooks.score(s) : s.score };
278
+ if (s.goal === 'line') Object.assign(r, { w: s.board.w, h: s.board.h, cells: [...s.board.cells], inRow: s.board.inRow, last: s.board.last });
279
+ else Object.assign(r, { hand: s.cards.hands[0].map((k) => ({ ...k })), rivals: s.cards.hands.slice(1).map((x) => x.length), top: { ...s.cards.pile[s.cards.pile.length - 1] }, color: s.cards.color, colors: s.cards.colors, deck: s.cards.deck.length });
280
+ return r;
281
+ },
282
+ });
283
+ sim.kit = kit; sim.bots = bots;
284
+ sim.legal = () => (hooks.legal ? hooks.legal(sim.state) : legal(sim.state));
285
+ sim.value = () => (hooks.value ? hooks.value(sim.state) : value(sim.state));
286
+ void settingsFor;
287
+ return sim;
288
+ }
289
+
290
+ /** Easier versions of a level, the smallest change first (for play()'s fixes). */
291
+ export function easier(lv) {
292
+ const out = [];
293
+ if ((lv.goal ?? 'shed') === 'line') { for (const r of [1, 2]) if ((lv.rival ?? 2) - r >= 0) out.push({ change: { rival: (lv.rival ?? 2) - r }, say: `the rival looks ${(lv.rival ?? 2) - r} moves ahead` }); return out; }
294
+ for (const e of [1, 2, 3]) out.push({ change: { extra: (lv.extra ?? 0) + e }, say: `rivals start with ${(lv.extra ?? 0) + e} cards more` });
295
+ if ((lv.rival ?? 1) > 0) out.push({ change: { rival: (lv.rival ?? 1) - 1 }, say: `a rival of level ${(lv.rival ?? 1) - 1}` });
296
+ return out;
297
+ }
298
+ export function harder(lv) {
299
+ if ((lv.goal ?? 'shed') === 'line') return (lv.rival ?? 2) < 5 ? [{ change: { rival: (lv.rival ?? 2) + 1 }, say: `the rival looks ${(lv.rival ?? 2) + 1} moves ahead` }] : [];
300
+ const out = [];
301
+ if ((lv.extra ?? 0) > -3) out.push({ change: { extra: (lv.extra ?? 0) - 1 }, say: `rivals start with ${(lv.extra ?? 0) - 1} cards more` });
302
+ if ((lv.rival ?? 1) < 2) out.push({ change: { rival: (lv.rival ?? 1) + 1 }, say: `a rival of level ${(lv.rival ?? 1) + 1}` });
303
+ return out;
304
+ }