@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/index.js
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
1
|
+
// @clarity-js/engine — a game engine for AI agents: one sentence → a game that is played and measured before it
|
|
2
|
+
// is handed over. A game is game.json (plain data: the kit, the look, the levels, the checks) and rules.js (the
|
|
3
|
+
// kit's hooks, changed where the game differs). Kits: puzzle-grid, platformer, top-down, shmup, racing, card-board,
|
|
4
|
+
// explore-3d and physics-toy; "blank" for rules of your own.
|
|
5
|
+
//
|
|
6
|
+
// import { newGame, loadGame, play, fit } from '@clarity-js/engine'
|
|
7
|
+
// const { game, rules } = newGame({ pitch: 'A calm marbling puzzle for one finger' })
|
|
8
|
+
// const report = play(loadGame(game)) // bots play every level: finish rate, time, deaths, the checks
|
|
9
|
+
// const better = fit(game) // play, change what fails (moves, a level), play again
|
|
10
|
+
|
|
11
|
+
import * as grid from './grid.js';
|
|
12
|
+
import * as platformer from './platformer.js';
|
|
13
|
+
import * as topdown from './topdown.js';
|
|
14
|
+
import * as shmup from './shmup.js';
|
|
15
|
+
import * as racing from './racing.js';
|
|
16
|
+
import * as cardboard from './cardboard.js';
|
|
17
|
+
import * as explore from './explore.js';
|
|
18
|
+
import * as physicstoy from './physicstoy.js';
|
|
19
|
+
import { runBot, BOTS } from './bots.js';
|
|
20
|
+
import { validateGame, parseFinish } from './validate.js';
|
|
21
|
+
import { createSim } from '@ozsarman/clarityjs/sim';
|
|
22
|
+
|
|
23
|
+
export { validateGame, jsonPlaces, KITS, STYLES } from './validate.js';
|
|
24
|
+
export { createArt, checkArt, ART_ROLES } from './art.js';
|
|
25
|
+
export { newGame, readPitch, titleOf, levelsFor, platformerLevel, pushLevel, pushLevelWith, tuneRace, tuneShed, LOOKS, lookOf } from './make.js';
|
|
26
|
+
export { topdownLevel } from './topdown.js';
|
|
27
|
+
export { shmupLevel } from './shmup.js';
|
|
28
|
+
export { trackPoints, buildTrack, bestLap } from './racing.js';
|
|
29
|
+
export { exploreLevel } from './explore.js';
|
|
30
|
+
export { toppleLevel, stackLevel } from './physicstoy.js';
|
|
31
|
+
export { compose, createSound, renderMusic, moodOf, MOODS, EFFECTS, EVENT_SOUNDS } from './sound.js';
|
|
32
|
+
export { runBot, BOTS } from './bots.js';
|
|
33
|
+
export { solveLights, search } from './grid.js';
|
|
34
|
+
|
|
35
|
+
const blank = {
|
|
36
|
+
kit: { name: 'blank', title: 'Rules of your own', describe: 'No kit: setup, step, actions and won/lost are all in rules.js.', settings: {}, examples: [], input: [], continuous: false },
|
|
37
|
+
create({ level, seed, hooks }) {
|
|
38
|
+
const sim = createSim({ seed, setup: (ctx) => ({ won: false, lost: false, score: 0, ...(hooks.setup?.({}, ctx, level) ?? {}) }), step: (s, dt, ctx) => { hooks.step?.(s, dt, ctx); if (!s.won && hooks.won?.(s)) s.won = true; if (!s.lost && hooks.lost?.(s)) s.lost = true; }, actions: hooks.actions ?? {}, report: hooks.report });
|
|
39
|
+
sim.kit = blank.kit; sim.legal = () => hooks.legal?.(sim.state) ?? []; sim.value = () => hooks.value?.(sim.state) ?? (sim.state.score ?? 0);
|
|
40
|
+
return sim;
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
|
|
44
|
+
const KIT_MODULES = { 'puzzle-grid': grid, platformer, 'top-down': topdown, shmup, racing, 'card-board': cardboard, 'explore-3d': explore, 'physics-toy': physicstoy, blank };
|
|
45
|
+
|
|
46
|
+
/** The kits, as cards: name, what it gives, its settings and goals, example pitches. */
|
|
47
|
+
export function kits() {
|
|
48
|
+
return Object.values(KIT_MODULES).map((m) => ({ name: m.kit.name, title: m.kit.title, describe: m.kit.describe, settings: m.kit.settings, goals: m.kit.goals, level: m.kit.level, examples: m.kit.examples, input: m.kit.input }));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* A game ready to play: its kit, and make(levelIndex, seed) → a simulation.
|
|
53
|
+
* @param {object|string} game game.json (an object, or its text)
|
|
54
|
+
* @param {object} [rules] what rules.js exports by default (its hooks)
|
|
55
|
+
*/
|
|
56
|
+
export function loadGame(game, rules = {}) {
|
|
57
|
+
const v = validateGame(game);
|
|
58
|
+
if (!v.ok) { const e = new Error('game.json: ' + v.errors.map((x) => `${x.path || '(top)'}${x.line ? ` (line ${x.line})` : ''}: ${x.message}${x.fix ? ` — ${x.fix}` : ''}`).join('; ')); e.errors = v.errors; throw e; }
|
|
59
|
+
const g = v.game, mod = KIT_MODULES[g.kit];
|
|
60
|
+
const levels = g.levels?.length ? g.levels : [{}];
|
|
61
|
+
return {
|
|
62
|
+
game: g, kit: mod.kit, rules, levels,
|
|
63
|
+
make: (level = 0, seed = 1) => mod.create({ game: g, level: levels[level], seed, hooks: rules }),
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/**
|
|
68
|
+
* Bots play every level, a few seeds each, and the game's checks are said to pass or fail, each with why and,
|
|
69
|
+
* where it can be found, the change that would make it pass.
|
|
70
|
+
* @param {ReturnType<typeof loadGame>} loaded
|
|
71
|
+
* @param {{ seeds?: number, bots?: string[], seconds?: number, turns?: number, fixes?: boolean }} [options]
|
|
72
|
+
*/
|
|
73
|
+
export function play(loaded, { seeds = 6, bots, seconds = 120, turns = 400, fixes = true } = {}) {
|
|
74
|
+
const g = loaded.game;
|
|
75
|
+
const use = bots ?? g.checks?.bots ?? BOTS;
|
|
76
|
+
const want = parseFinish(g.checks?.finish ?? '>= 0.7') ?? 0.7;
|
|
77
|
+
seeds = Math.min(seeds, loaded.kit.maxSeeds ?? seeds);
|
|
78
|
+
const levels = loaded.levels.map((lv, i) => {
|
|
79
|
+
const out = { id: lv.id ?? `l${i + 1}`, bots: {}, deaths: [] };
|
|
80
|
+
for (const bot of use) {
|
|
81
|
+
const runs = [];
|
|
82
|
+
for (let s = 1; s <= seeds; s++) runs.push(runBot((seed) => loaded.make(i, seed), { bot, seed: s, seconds, turns }));
|
|
83
|
+
const won = runs.filter((r) => r.won);
|
|
84
|
+
out.bots[bot] = {
|
|
85
|
+
rate: round(won.length / runs.length), games: runs.length,
|
|
86
|
+
time: won.length && loaded.kit.continuous ? round(median(won.map((r) => r.t))) : null,
|
|
87
|
+
moves: won.length ? Math.round(median(won.map((r) => r.moves))) : null,
|
|
88
|
+
score: round(median(runs.map((r) => r.score ?? 0))),
|
|
89
|
+
errors: [...new Set(runs.filter((r) => r.error).map((r) => r.error))],
|
|
90
|
+
};
|
|
91
|
+
if (bot === 'planner' || bot === use[use.length - 1]) out.deaths.push(...runs.flatMap((r) => r.deaths ?? []));
|
|
92
|
+
}
|
|
93
|
+
return out;
|
|
94
|
+
});
|
|
95
|
+
const checks = [];
|
|
96
|
+
const plannerOf = (l) => l.bots.planner ?? l.bots[use[use.length - 1]];
|
|
97
|
+
const errorsAll = levels.flatMap((l) => Object.values(l.bots).flatMap((b) => b.errors.map((e) => `${l.id}: ${e}`)));
|
|
98
|
+
checks.push({ name: 'starts and does not break', pass: !errorsAll.length, value: errorsAll.length, why: errorsAll.length ? errorsAll.slice(0, 5).join('; ') : 'every bot played every level to its end' });
|
|
99
|
+
for (const l of levels) {
|
|
100
|
+
const p = plannerOf(l);
|
|
101
|
+
const c = { name: `${l.id} can be finished`, pass: p.rate >= want, value: p.rate, want, why: `the planner finished ${Math.round(p.rate * 100)}% of ${p.games} games` };
|
|
102
|
+
if (!c.pass && fixes) c.fix = suggest(loaded, loaded.levels.findIndex((x, i) => (x.id ?? `l${i + 1}`) === l.id), want, { seeds, seconds, turns });
|
|
103
|
+
checks.push(c);
|
|
104
|
+
}
|
|
105
|
+
if (levels.length > 1) {
|
|
106
|
+
const rates = levels.map((l) => plannerOf(l).rate), times = levels.map((l) => plannerOf(l).time ?? plannerOf(l).moves ?? 0);
|
|
107
|
+
const harder = times.every((t, i) => i === 0 || t >= times[i - 1] * 0.8) || rates.every((r, i) => i === 0 || r <= rates[i - 1] + 0.01);
|
|
108
|
+
checks.push({ name: 'gets harder', pass: harder, value: times, why: harder ? 'later levels take as long or longer' : 'a later level is much quicker than the one before it: reorder them', soft: true });
|
|
109
|
+
}
|
|
110
|
+
const r0 = levels[0]?.bots.random;
|
|
111
|
+
if (r0) checks.push({ name: 'not finished by chance', pass: r0.rate <= 0.9, value: r0.rate, why: r0.rate <= 0.9 ? 'random moves rarely finish the first level' : 'random moves finish the first level: there is nothing to think about', soft: true });
|
|
112
|
+
const ok = checks.every((c) => c.pass || c.soft);
|
|
113
|
+
return { title: g.title, kit: g.kit, ok, checks, levels };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
const round = (v) => (v == null ? null : Math.round(v * 100) / 100);
|
|
117
|
+
const median = (l) => { const s = [...l].sort((a, b) => a - b); return s.length ? (s.length % 2 ? s[s.length >> 1] : (s[(s.length >> 1) - 1] + s[s.length >> 1]) / 2) : 0; };
|
|
118
|
+
|
|
119
|
+
function rateWith(loaded, i, level, { seeds, seconds, turns }) {
|
|
120
|
+
const levels = loaded.levels.map((l, k) => (k === i ? level : l));
|
|
121
|
+
const tmp = { ...loaded, levels, make: (lv = 0, seed = 1) => KIT_MODULES[loaded.game.kit].create({ game: loaded.game, level: levels[lv], seed, hooks: loaded.rules }) };
|
|
122
|
+
let won = 0;
|
|
123
|
+
for (let s = 1; s <= seeds; s++) if (runBot((seed) => tmp.make(i, seed), { bot: 'planner', seed: s, seconds, turns }).won) won++;
|
|
124
|
+
return won / seeds;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** The smallest change to a level that lets the planner finish it often enough: more moves, a lower target, more time. */
|
|
128
|
+
function suggest(loaded, i, want, opts) {
|
|
129
|
+
const lv = loaded.levels[i];
|
|
130
|
+
if (loaded.game.kit === 'puzzle-grid') {
|
|
131
|
+
if (lv.goal === 'match' || lv.goal == null) {
|
|
132
|
+
for (const f of [0.8, 0.65, 0.5]) { const target = Math.round(((lv.target ?? 600) * f) / 10) * 10; const r = rateWith(loaded, i, { ...lv, target }, opts); if (r >= want) return { change: { target }, rate: round(r), say: `target ${lv.target} → ${target} gives ${Math.round(r * 100)}%` }; }
|
|
133
|
+
}
|
|
134
|
+
if (lv.moves) for (const f of [1.25, 1.5, 2, 3]) { const moves = Math.ceil(lv.moves * f); const r = rateWith(loaded, i, { ...lv, moves }, opts); if (r >= want) return { change: { moves }, rate: round(r), say: `moves ${lv.moves} → ${moves} gives ${Math.round(r * 100)}%` }; }
|
|
135
|
+
if (lv.shuffle) for (const f of [0.75, 0.5]) { const shuffle = Math.max(4, Math.round(lv.shuffle * f)); const r = rateWith(loaded, i, { ...lv, shuffle }, opts); if (r >= want) return { change: { shuffle }, rate: round(r), say: `shuffle ${lv.shuffle} → ${shuffle} gives ${Math.round(r * 100)}%` }; }
|
|
136
|
+
if (lv.presses) { const presses = Math.max(1, Math.round(lv.presses / 2)); const r = rateWith(loaded, i, { ...lv, presses }, opts); if (r >= want) return { change: { presses }, rate: round(r), say: `presses ${lv.presses} → ${presses} gives ${Math.round(r * 100)}%` }; }
|
|
137
|
+
}
|
|
138
|
+
if (loaded.game.kit === 'platformer') {
|
|
139
|
+
if (lv.time) { const time = Math.round(lv.time * 1.5); const r = rateWith(loaded, i, { ...lv, time }, opts); if (r >= want) return { change: { time }, rate: round(r), say: `time ${lv.time} → ${time} s gives ${Math.round(r * 100)}%` }; }
|
|
140
|
+
const map = lv.map.map((row) => row.replace(/E/g, ' ').replace(/\^/g, ' '));
|
|
141
|
+
const r = rateWith(loaded, i, { ...lv, map }, opts);
|
|
142
|
+
if (r >= want) return { change: { map }, rate: round(r), say: `without its walkers and spikes it gives ${Math.round(r * 100)}%` };
|
|
143
|
+
}
|
|
144
|
+
for (const c of KIT_MODULES[loaded.game.kit].easier?.(lv) ?? []) {
|
|
145
|
+
const r = rateWith(loaded, i, { ...lv, ...c.change }, opts);
|
|
146
|
+
if (r >= want) return { change: c.change, rate: round(r), say: `${c.say} gives ${Math.round(r * 100)}%` };
|
|
147
|
+
}
|
|
148
|
+
return { say: 'no small change found: make the level again (newGame with another pitch, or levelsFor)' };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** The changes that make a level easier or harder, smallest first, for its kit: [{ change, say }]. */
|
|
152
|
+
export function levelChanges(game, level, way = 'easier') {
|
|
153
|
+
const mod = KIT_MODULES[typeof game === 'string' ? game : game.kit];
|
|
154
|
+
return (way === 'harder' ? mod?.harder : mod?.easier)?.(level) ?? [];
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Play the game and apply the fixes play() finds, round after round, until every check passes (or `rounds` are
|
|
159
|
+
* spent). → { game, report, rounds: [{ fixed: [...] }] }
|
|
160
|
+
*/
|
|
161
|
+
export function fit(game, rules = {}, { rounds = 4, ...options } = {}) {
|
|
162
|
+
let g = JSON.parse(JSON.stringify(typeof game === 'string' ? JSON.parse(game) : game));
|
|
163
|
+
const log = [];
|
|
164
|
+
for (let n = 0; n < rounds; n++) {
|
|
165
|
+
const report = play(loadGame(g, rules), options);
|
|
166
|
+
const fixes = report.checks.filter((c) => !c.pass && c.fix?.change);
|
|
167
|
+
if (report.ok || !fixes.length) return { game: g, report, rounds: log };
|
|
168
|
+
for (const c of fixes) {
|
|
169
|
+
const id = c.name.replace(/ can be finished$/, '');
|
|
170
|
+
const i = g.levels.findIndex((l, k) => (l.id ?? `l${k + 1}`) === id);
|
|
171
|
+
if (i >= 0) g.levels[i] = { ...g.levels[i], ...c.fix.change };
|
|
172
|
+
}
|
|
173
|
+
log.push({ fixed: fixes.map((c) => `${c.name.replace(/ can be finished$/, '')}: ${c.fix.say}`) });
|
|
174
|
+
}
|
|
175
|
+
return { game: g, report: play(loadGame(g, rules), options), rounds: log };
|
|
176
|
+
}
|
package/src/make.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
// @clarity-js/engine — from a pitch to a first game: the kit, the look, the feel and levels made by the seed of
|
|
2
|
+
// the pitch, each checked by a bot before it is kept (a level the planner cannot finish is made again, easier).
|
|
3
|
+
|
|
4
|
+
import { createRng } from '@ozsarman/clarityjs/sim';
|
|
5
|
+
import { create as createGrid, search } from './grid.js';
|
|
6
|
+
import { runBot } from './bots.js';
|
|
7
|
+
import { topdownLevel } from './topdown.js';
|
|
8
|
+
import { shmupLevel } from './shmup.js';
|
|
9
|
+
import { create as createRacing, trackPoints } from './racing.js';
|
|
10
|
+
import { create as createCards } from './cardboard.js';
|
|
11
|
+
import { exploreLevel } from './explore.js';
|
|
12
|
+
import { toppleLevel, stackLevel } from './physicstoy.js';
|
|
13
|
+
|
|
14
|
+
/**
|
|
15
|
+
* Looks, as recipes: a palette, a background and an ink, and how a shape is finished — its corners (radius, a
|
|
16
|
+
* share of its size), a glow, a gloss (the light along its top), an outline, a pattern (marble, hatch, bevel) and,
|
|
17
|
+
* for 3D, how much the sides are shaded. A game.json's look can change any of them: { "style": "pastel",
|
|
18
|
+
* "radius": 0.4, "glow": 0.2 }.
|
|
19
|
+
*/
|
|
20
|
+
export const LOOKS = {
|
|
21
|
+
'paper-marbling': { palette: ['#1d3557', '#e63946', '#f1faee', '#a8dadc', '#457b9d', '#f4a261'], background: '#f6efe4', ink: '#1d3557', radius: 0.18, glow: 0, gloss: 0, outline: 0, pattern: 'marble', shade: 0.2 },
|
|
22
|
+
pixel: { palette: ['#2b2d42', '#ef233c', '#8d99ae', '#edf2f4', '#ffb703', '#219ebc'], background: '#1b1c2b', ink: '#edf2f4', radius: 0, glow: 0, gloss: 0, outline: 0, pattern: 'bevel', shade: 0.3 },
|
|
23
|
+
'neon-night': { palette: ['#0b0f2b', '#ff2e88', '#29f0ff', '#b8ff3c', '#ffd23f', '#9d4dff'], background: '#0b0f2b', ink: '#e6f7ff', radius: 0.18, glow: 0.4, gloss: 0, outline: 0, pattern: null, shade: 0.25 },
|
|
24
|
+
'ink-sketch': { palette: ['#222222', '#c1121f', '#f5f0e6', '#6c757d', '#8a6d3b', '#3d5a80'], background: '#f5f0e6', ink: '#222222', radius: 0.18, glow: 0, gloss: 0, outline: 0.5, pattern: 'hatch', shade: 0.15 },
|
|
25
|
+
'toy-plastic': { palette: ['#ff595e', '#ffca3a', '#8ac926', '#1982c4', '#6a4c93', '#ff924c'], background: '#fdf6e3', ink: '#2f2f2f', radius: 0.28, glow: 0, gloss: 0.35, outline: 0, pattern: null, shade: 0.2 },
|
|
26
|
+
pastel: { palette: ['#cdb4db', '#ffc8dd', '#ffafcc', '#bde0fe', '#a2d2ff', '#caffbf'], background: '#fffaf5', ink: '#4a4e69', radius: 0.18, glow: 0, gloss: 0.35, outline: 0, pattern: null, shade: 0.15 },
|
|
27
|
+
flat: { palette: ['#264653', '#2a9d8f', '#e9c46a', '#f4a261', '#e76f51', '#8ab17d'], background: '#f8f9fa', ink: '#264653', radius: 0.18, glow: 0, gloss: 0, outline: 0, pattern: null, shade: 0.2 },
|
|
28
|
+
'low-poly-diorama': { palette: ['#3a5a40', '#e07a5f', '#f2cc8f', '#81b29a', '#f4f1de', '#3d405b'], background: '#bcd4e6', ink: '#24303f', radius: 0.08, glow: 0, gloss: 0.12, outline: 0, pattern: null, shade: 0.3 },
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
/** A game's look: its style's recipe with what game.json changes. */
|
|
32
|
+
export function lookOf(game) {
|
|
33
|
+
const base = LOOKS[game?.look?.style] ?? LOOKS.flat, own = game?.look ?? {};
|
|
34
|
+
const out = { ...base };
|
|
35
|
+
for (const k of ['background', 'ink', 'pattern']) if (typeof own[k] === 'string' || own[k] === null) out[k] = own[k];
|
|
36
|
+
for (const k of ['radius', 'glow', 'gloss', 'outline', 'shade']) if (typeof own[k] === 'number' && Number.isFinite(own[k])) out[k] = Math.max(0, Math.min(k === 'radius' ? 0.5 : 1, own[k]));
|
|
37
|
+
out.palette = Array.isArray(own.palette) && own.palette.length ? own.palette : base.palette;
|
|
38
|
+
return out;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const has = (text, words) => words.some((w) => text.includes(w));
|
|
42
|
+
|
|
43
|
+
/** What a pitch asks for, read from its words (English and Turkish). */
|
|
44
|
+
export function readPitch(pitch) {
|
|
45
|
+
const t = ` ${String(pitch).toLowerCase()} `;
|
|
46
|
+
let kit = 'puzzle-grid', goal = 'match';
|
|
47
|
+
if (has(t, ['race', 'racing', 'racer', 'lap ', 'laps', 'circuit', 'drift', 'yarış', 'pist', 'rally', ' cars ', 'table track', 'go-kart'])) kit = 'racing';
|
|
48
|
+
else if (has(t, ['shoot', 'shmup', 'bullet', 'spaceship', 'space ship', ' ships', 'starfighter', 'dodge glowing', 'vertical scroll', 'planes', 'nebula', 'squadron', 'fighter', 'nişancı', 'uzay gemisi', 'gemileriyle'])) kit = 'shmup';
|
|
49
|
+
else if (has(t, ['card', 'deck', ' hand ', 'in a row', 'board game', 'tokens', 'tavla', 'kart oyunu', 'iskambil', 'dörtlü', 'duel'])) { kit = 'card-board'; goal = has(t, ['in a row', 'row of', 'tokens', 'board', 'dörtlü', 'sıra']) && !has(t, ['card', 'deck', 'kart']) ? 'line' : 'shed'; }
|
|
50
|
+
else if (has(t, ['stack', 'topple', 'knock', 'catapult', 'throw', 'tower', 'devir', 'kule', 'fırlat', 'yığ', 'tumble'])) { kit = 'physics-toy'; goal = has(t, ['stack', 'build', 'kule kur', 'yığ', ' kur', 'high without']) ? 'stack' : 'topple'; }
|
|
51
|
+
else if (has(t, ['explore', 'island', 'wander', 'scattered', 'stray', 'gather the', 'lost ', ' 3d', 'keşif', 'adada', 'ada ', 'kayıp'])) kit = 'explore-3d';
|
|
52
|
+
else if (has(t, ['dungeon', 'top-down', 'top down', 'twin-stick', 'maze', 'labyrinth', 'room by room', 'cellar', 'crawl', 'zindan', 'labirent', 'mahzen'])) kit = 'top-down';
|
|
53
|
+
else if (has(t, ['platform', 'jump', 'run ', 'runner', 'hop', 'leap', 'parkour', 'side-scroll', 'zıpla', 'koş', 'atla', 'rooftop', 'çatı'])) kit = 'platformer';
|
|
54
|
+
if (kit === 'puzzle-grid') {
|
|
55
|
+
if (has(t, ['push', 'crate', 'box', 'sokoban', 'warehouse', 'tray', 'kasa', 'kutu', 'it ', 'tepsi', 'depo'])) goal = 'push';
|
|
56
|
+
else if (has(t, ['light', 'lantern', 'lamp', 'switch', 'candle', 'star', 'ışık', 'fener', 'lamba', 'mum', 'yıldız'])) goal = 'lights';
|
|
57
|
+
else if (has(t, ['slide', 'tile', 'mosaic', 'sliding', 'kaydır', 'karo', 'mozaik', 'parça'])) goal = 'slide';
|
|
58
|
+
}
|
|
59
|
+
const style = has(t, ['marbl', 'ebru', 'ink tide', 'water colour', 'watercolor']) ? 'paper-marbling'
|
|
60
|
+
: has(t, ['diorama', 'low-poly', 'low poly']) || (kit === 'explore-3d' && !has(t, ['neon', 'night', 'pixel', 'ink', 'pastel', 'toy', 'gece'])) ? 'low-poly-diorama'
|
|
61
|
+
: has(t, ['neon', 'night', 'synth', 'cyber', 'gece']) ? 'neon-night'
|
|
62
|
+
: has(t, ['pixel', 'retro', '8-bit', '16-bit', 'piksel']) ? 'pixel'
|
|
63
|
+
: has(t, ['pastel', 'soft', 'cozy', 'cosy', 'yumuşak']) ? 'pastel'
|
|
64
|
+
: has(t, ['ink', 'sketch', 'pencil', 'mürekkep', 'karakalem']) ? 'ink-sketch'
|
|
65
|
+
: has(t, ['toy', 'plastic', 'candy', 'oyuncak', 'şeker', 'bright']) ? 'toy-plastic' : 'flat';
|
|
66
|
+
const pace = has(t, ['calm', 'relax', 'zen', 'slow', 'sakin', 'huzur']) ? 'calm' : has(t, ['fast', 'frantic', 'speed', 'hızlı', 'rush']) ? 'fast' : 'steady';
|
|
67
|
+
const phone = has(t, ['phone', 'mobile', 'one finger', 'tap', 'telefon', 'tek parmak', 'dokun']);
|
|
68
|
+
const hard = has(t, ['hard', 'tough', 'challeng', 'zor', 'brutal']) ? 1 : pace === 'calm' ? -1 : 0;
|
|
69
|
+
return { kit, goal, style, pace, phone, hard };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const STOP = new Set(['a', 'an', 'the', 'of', 'in', 'on', 'onto', 'with', 'and', 'to', 'for', 'at', 'by', 'from', 'into', 'over', 'across', 'through', 'back', 'up', 'off', 'every', 'all', 'few', 'game', 'puzzle', 'platformer', 'short', 'little', 'small', 'calm', 'tiny', 'quiet', 'busy', 'hard', 'tough', 'fast', 'relaxing', 'zen', 'soft', 'colours', 'colors', 'kids', 'moves', 'place', 'deep', 'old', 'broken',
|
|
73
|
+
'push', 'sort', 'switch', 'turn', 'slide', 'sliding', 'match', 'matching', 'hop', 'jump', 'run', 'runner', 'leaping', 'light', 'rebuild', 'collecting', 'art', 'retro', 'pixel', 'plastic', 'toy', 'pastel', 'neon', 'ink', 'sketch', 'ink-sketch', 'marbling',
|
|
74
|
+
'race', 'racing', 'along', 'round', 'around', 'find', 'gather', 'bring', 'lost', 'stray', 'scattered', 'explore', 'knock', 'down', 'topple', 'stack', 'high', 'without', 'letting', 'fall', 'few', 'throws', 'four', 'row', 'careful', 'rival', 'quick', 'card', 'duel',
|
|
75
|
+
'or', 'hand', 'number', 'colour', 'color', 'vertical', 'shoot-\'em-up', 'dodge', 'glowing', 'against', 'twin-stick', 'crawl', 'clear', 'room', 'drift', 'empty', 'your', 'first', 'colour', 'number', 'diorama', 'low-poly', 'cars', 'table', 'track', 'parcels', 'off',
|
|
76
|
+
'bir', 've', 'ile', 'oyun', 'oyunu', 'bulmaca', 'kısa', 'tarzında', 'sakin', 'one', 'finger', 'phone']);
|
|
77
|
+
export function titleOf(pitch) {
|
|
78
|
+
const words = String(pitch).replace(/[^\p{L}\p{N}\s'-]/gu, ' ').split(/\s+/).filter((w) => w && !STOP.has(w.toLowerCase()));
|
|
79
|
+
const pick = words.slice(-3).map((w) => w[0].toUpperCase() + w.slice(1).toLowerCase());
|
|
80
|
+
if (pick.length === 3 && pick.join(' ').length > 26) pick.shift();
|
|
81
|
+
if (!pick.length) {
|
|
82
|
+
const tiny = new Set(['a', 'an', 'the', 'of', 'in', 'on', 'for', 'to', 'and', 'with', 'bir', 've', 'ile']);
|
|
83
|
+
const any = String(pitch).replace(/[^\p{L}\p{N}\s'-]/gu, ' ').split(/\s+/).filter((w) => w && !tiny.has(w.toLowerCase())).slice(0, 2);
|
|
84
|
+
pick.push(...any.map((w) => w[0].toUpperCase() + w.slice(1).toLowerCase()));
|
|
85
|
+
}
|
|
86
|
+
return (pick.join(' ') || 'Untitled').slice(0, 40);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// ─── levels ──────────────────────────────────────────────────────────────────
|
|
90
|
+
|
|
91
|
+
/** A platformer level by the seed: ground with gaps, ledges, coins, walkers and spikes, the door at the end. */
|
|
92
|
+
export function platformerLevel(rng, { length = 46, gaps = 3, walkers = 2, spikes = 2, ledges = 3, coins = 6, height = 9 } = {}) {
|
|
93
|
+
const w = length, h = height, g = h - 1;
|
|
94
|
+
const rows = Array.from({ length: h }, () => new Array(w).fill(' '));
|
|
95
|
+
for (let x = 0; x < w; x++) rows[g][x] = '#';
|
|
96
|
+
rows[g - 1][1] = '@';
|
|
97
|
+
// things on the ground keep apart: a hazard every few tiles at most, with room to land between them
|
|
98
|
+
const taken = [];
|
|
99
|
+
const room = (x, wide) => x >= 6 && x + wide <= w - 6 && taken.every(([a, b]) => x + wide + 3 <= a || x >= b + 3);
|
|
100
|
+
const place = (wide) => { for (let i = 0; i < 60; i++) { const x = rng.int(6, w - 6 - wide); if (room(x, wide)) { taken.push([x, x + wide]); return x; } } return null; };
|
|
101
|
+
const gapAt = [];
|
|
102
|
+
for (let i = 0; i < gaps; i++) { const wide = rng.int(2, 3), x = place(wide); if (x == null) continue; for (let k = 0; k < wide; k++) rows[g][x + k] = ' '; gapAt.push([x - 2, x + wide + 2]); }
|
|
103
|
+
for (let i = 0; i < spikes; i++) { const x = place(1); if (x != null) rows[g - 1][x] = '^'; }
|
|
104
|
+
for (let i = 0; i < walkers; i++) { const x = place(3); if (x != null) rows[g - 1][x + 1] = 'E'; }
|
|
105
|
+
// ledges up high (three tiles over the ground, never over a gap: a ceiling there would cut every jump short)
|
|
106
|
+
for (let i = 0; i < ledges; i++) {
|
|
107
|
+
for (let tries = 0; tries < 20; tries++) {
|
|
108
|
+
const len = rng.int(3, 5), x = rng.int(6, w - 8 - len), y = g - 3;
|
|
109
|
+
if (gapAt.some(([a, b]) => x + len > a && x < b)) continue;
|
|
110
|
+
if (rows[y].slice(x - 1, x + len + 1).some((c) => c !== ' ')) continue;
|
|
111
|
+
for (let k = 0; k < len; k++) rows[y][x + k] = '-';
|
|
112
|
+
rows[y - 1][x + Math.floor(len / 2)] = 'o';
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
let placed = rows.flat().filter((c) => c === 'o').length;
|
|
117
|
+
for (let i = 0; i < 80 && placed < coins; i++) { const x = rng.int(4, w - 4); if (rows[g - 1][x] === ' ' && rows[g][x] === '#' && rows[g - 2][x] === ' ') { rows[g - 2][x] = 'o'; placed++; } }
|
|
118
|
+
const mid = Math.floor(w / 2);
|
|
119
|
+
if (rows[g][mid] === '#' && rows[g - 1][mid] === ' ') rows[g - 1][mid] = 'C';
|
|
120
|
+
for (let x = w - 4; x < w; x++) { rows[g][x] = '#'; if (rows[g - 1][x] !== ' ') rows[g - 1][x] = ' '; }
|
|
121
|
+
rows[g - 1][w - 2] = 'D';
|
|
122
|
+
return rows.map((r) => r.join(''));
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** A push level made backwards from its solution (so it can be solved): crates on marks, pulled away by the keeper. */
|
|
126
|
+
export function pushLevel(rng, options = {}) { return pushLevelWith(rng, options).map; }
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* The same, with the moves of the way found to solve it; with `minMoves`, levels are made until one takes at
|
|
130
|
+
* least that many (the longest found is kept). → { map, moves }
|
|
131
|
+
*/
|
|
132
|
+
export function pushLevelWith(rng, { w = 8, h = 7, crates = 2, walls = 4, pulls = 40, minMoves = 0, tries = 14 } = {}) {
|
|
133
|
+
let best = null;
|
|
134
|
+
for (let t = 0; t < (minMoves ? tries : 1); t++) {
|
|
135
|
+
const map = pushOnce(rng, { w, h, crates, walls, pulls });
|
|
136
|
+
if (!minMoves) return { map, moves: null };
|
|
137
|
+
const sim = createGrid({ level: { goal: 'push', map, moves: 0 }, seed: 1 });
|
|
138
|
+
const way = search(sim, { budget: 25000 });
|
|
139
|
+
if (!way) continue;
|
|
140
|
+
if (!best || way.length > best.moves) best = { map, moves: way.length };
|
|
141
|
+
if (way.length >= minMoves) break;
|
|
142
|
+
}
|
|
143
|
+
return best ?? { map: pushOnce(rng, { w, h, crates, walls, pulls }), moves: null };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function pushOnce(rng, { w, h, crates, walls, pulls }) {
|
|
147
|
+
for (let attempt = 0; attempt < 30; attempt++) {
|
|
148
|
+
const wall = (x, y) => x <= 0 || y <= 0 || x >= w - 1 || y >= h - 1;
|
|
149
|
+
const cells = [];
|
|
150
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) cells.push(wall(x, y) ? '#' : ' ');
|
|
151
|
+
for (let i = 0; i < walls; i++) { const x = rng.int(2, w - 3), y = rng.int(2, h - 3); cells[y * w + x] = '#'; }
|
|
152
|
+
const open = cells.map((c, i) => (c === ' ' ? i : -1)).filter((i) => i >= 0);
|
|
153
|
+
if (open.length < crates * 3 + 2) continue;
|
|
154
|
+
rng.shuffle(open);
|
|
155
|
+
const marks = open.slice(0, crates), boxes = [...marks];
|
|
156
|
+
let player = open[crates];
|
|
157
|
+
const dirs = [1, -1, w, -w];
|
|
158
|
+
let moved = 0;
|
|
159
|
+
for (let i = 0; i < pulls * 4 && moved < pulls; i++) {
|
|
160
|
+
const d = rng.pick(dirs), to = player + d;
|
|
161
|
+
if (cells[to] === '#' || boxes.includes(to)) continue;
|
|
162
|
+
const behind = player - d, bi = boxes.indexOf(behind);
|
|
163
|
+
if (bi >= 0 && rng.chance(0.7)) { boxes[bi] = player; moved++; }
|
|
164
|
+
player = to;
|
|
165
|
+
}
|
|
166
|
+
if (boxes.some((b) => marks.includes(b))) continue; // every crate off its mark: each is a job
|
|
167
|
+
const out = cells.slice();
|
|
168
|
+
for (const m of marks) out[m] = '.';
|
|
169
|
+
for (const b of boxes) out[b] = out[b] === '.' ? '*' : '$';
|
|
170
|
+
out[player] = out[player] === '.' ? '+' : '@';
|
|
171
|
+
const rows = []; for (let y = 0; y < h; y++) rows.push(out.slice(y * w, (y + 1) * w).join(''));
|
|
172
|
+
return rows;
|
|
173
|
+
}
|
|
174
|
+
return ['#######', '# #', '# $. #', '# @ #', '#######'];
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
/** Three levels of a kit and goal, harder one after another. */
|
|
178
|
+
export function levelsFor({ kit, goal, hard = 0 }, rng) {
|
|
179
|
+
const d = (n) => Math.max(0, n + hard);
|
|
180
|
+
const L = (i, o) => ({ id: `l${i + 1}`, ...o });
|
|
181
|
+
if (kit === 'top-down') return [0, 1, 2].map((i) => L(i, { map: topdownLevel(rng.fork('l' + i), { rooms: 3 + i + (i > 1 ? 1 : 0), chasers: 1 + d(i) + i, sentries: d(i - 1), gems: 2 + i, locked: i > 0 }), time: 40 + i * 20 }));
|
|
182
|
+
if (kit === 'shmup') return [0, 1, 2].map((i) => L(i, shmupLevel(rng.fork('l' + i), { length: 24 + i * 10, density: 0.9 + i * 0.2 + hard * 0.1, fire: 0.32 + i * 0.15 + hard * 0.1, bossHp: 40 + i * 25, pattern: ['ring', 'fan', 'spiral'][i] })));
|
|
183
|
+
if (kit === 'racing') return [0, 1, 2].map((i) => tuneRace(L(i, { track: trackPoints(rng.fork('l' + i), { points: 8 + i * 2, radius: 50 + i * 10, wobble: 0.3 + i * 0.1 }), width: 10 - i, laps: i < 2 ? 2 : 3, rivals: 3, place: [3, 2, 1][i], rivalPace: 0.8 }), hard));
|
|
184
|
+
if (kit === 'card-board') {
|
|
185
|
+
if (goal === 'line') return [0, 1, 2].map((i) => L(i, { goal, size: i ? [7, 6] : [6, 5], inRow: 4, rival: Math.max(0, Math.min(3, i + 1 + hard)) }));
|
|
186
|
+
return [0, 1, 2].map((i) => tuneShed(L(i, { goal: 'shed', colors: 4, ranks: 6 + i, hand: 5 + i, rivals: 1, rival: Math.max(0, Math.min(2, i + hard)), wilds: 2, extra: 0 })));
|
|
187
|
+
}
|
|
188
|
+
if (kit === 'explore-3d') return [0, 1, 2].map((i) => L(i, exploreLevel(rng.fork('l' + i), { size: 24 + i * 6, items: 2 + i, trees: 25 + i * 15, rocks: 8 + i * 4, npcs: 1, fog: Math.max(4, 7 - i - Math.max(0, hard)) })));
|
|
189
|
+
if (kit === 'physics-toy') {
|
|
190
|
+
if (goal === 'stack') return [0, 1, 2].map((i) => L(i, stackLevel(rng.fork('l' + i), { pieces: 4 + i * 2, platform: 3 - i * 0.4 })));
|
|
191
|
+
return [0, 1, 2].map((i) => L(i, toppleLevel(rng.fork('l' + i), [{ floors: 2, towers: 1, shots: 2, distance: 12 }, { floors: 2, towers: 2, shots: 3, distance: 13 }, { floors: 3, towers: 1, shots: 3, distance: 14 }][i])));
|
|
192
|
+
}
|
|
193
|
+
if (kit === 'platformer') {
|
|
194
|
+
return [0, 1, 2].map((i) => ({ id: `l${i + 1}`, map: platformerLevel(rng.fork('l' + i), { length: 34 + i * 12, gaps: 1 + d(i), walkers: d(i), spikes: d(i), ledges: 2 + i, coins: 4 + i * 2 }) }));
|
|
195
|
+
}
|
|
196
|
+
if (goal === 'push') return [0, 1, 2].map((i) => {
|
|
197
|
+
const made = pushLevelWith(rng.fork('l' + i), { w: 7 + i, h: 6 + (i > 1 ? 1 : 0), crates: 1 + Math.min(2, d(i)), walls: 2 + i, pulls: 24 + i * 16, minMoves: 8 + i * 6 + hard * 4 });
|
|
198
|
+
return { id: `l${i + 1}`, goal, map: made.map, moves: made.moves ? Math.max(20, Math.ceil(made.moves * 2.5)) : 60 };
|
|
199
|
+
});
|
|
200
|
+
if (goal === 'lights') return [0, 1, 2].map((i) => ({ id: `l${i + 1}`, goal, size: [4 + Math.min(2, i), 4 + Math.min(2, i)], presses: 3 + d(i) * 2 }));
|
|
201
|
+
if (goal === 'slide') return [0, 1, 2].map((i) => ({ id: `l${i + 1}`, goal, size: i < 2 ? [3, 3] : [4, 4], shuffle: [16, 28, 26][i] + hard * 6 }));
|
|
202
|
+
return [0, 1, 2].map((i) => tuneMatch({ id: `l${i + 1}`, goal: 'match', size: [6 + Math.min(2, i), 6 + Math.min(2, i)], colors: 4 + Math.min(2, d(i)), moves: 18 - i * 2 }, hard));
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* A match level's target, by playing it: above what random swaps reach, within what the planner reaches three
|
|
207
|
+
* games in four (a calm pitch asks for less, a hard one for more).
|
|
208
|
+
*/
|
|
209
|
+
export function tuneMatch(level, hard = 0) {
|
|
210
|
+
const scores = (bot) => [1, 2, 3, 4, 5, 6].map((seed) => runBot((sd) => createGrid({ level: { ...level, target: 0 }, seed: sd }), { bot, seed, turns: level.moves }).score).sort((a, b) => a - b);
|
|
211
|
+
// what a person reaches: the greedy bot (one move ahead) for a calm or a usual game, the planner for a hard one;
|
|
212
|
+
// never so low that random moves get there
|
|
213
|
+
const rand = scores('random'), ahead = hard > 0 ? scores('planner') : scores('greedy');
|
|
214
|
+
const floor = rand[Math.floor(rand.length * 0.8)] * 1.15, ceil = ahead[Math.floor(ahead.length * (hard > 0 ? 0.3 : hard < 0 ? 0.25 : 0.5))];
|
|
215
|
+
const target = Math.max(50, Math.round(Math.min(ceil, Math.max(floor, ceil * 0.9)) / 10) * 10);
|
|
216
|
+
return { ...level, target };
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** A race's rivals as fast as they can be while a careful driver still finishes where it must, most times. */
|
|
220
|
+
export function tuneRace(level, hard = 0) {
|
|
221
|
+
const rate = (pace) => { let won = 0; for (let seed = 1; seed <= 4; seed++) if (runBot((sd) => createRacing({ game: {}, level: { ...level, rivalPace: pace }, seed: sd }), { bot: 'planner', seed, seconds: 400 }).won) won++; return won / 4; };
|
|
222
|
+
let lo = 0.5, hi = 1.05;
|
|
223
|
+
if (rate(lo) < 1) return { ...level, rivalPace: 0.45 };
|
|
224
|
+
for (let k = 0; k < 6; k++) { const mid = (lo + hi) / 2; if (rate(mid) >= 1) lo = mid; else hi = mid; }
|
|
225
|
+
return { ...level, rivalPace: Math.round(lo * (hard > 0 ? 0.99 : hard < 0 ? 0.9 : 0.95) * 100) / 100 };
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** A card game's rivals start with more cards until the planner wins four games in five. */
|
|
229
|
+
export function tuneShed(level) {
|
|
230
|
+
for (let extra = 0; extra <= 4; extra++) {
|
|
231
|
+
let won = 0;
|
|
232
|
+
for (let seed = 1; seed <= 24; seed++) if (runBot((sd) => createCards({ game: {}, level: { ...level, extra }, seed: sd }), { bot: 'planner', seed, turns: 300 }).won) won++;
|
|
233
|
+
if (won / 24 >= 0.85) return { ...level, extra };
|
|
234
|
+
}
|
|
235
|
+
return { ...level, rival: 0, extra: 4 };
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/**
|
|
239
|
+
* A first game from a pitch. → { game, rules } (rules: the text of rules.js).
|
|
240
|
+
* @param {{ pitch: string, kit?: string, goal?: string, style?: string }} options
|
|
241
|
+
*/
|
|
242
|
+
const CAMERA = { platformer: 'side', 'physics-toy': 'side', 'explore-3d': 'diorama', racing: 'follow', shmup: 'top' };
|
|
243
|
+
const INPUT = { platformer: ['keys', 'touch', 'pad'], 'top-down': ['keys', 'touch', 'pad'], shmup: ['keys', 'drag', 'pad'], racing: ['keys', 'touch', 'pad'], 'explore-3d': ['keys', 'touch', 'pad'], 'card-board': ['tap', 'keys'], 'physics-toy': ['drag', 'keys'] };
|
|
244
|
+
|
|
245
|
+
export function newGame({ pitch, kit, goal, style } = {}) {
|
|
246
|
+
if (!pitch || !String(pitch).trim()) throw new Error('newGame needs a pitch: one sentence of what the game is');
|
|
247
|
+
const read = readPitch(pitch);
|
|
248
|
+
const k = kit ?? read.kit, st = style ?? read.style;
|
|
249
|
+
const goals = { 'puzzle-grid': ['match', 'push', 'lights', 'slide'], 'card-board': ['shed', 'line'], 'physics-toy': ['topple', 'stack'] }[k];
|
|
250
|
+
const g = goals ? (goal ?? (goals.includes(read.goal) ? read.goal : goals[0])) : undefined;
|
|
251
|
+
const rng = createRng('pitch/' + pitch);
|
|
252
|
+
const look = LOOKS[st] ?? LOOKS.flat;
|
|
253
|
+
const game = {
|
|
254
|
+
engine: 1,
|
|
255
|
+
title: titleOf(pitch),
|
|
256
|
+
pitch: String(pitch),
|
|
257
|
+
kit: k,
|
|
258
|
+
look: { style: st, palette: look.palette.slice(0, 5), camera: CAMERA[k] ?? 'top' },
|
|
259
|
+
feel: { pace: read.pace, input: INPUT[k] ?? ['tap', 'arrows'], device: read.phone ? 'phone-first' : 'any' },
|
|
260
|
+
rules: 'rules.js',
|
|
261
|
+
...(k === 'platformer' ? { settings: { lives: read.hard > 0 ? 3 : 5, speed: read.pace === 'fast' ? 9 : read.pace === 'calm' ? 6 : 7 } } : {}),
|
|
262
|
+
levels: levelsFor({ kit: k, goal: g, hard: read.hard }, rng),
|
|
263
|
+
sound: { music: read.hard > 0 || k === 'shmup' || k === 'racing' ? 'tense' : read.pace === 'calm' || k === 'explore-3d' ? 'calm' : 'playful', sfx: true, volume: 0.6 },
|
|
264
|
+
checks: { bots: ['random', 'greedy', 'planner'], finish: '>= 0.7' },
|
|
265
|
+
};
|
|
266
|
+
const rules = `// The rules of "${game.title}": the ${k} kit's, and what you change here. Every hook is optional.
|
|
267
|
+
// setup(state, ctx, level), step(state, dt, ctx), actions: { name(state, ctx, ...args) }, won(state), lost(state), score(state)
|
|
268
|
+
// ctx: { rng (the seeded chance: rng(), rng.int(n), rng.pick(list)), emit(event), t }. Keep it plain data: no DOM, no Math.random.
|
|
269
|
+
export default {
|
|
270
|
+
}
|
|
271
|
+
`;
|
|
272
|
+
return { game, rules };
|
|
273
|
+
}
|
package/src/node.js
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// @clarity-js/engine/node — a game as a folder: game.json, rules.js and a page that plays it.
|
|
2
|
+
|
|
3
|
+
import { readFile, writeFile, mkdir, access } from 'node:fs/promises';
|
|
4
|
+
import { join, resolve } from 'node:path';
|
|
5
|
+
import { pathToFileURL } from 'node:url';
|
|
6
|
+
import { newGame, fit, loadGame, play, validateGame } from './index.js';
|
|
7
|
+
|
|
8
|
+
const exists = (p) => access(p).then(() => true, () => false);
|
|
9
|
+
|
|
10
|
+
/** game.json (its text too, for lines in mistakes) and what rules.js exports. */
|
|
11
|
+
export async function readGame(dir) {
|
|
12
|
+
const root = resolve(dir);
|
|
13
|
+
const text = await readFile(join(root, 'game.json'), 'utf8');
|
|
14
|
+
const v = validateGame(text);
|
|
15
|
+
let rules = {};
|
|
16
|
+
const file = v.game?.rules ?? 'rules.js';
|
|
17
|
+
if (await exists(join(root, file))) rules = (await import(pathToFileURL(join(root, file)).href + '?t=' + Date.now())).default ?? {};
|
|
18
|
+
return { dir: root, text, validation: v, game: v.game, rules };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A new game from a pitch, played and fitted, written as a folder you can run (npm install && npm run dev):
|
|
23
|
+
* `dir` (from `base`, the working folder unless given), or a folder named after the game's title.
|
|
24
|
+
* → { dir, game, report, rounds, files }
|
|
25
|
+
*/
|
|
26
|
+
export async function createGame({ pitch, dir, base = '.', kit, goal, style, seeds = 4, overwrite = false } = {}) {
|
|
27
|
+
const made = newGame({ pitch, kit, goal, style });
|
|
28
|
+
const fitted = fit(made.game, {}, { seeds });
|
|
29
|
+
const slug = fitted.game.title.normalize('NFD').replace(/[\u0300-\u036f]/g, '').replace(/ı/g, 'i').toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-|-$/g, '');
|
|
30
|
+
const root = resolve(base, dir ?? (slug || 'game'));
|
|
31
|
+
if (!overwrite && await exists(join(root, 'game.json'))) throw new Error(`${root} already has a game.json (give another folder, or overwrite)`);
|
|
32
|
+
await mkdir(root, { recursive: true });
|
|
33
|
+
const g = fitted.game;
|
|
34
|
+
const files = {
|
|
35
|
+
'game.json': JSON.stringify(g, null, 2) + '\n',
|
|
36
|
+
'rules.js': made.rules,
|
|
37
|
+
'index.html': `<!doctype html>\n<html lang="en">\n<head>\n<meta charset="utf-8">\n<meta name="viewport" content="width=device-width,initial-scale=1">\n<title>${g.title.replace(/[<&]/g, '')}</title>\n<link rel="stylesheet" href="/style.css">\n</head>\n<body>\n<div id="app"></div>\n<script type="module" src="/main.js"></script>\n</body>\n</html>\n`,
|
|
38
|
+
'style.css': 'html, body, #app { margin: 0; height: 100%; }\n',
|
|
39
|
+
'main.js': `import { mountGame } from '@clarity-js/engine/view'\nimport game from './game.json'\nimport rules from './rules.js'\n\nconst app = document.getElementById('app')\nmountGame(app, game, rules)\napp.firstElementChild?.focus()\n`,
|
|
40
|
+
'package.json': JSON.stringify({ name: root.split(/[\\/]/).pop(), private: true, type: 'module', scripts: { dev: 'vite', build: 'vite build', play: 'clarity game play .' }, dependencies: { '@ozsarman/clarityjs': '^1.15.0', '@clarity-js/engine': '^1.0.0' }, devDependencies: { vite: '^5.0.0' } }, null, 2) + '\n',
|
|
41
|
+
'README.md': `# ${g.title}\n\n${g.pitch}\n\nMade with the ${g.kit} kit of Clarity's engine. \`npm install\`, then \`npm run dev\`. The rules: game.json and rules.js. \`npx clarity game play .\` has the bots play every level and says what to change.\n`,
|
|
42
|
+
};
|
|
43
|
+
for (const [name, text] of Object.entries(files)) await writeFile(join(root, name), text);
|
|
44
|
+
return { dir: root, game: g, report: fitted.report, rounds: fitted.rounds, files: Object.keys(files) };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** Bots play a game folder. */
|
|
48
|
+
export async function playGame(dir, options = {}) {
|
|
49
|
+
const r = await readGame(dir);
|
|
50
|
+
if (!r.validation.ok) return { ok: false, validation: r.validation };
|
|
51
|
+
return play(loadGame(r.game, r.rules), options);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** The report of play(), as lines a person or an agent reads. */
|
|
55
|
+
export function formatReport(report) {
|
|
56
|
+
if (report.validation) return ['game.json has mistakes:', ...report.validation.errors.map((e) => ` ${e.path || '(top)'}${e.line ? ` (line ${e.line})` : ''}: ${e.message}${e.fix ? ` — ${e.fix}` : ''}`)].join('\n');
|
|
57
|
+
const lines = [`${report.ok ? 'Ready' : 'Not ready'}: "${report.title}" (${report.kit})`];
|
|
58
|
+
for (const l of report.levels) lines.push(` ${l.id}: ` + Object.entries(l.bots).map(([b, v]) => `${b} ${Math.round(v.rate * 100)}%${v.time != null ? ` in ${v.time}s` : v.moves != null ? ` in ${v.moves} moves` : ''}`).join(', ') + (l.deaths.length ? `; deaths at ${[...new Set(l.deaths.map((d) => `x ${Math.round(d.x)} (${d.why})`))].slice(0, 4).join(', ')}` : ''));
|
|
59
|
+
for (const c of report.checks) lines.push(` ${c.pass ? '✓' : c.soft ? '·' : '✗'} ${c.name}: ${c.why}${c.fix ? ` — fix: ${c.fix.say}` : ''}`);
|
|
60
|
+
return lines.join('\n');
|
|
61
|
+
}
|