@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
|
@@ -0,0 +1,268 @@
|
|
|
1
|
+
// @clarity-js/engine — the physics toy kit: throw to topple, or stack to build — on Clarity's own physics.
|
|
2
|
+
//
|
|
3
|
+
// Two goals (a level's `goal`), side on (x across, y up; everything stays in one plane):
|
|
4
|
+
// topple blocks stand on the ground with targets among them; throw a ball (`shots` of them) to knock every
|
|
5
|
+
// target off its place. throw(angle, power): angle in degrees above the ground, power 0 … 1.
|
|
6
|
+
// stack pieces come one at a time; drop each above the platform (drop(x)); reach `height` with the stack
|
|
7
|
+
// standing. A piece that falls off the platform ends the game.
|
|
8
|
+
//
|
|
9
|
+
// { "id": "l1", "goal": "topple", "blocks": [[x, y, w, h], …], "targets": [[x, y, size], …], "shots": 3 }
|
|
10
|
+
// { "id": "l1", "goal": "stack", "platform": 4, "pieces": [[w, h], …], "height": 4 }
|
|
11
|
+
|
|
12
|
+
import { createSim } from '@ozsarman/clarityjs/sim';
|
|
13
|
+
import { createPhysics } from '@ozsarman/clarityjs/physics';
|
|
14
|
+
import { DT, clamp, round3, settingsFor, hooked } from './common.js';
|
|
15
|
+
|
|
16
|
+
export const kit = {
|
|
17
|
+
name: 'physics-toy',
|
|
18
|
+
title: 'Physics toy',
|
|
19
|
+
describe: 'Throw to topple a tower of blocks and targets, or stack pieces into a tower that stands — on Clarity\'s own physics.',
|
|
20
|
+
goals: ['topple', 'stack'],
|
|
21
|
+
settings: {
|
|
22
|
+
gravity: { value: 9.81, min: 2, max: 30, unit: 'm/s²' },
|
|
23
|
+
launch: { value: 16, min: 4, max: 40, unit: 'm/s at full power' },
|
|
24
|
+
ball: { value: 0.35, min: 0.1, max: 1.2, unit: 'm' },
|
|
25
|
+
friction: { value: 0.6, min: 0, max: 1.5 },
|
|
26
|
+
},
|
|
27
|
+
level: {
|
|
28
|
+
topple: { blocks: [[10, 0.5, 0.5, 1], [11.5, 0.5, 0.5, 1], [10.75, 1.15, 2.2, 0.3]], targets: [[10.75, 1.65, 0.6]], shots: 3 },
|
|
29
|
+
stack: { platform: 3, pieces: [[2, 0.5], [1.6, 0.5], [1.4, 0.6], [1, 0.6], [0.8, 0.8]], height: 2.4 },
|
|
30
|
+
},
|
|
31
|
+
examples: ['Knock down the tea-glass tower with a few throws', 'Stack the parcels high without letting one fall', 'Topple the paper lanterns off the market stall'],
|
|
32
|
+
input: ['drag', 'tap', 'keys'],
|
|
33
|
+
continuous: true,
|
|
34
|
+
maxSeeds: 3, // the physics has no chance in it: more seeds play the same throws again
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
const LAUNCH = { x: 1.5, y: 1.2 };
|
|
38
|
+
const DEPTH = 1;
|
|
39
|
+
|
|
40
|
+
/** The world of a level: the bodies (made again on restore), and where each target stood. */
|
|
41
|
+
function build(s) {
|
|
42
|
+
const cfg = s.cfg, world = createPhysics({ gravity: [0, -cfg.gravity, 0], iterations: 8 });
|
|
43
|
+
world.body({ shape: 'box', size: [200, 2, 20], position: [0, -1, 0], friction: cfg.friction, name: 'ground' });
|
|
44
|
+
const bodies = [];
|
|
45
|
+
if (s.goal === 'topple') {
|
|
46
|
+
for (const [x, y, w, h] of s.blocks) bodies.push(world.body({ shape: 'box', size: [w, h, DEPTH], position: [x, y, 0], mass: w * h * 6, friction: cfg.friction, restitution: 0.05, name: 'block' }));
|
|
47
|
+
for (const [x, y, size] of s.targets) bodies.push(world.body({ shape: 'box', size: [size, size, DEPTH], position: [x, y, 0], mass: size * size * 4, friction: cfg.friction, restitution: 0.1, name: 'target' }));
|
|
48
|
+
} else {
|
|
49
|
+
world.body({ shape: 'box', size: [s.platform, 1, 4], position: [s.px, 0.5, 0], friction: 0.9, name: 'platform' });
|
|
50
|
+
}
|
|
51
|
+
return { world, bodies };
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function setup(level, cfg) {
|
|
55
|
+
const goal = level.goal ?? 'topple';
|
|
56
|
+
const base = { ...kit.level[goal], ...level };
|
|
57
|
+
const s = { goal, cfg, won: false, lost: false, t: 0, used: 0, score: 0, deaths: [], settle: 0, busy: false, best: 0 };
|
|
58
|
+
if (goal === 'topple') Object.assign(s, { blocks: base.blocks, targets: base.targets, shots: clamp(Math.round(base.shots ?? 3), 1, 12), down: 0, balls: [] });
|
|
59
|
+
else Object.assign(s, { platform: clamp(base.platform ?? 3, 0.5, 12), px: 8, pieces: base.pieces, next: 0, height: clamp(base.height ?? 2, 0.3, 20), top: 1, placed: [], stood: 0 });
|
|
60
|
+
return s;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** Each target is down when it has moved off its place (fallen a third of its size, or left by more than its size). */
|
|
64
|
+
function countDown(s, phys) {
|
|
65
|
+
let down = 0;
|
|
66
|
+
s.targets.forEach(([x, y, size], i) => { const b = phys.bodies[s.blocks.length + i]; if (b && (b.position[1] < y - size * 0.33 || Math.abs(b.position[0] - x) > size * 1.2 || b.position[1] < 0)) down++; });
|
|
67
|
+
return down;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function stackTop(s, phys) {
|
|
71
|
+
let top = 1;
|
|
72
|
+
for (const b of phys.bodies) if (b.position[1] > 0.6 && Math.abs(b.position[0] - s.px) < s.platform * 0.5 + 1) top = Math.max(top, b.position[1] + b.shape.half[1]);
|
|
73
|
+
return top;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// at rest: every block, target and piece still; a ball only counts while it is near the toys and moving fast
|
|
77
|
+
const still = (phys) => phys.world.bodies.every((b) => !b.invMass || b.sleeping || (b.name === 'ball' ? Math.hypot(...b.velocity) < 1.5 : Math.hypot(...b.velocity) < 0.08 && Math.hypot(...b.angularVelocity) < 0.15));
|
|
78
|
+
|
|
79
|
+
function step(s, dt, ctx, phys) {
|
|
80
|
+
if (s.won || s.lost) return;
|
|
81
|
+
s.t += dt;
|
|
82
|
+
phys.world.step(dt);
|
|
83
|
+
// the plane: nothing drifts out of it, nothing turns but about the axis toward the eye
|
|
84
|
+
for (const b of phys.world.bodies) if (b.invMass) { b.position[2] = 0; b.velocity[2] = 0; b.angularVelocity[0] = 0; b.angularVelocity[1] = 0; const q = b.quaternion, l = Math.hypot(q[2], q[3]) || 1; b.quaternion = [0, 0, q[2] / l, q[3] / l]; }
|
|
85
|
+
if (!s.busy) return;
|
|
86
|
+
s.settle += dt;
|
|
87
|
+
if (s.settle < 0.6 || (!still(phys) && s.settle < 6)) return;
|
|
88
|
+
s.busy = false; s.settle = 0;
|
|
89
|
+
if (s.goal === 'topple') {
|
|
90
|
+
s.down = countDown(s, phys);
|
|
91
|
+
ctx.emit({ type: 'settled', down: s.down });
|
|
92
|
+
if (s.down >= s.targets.length) { s.won = true; s.score = 200 * s.shots + 100; ctx.emit({ type: 'won', shotsLeft: s.shots }); }
|
|
93
|
+
else if (s.shots <= 0) { s.lost = true; ctx.emit({ type: 'lost', why: 'shots' }); }
|
|
94
|
+
} else {
|
|
95
|
+
const fell = phys.bodies.some((b) => b.position[1] < 0.5);
|
|
96
|
+
s.top = round3(stackTop(s, phys));
|
|
97
|
+
s.best = Math.max(s.best, s.top - 1);
|
|
98
|
+
ctx.emit({ type: 'settled', top: s.top });
|
|
99
|
+
if (fell) { s.lost = true; s.deaths.push({ x: s.px, y: 0, why: 'fell', t: round3(s.t) }); ctx.emit({ type: 'lost', why: 'fell' }); }
|
|
100
|
+
else if (s.top - 1 >= s.height) { s.won = true; s.score = 300 + (s.pieces.length - s.next) * 100; ctx.emit({ type: 'won' }); }
|
|
101
|
+
else if (s.next >= s.pieces.length) { s.lost = true; ctx.emit({ type: 'lost', why: 'pieces' }); }
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function makeActions(phys) {
|
|
106
|
+
return {
|
|
107
|
+
/** topple: throw the ball at an angle (degrees above the ground) with a power from 0 to 1. */
|
|
108
|
+
throw(s, ctx, angle = 45, power = 0.8) {
|
|
109
|
+
if (s.goal !== 'topple' || s.busy || s.won || s.lost || s.shots <= 0) return false;
|
|
110
|
+
const a = clamp(Number(angle) || 45, 0, 89) * Math.PI / 180, v = clamp(Number(power) || 0, 0.05, 1) * s.cfg.launch;
|
|
111
|
+
phys.balls.push(phys.world.body({ shape: 'sphere', radius: s.cfg.ball, position: [LAUNCH.x, LAUNCH.y, 0], velocity: [Math.cos(a) * v, Math.sin(a) * v, 0], mass: 2, restitution: 0.3, friction: 0.4, name: 'ball' }));
|
|
112
|
+
s.shots--; s.used++; s.busy = true; s.settle = 0;
|
|
113
|
+
ctx.emit({ type: 'throw', angle: round3(a * 180 / Math.PI), power: round3(v / s.cfg.launch) });
|
|
114
|
+
return true;
|
|
115
|
+
},
|
|
116
|
+
/** stack: drop the next piece with its middle at x (the platform's middle is x 8). */
|
|
117
|
+
drop(s, ctx, x = 8) {
|
|
118
|
+
if (s.goal !== 'stack' || s.busy || s.won || s.lost || s.next >= s.pieces.length) return false;
|
|
119
|
+
const [w, h] = s.pieces[s.next];
|
|
120
|
+
const top = stackTop(s, phys);
|
|
121
|
+
phys.bodies.push(phys.world.body({ shape: 'box', size: [w, h, DEPTH], position: [clamp(Number(x) || 8, s.px - 6, s.px + 6), top + h / 2 + 0.4, 0], mass: w * h * 2, friction: s.cfg.friction + 0.2, restitution: 0.02, name: 'piece' }));
|
|
122
|
+
s.next++; s.used++; s.busy = true; s.settle = 0;
|
|
123
|
+
ctx.emit({ type: 'drop', x: round3(x) });
|
|
124
|
+
return true;
|
|
125
|
+
},
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function value(s) {
|
|
130
|
+
if (s.won) return 1e6 + (s.shots ?? 0) * 1000 - s.used;
|
|
131
|
+
if (s.lost) return -1e6;
|
|
132
|
+
return s.goal === 'topple' ? s.down * 100 + s.shots * 10 : (s.top - 1) * 100 + (s.pieces.length - s.next) * 5;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Ballistics: the power for a throw at `deg` to pass through (x, y), or null. */
|
|
136
|
+
function powerFor(s, deg, x, y) {
|
|
137
|
+
const a = deg * Math.PI / 180, dx = x - LAUNCH.x, dy = y - LAUNCH.y, g = s.cfg.gravity;
|
|
138
|
+
const den = 2 * Math.cos(a) ** 2 * (dx * Math.tan(a) - dy);
|
|
139
|
+
if (den <= 0) return null;
|
|
140
|
+
const v = Math.sqrt(g * dx * dx / den) / s.cfg.launch;
|
|
141
|
+
return v <= 1 ? v : null;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** Try a move, play until it settles, see how it went; then put the world back. */
|
|
145
|
+
function trial(sim, act, args) {
|
|
146
|
+
const snap = sim.snapshot(), n = sim.log.length;
|
|
147
|
+
sim.act(act, ...args);
|
|
148
|
+
const want = sim.state.goal === 'topple' ? sim.state.targets.length : 0;
|
|
149
|
+
for (let t = 0; t < 3 && sim.state.busy; t += DT) {
|
|
150
|
+
sim.step(DT);
|
|
151
|
+
if (want && (t * 60 | 0) % 15 === 0 && countDown(sim.state, sim.world) >= want) break; // everything down: no need to wait
|
|
152
|
+
}
|
|
153
|
+
if (sim.state.goal === 'topple' && sim.state.busy) sim.state.down = countDown(sim.state, sim.world);
|
|
154
|
+
const v = sim.value(), s = sim.state;
|
|
155
|
+
const extra = s.goal === 'topple' ? 0 : -(s.placed?.length ?? 0);
|
|
156
|
+
sim.restore(snap); sim.log.length = n;
|
|
157
|
+
return v + extra;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export const bots = {
|
|
161
|
+
random(sim, rng) {
|
|
162
|
+
const s = sim.state;
|
|
163
|
+
if (s.busy) return { act: null, for: 0.2 };
|
|
164
|
+
return s.goal === 'topple' ? { act: 'throw', args: [rng.range(10, 70), rng.range(0.3, 1)], for: 0.2 } : { act: 'drop', args: [s.px + rng.range(-1.5, 1.5)], for: 0.2 };
|
|
165
|
+
},
|
|
166
|
+
greedy(sim) {
|
|
167
|
+
// straight at the nearest target still standing (a 35° throw), or each piece in the middle
|
|
168
|
+
const s = sim.state;
|
|
169
|
+
if (s.busy) return { act: null, for: 0.2 };
|
|
170
|
+
if (s.goal === 'stack') return { act: 'drop', args: [s.px], for: 0.2 };
|
|
171
|
+
const t = s.targets[0];
|
|
172
|
+
const p = powerFor(s, 35, t[0], t[1]) ?? 1;
|
|
173
|
+
return { act: 'throw', args: [35, p], for: 0.2 };
|
|
174
|
+
},
|
|
175
|
+
planner(sim, rng) {
|
|
176
|
+
// throws (or drops) tried on a copy of the world; the best end chosen
|
|
177
|
+
const s = sim.state;
|
|
178
|
+
if (s.busy) return { act: null, for: 0.2 };
|
|
179
|
+
let best = -Infinity, pick = null;
|
|
180
|
+
if (s.goal === 'topple') {
|
|
181
|
+
// for each tower still holding a target: a flat hard throw at its foot, one at the target, a lob onto it
|
|
182
|
+
const cands = [], standing = s.targets.filter((t, i) => { const b = sim.world.bodies[s.blocks.length + i]; return b && b.position[1] > t[1] - t[2] * 0.33 && Math.abs(b.position[0] - t[0]) < t[2] * 1.2; });
|
|
183
|
+
const towers = [...new Map(standing.map((t) => [Math.round(t[0] / 3), t])).values()].slice(0, 2);
|
|
184
|
+
for (const [x, y, size] of towers) {
|
|
185
|
+
const foot = s.blocks.filter((b) => Math.abs(b[0] - x) < 2).sort((a, b) => a[0] - b[0] || a[1] - b[1])[0];
|
|
186
|
+
const fp = foot && powerFor(s, 12, foot[0] - 0.2, foot[1] + foot[3] * 0.25); if (fp) cands.push([12, Math.min(1, fp * 1.08)]);
|
|
187
|
+
const tp = powerFor(s, 30, x - size * 0.4, y); if (tp) cands.push([30, Math.min(1, tp * 1.05)]);
|
|
188
|
+
const lp = powerFor(s, 55, x, y + size * 0.2); if (lp) cands.push([55, Math.min(1, lp * 1.02)]);
|
|
189
|
+
}
|
|
190
|
+
cands.push([rng.range(15, 55), rng.range(0.75, 1)]);
|
|
191
|
+
for (const c of cands) { const v = trial(sim, 'throw', c); if (v > best) { best = v; pick = c; } }
|
|
192
|
+
return { act: 'throw', args: pick ?? [40, 0.9], for: 0.2 };
|
|
193
|
+
}
|
|
194
|
+
const piece = s.pieces[s.next], cands = [0, -0.15, 0.15, -0.35, 0.35].map((d) => s.px + d * (s.platform - (piece?.[0] ?? 1)));
|
|
195
|
+
for (const x of cands) { const v = trial(sim, 'drop', [x]) - Math.abs(x - s.px) * 0.5; if (v > best) { best = v; pick = [x]; } }
|
|
196
|
+
return { act: 'drop', args: pick ?? [s.px], for: 0.2 };
|
|
197
|
+
},
|
|
198
|
+
};
|
|
199
|
+
|
|
200
|
+
export function create({ game, level, seed = 1, hooks = {} }) {
|
|
201
|
+
const cfg = settingsFor(kit.settings, game);
|
|
202
|
+
const phys = { world: null, bodies: [], balls: [] };
|
|
203
|
+
const h = hooked(hooks, makeActions(phys));
|
|
204
|
+
const sim = createSim({
|
|
205
|
+
seed,
|
|
206
|
+
setup: (ctx) => { const s = setup(level, cfg); const b = build(s); phys.world = b.world; phys.bodies = b.bodies; phys.balls = []; hooks.setup?.(s, ctx, level); return s; },
|
|
207
|
+
step: (s, dt, ctx) => { step(s, dt, ctx, phys); hooks.step?.(s, dt, ctx); h.end(s, ctx); },
|
|
208
|
+
actions: h.actions,
|
|
209
|
+
report: (s) => ({
|
|
210
|
+
goal: s.goal, won: s.won, lost: s.lost, busy: s.busy, used: s.used, t: round3(s.t),
|
|
211
|
+
...(s.goal === 'topple' ? { shots: s.shots, down: s.down, targets: s.targets.length } : { next: s.next, pieces: s.pieces.length, top: s.top, height: s.height }),
|
|
212
|
+
bodies: phys.world.bodies.filter((b) => b.invMass).map((b) => ({ name: b.name, x: round3(b.position[0]), y: round3(b.position[1]), angle: round3(2 * Math.atan2(b.quaternion[2], b.quaternion[3])), w: b.shape.half ? round3(b.shape.half[0] * 2) : round3(b.shape.radius * 2), h: b.shape.half ? round3(b.shape.half[1] * 2) : round3(b.shape.radius * 2) })),
|
|
213
|
+
score: hooks.score ? hooks.score(s) : s.score,
|
|
214
|
+
}),
|
|
215
|
+
});
|
|
216
|
+
// the world is not plain data: a snapshot keeps it beside the rules' state, the bodies (balls, pieces) too
|
|
217
|
+
const snap = sim.snapshot.bind(sim), restore = sim.restore.bind(sim);
|
|
218
|
+
sim.snapshot = () => ({ rules: snap(), world: phys.world.snapshot(), count: phys.world.bodies.length, balls: phys.balls.length, bodies: phys.bodies.length });
|
|
219
|
+
sim.restore = (k) => {
|
|
220
|
+
restore(k.rules);
|
|
221
|
+
while (phys.world.bodies.length > k.count) { const b = phys.world.bodies[phys.world.bodies.length - 1]; phys.world.remove(b); }
|
|
222
|
+
phys.balls.length = k.balls; phys.bodies.length = k.bodies;
|
|
223
|
+
phys.world.restore(k.world);
|
|
224
|
+
return sim;
|
|
225
|
+
};
|
|
226
|
+
sim.kit = kit; sim.bots = bots; sim.world = phys;
|
|
227
|
+
sim.legal = () => [];
|
|
228
|
+
sim.value = () => (hooks.value ? hooks.value(sim.state) : value(sim.state));
|
|
229
|
+
return sim;
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// ─── levels ──────────────────────────────────────────────────────────────────
|
|
233
|
+
|
|
234
|
+
/** A tower to topple: posts and planks in floors, a target on each floor, at a distance. */
|
|
235
|
+
export function toppleLevel(rng, { floors = 2, towers = 1, shots = 3, distance = 10 } = {}) {
|
|
236
|
+
const blocks = [], targets = [];
|
|
237
|
+
for (let k = 0; k < towers; k++) {
|
|
238
|
+
const x0 = distance + k * 4 + rng.range(-0.5, 0.5), span = rng.range(1.6, 2.4);
|
|
239
|
+
let y = 0;
|
|
240
|
+
for (let f = 0; f < floors; f++) {
|
|
241
|
+
const post = 0.9 + rng.range(0, 0.4), w = Math.max(1, span - f * 0.3);
|
|
242
|
+
blocks.push([round3(x0 - w / 2 + 0.2), round3(y + post / 2), 0.3, round3(post)], [round3(x0 + w / 2 - 0.2), round3(y + post / 2), 0.3, round3(post)]);
|
|
243
|
+
y += post;
|
|
244
|
+
blocks.push([round3(x0), round3(y + 0.12), round3(w + 0.2), 0.24]);
|
|
245
|
+
y += 0.24;
|
|
246
|
+
if (f === floors - 1 || rng.chance(0.4)) targets.push([round3(x0), round3(y + 0.25), 0.5]);
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
return { goal: 'topple', blocks, targets, shots };
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
/** Pieces to stack: wide first, then narrower and taller, to a height they can reach. */
|
|
253
|
+
export function stackLevel(rng, { pieces = 6, platform = 3, height } = {}) {
|
|
254
|
+
const list = [];
|
|
255
|
+
let total = 0;
|
|
256
|
+
for (let i = 0; i < pieces; i++) { const w = round3(Math.max(0.6, platform * (0.75 - i * 0.07) + rng.range(-0.15, 0.15))), hh = round3(rng.range(0.4, 0.7)); list.push([w, hh]); total += hh; }
|
|
257
|
+
return { goal: 'stack', platform, pieces: list, height: round3(height ?? total * 0.85) };
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** Easier versions of a level, the smallest change first (for play()'s fixes). */
|
|
261
|
+
export function easier(lv) {
|
|
262
|
+
if ((lv.goal ?? 'topple') === 'stack') return [0.85, 0.7, 0.55].map((f) => ({ change: { height: round3((lv.height ?? 2) * f) }, say: `height ${lv.height} → ${round3((lv.height ?? 2) * f)}` }));
|
|
263
|
+
return [1, 2, 4].map((n) => ({ change: { shots: (lv.shots ?? 3) + n }, say: `shots ${lv.shots ?? 3} → ${(lv.shots ?? 3) + n}` }));
|
|
264
|
+
}
|
|
265
|
+
export function harder(lv) {
|
|
266
|
+
if ((lv.goal ?? 'topple') === 'stack') return [{ change: { height: round3((lv.height ?? 2) * 1.15) }, say: `height ${lv.height} → ${round3((lv.height ?? 2) * 1.15)}` }];
|
|
267
|
+
return (lv.shots ?? 3) > 1 ? [{ change: { shots: (lv.shots ?? 3) - 1 }, say: `shots ${lv.shots ?? 3} → ${(lv.shots ?? 3) - 1}` }] : [];
|
|
268
|
+
}
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
// @clarity-js/engine — the platformer kit: run, jump, collect, reach the door.
|
|
2
|
+
//
|
|
3
|
+
// A level is a map, one string a row, top first:
|
|
4
|
+
// # solid ground - a ledge you can jump up through @ where you start
|
|
5
|
+
// o a coin E a walker (stomp it, or keep away) ^ spikes
|
|
6
|
+
// D the door (the goal; with `coins` set, only after that many) C a checkpoint
|
|
7
|
+
//
|
|
8
|
+
// The rules step at a fixed rate (1/60 s) with coyote time (a jump just after leaving a ledge still
|
|
9
|
+
// counts), a jump buffer (a press just before landing still jumps) and a jump that is cut short when the
|
|
10
|
+
// button is let go. Input is held state, as a pad's is: input(dir, jump), dir −1, 0 or 1.
|
|
11
|
+
|
|
12
|
+
import { createSim } from '@ozsarman/clarityjs/sim';
|
|
13
|
+
|
|
14
|
+
export const kit = {
|
|
15
|
+
name: 'platformer',
|
|
16
|
+
title: 'Platformer',
|
|
17
|
+
describe: 'Run and jump through a level of ledges, coins, walkers and spikes to the door.',
|
|
18
|
+
settings: {
|
|
19
|
+
gravity: { value: 42, min: 10, max: 120, unit: 'tiles/s²' },
|
|
20
|
+
jump: { value: 3.2, min: 1, max: 8, unit: 'tiles high' },
|
|
21
|
+
speed: { value: 7, min: 2, max: 20, unit: 'tiles/s' },
|
|
22
|
+
accel: { value: 70, min: 10, max: 300, unit: 'tiles/s²' },
|
|
23
|
+
coyote: { value: 0.1, min: 0, max: 0.3, unit: 's' },
|
|
24
|
+
buffer: { value: 0.12, min: 0, max: 0.3, unit: 's' },
|
|
25
|
+
lives: { value: 3, min: 1, max: 99 },
|
|
26
|
+
enemySpeed: { value: 2, min: 0, max: 10, unit: 'tiles/s' },
|
|
27
|
+
},
|
|
28
|
+
level: { map: [' ', ' D ', ' o o #####', ' #### ### ', '@ ', '####################'] },
|
|
29
|
+
examples: ['A short platformer through a windy orchard', 'Hop across rooftops collecting lanterns', 'A night run over the market stalls'],
|
|
30
|
+
input: ['keys', 'touch', 'pad'],
|
|
31
|
+
continuous: true,
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
const W = 0.7, H = 0.9; // the runner's box, in tiles
|
|
35
|
+
|
|
36
|
+
export function settingsOf(game) {
|
|
37
|
+
const out = {};
|
|
38
|
+
for (const [k, d] of Object.entries(kit.settings)) {
|
|
39
|
+
const v = Number(game?.settings?.[k]);
|
|
40
|
+
out[k] = Number.isFinite(v) ? Math.min(d.max, Math.max(d.min, v)) : d.value;
|
|
41
|
+
}
|
|
42
|
+
return out;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function parse(map) {
|
|
46
|
+
const rows = map.map(String);
|
|
47
|
+
const h = rows.length, w = Math.max(...rows.map((r) => r.length));
|
|
48
|
+
const tiles = new Array(w * h).fill(0); // 0 air, 1 solid, 2 ledge, 3 spikes
|
|
49
|
+
const coins = [], enemies = [], checkpoints = [];
|
|
50
|
+
let start = null, door = null;
|
|
51
|
+
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
|
|
52
|
+
const c = rows[y][x] ?? ' ';
|
|
53
|
+
if (c === '#') tiles[y * w + x] = 1;
|
|
54
|
+
else if (c === '-') tiles[y * w + x] = 2;
|
|
55
|
+
else if (c === '^') tiles[y * w + x] = 3;
|
|
56
|
+
else if (c === 'o') coins.push({ x: x + 0.5, y: y + 0.5, got: false });
|
|
57
|
+
else if (c === 'E') enemies.push({ x: x + 0.5, y: y + 1 - 0.45, vx: -1, alive: true, home: x });
|
|
58
|
+
else if (c === '@') start = { x: x + 0.5, y: y + 1 - H / 2 };
|
|
59
|
+
else if (c === 'D') door = { x: x + 0.5, y: y + 0.5 };
|
|
60
|
+
else if (c === 'C') checkpoints.push({ x: x + 0.5, y: y + 1 - H / 2, on: false });
|
|
61
|
+
}
|
|
62
|
+
if (!start) throw new Error('a platformer level needs a start: @ in its map');
|
|
63
|
+
if (!door) throw new Error('a platformer level needs a door: D in its map');
|
|
64
|
+
return { w, h, tiles, coins, enemies, checkpoints, start, door };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const tile = (s, x, y) => (x < 0 || x >= s.w ? 1 : y < 0 ? 0 : y >= s.h ? 0 : s.tiles[y * s.w + x]);
|
|
68
|
+
|
|
69
|
+
function setup(level, cfg) {
|
|
70
|
+
const m = parse(level.map);
|
|
71
|
+
const s = {
|
|
72
|
+
...m, cfg,
|
|
73
|
+
x: m.start.x, y: m.start.y, vx: 0, vy: 0, onGround: false, facing: 1,
|
|
74
|
+
coyote: 0, buffered: 0, cut: false, dir: 0, jumpHeld: false, jumpWas: false,
|
|
75
|
+
respawn: { ...m.start }, lives: cfg.lives, deaths: [], coinsGot: 0, need: Number(level.coins ?? 0) || 0,
|
|
76
|
+
score: 0, won: false, lost: false, t: 0, time: Number(level.time ?? 0) || 0, best: 0, far: 0,
|
|
77
|
+
};
|
|
78
|
+
s.dist0 = Math.hypot(m.door.x - m.start.x, m.door.y - m.start.y) || 1;
|
|
79
|
+
return s;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function die(s, ctx, why) {
|
|
83
|
+
s.deaths.push({ x: Math.round(s.x * 10) / 10, y: Math.round(s.y * 10) / 10, why, t: Math.round(s.t * 100) / 100 });
|
|
84
|
+
s.lives--;
|
|
85
|
+
ctx.emit({ type: 'death', why, x: s.x, y: s.y });
|
|
86
|
+
if (s.lives <= 0) { s.lost = true; ctx.emit({ type: 'lost', why }); return; }
|
|
87
|
+
s.x = s.respawn.x; s.y = s.respawn.y; s.vx = 0; s.vy = 0; s.buffered = 0; s.coyote = 0;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function collideX(s) {
|
|
91
|
+
const top = Math.floor(s.y - H / 2 + 0.01), bot = Math.floor(s.y + H / 2 - 0.01);
|
|
92
|
+
if (s.vx > 0) {
|
|
93
|
+
const edge = Math.floor(s.x + W / 2);
|
|
94
|
+
for (let y = top; y <= bot; y++) if (tile(s, edge, y) === 1) { s.x = edge - W / 2 - 0.0001; s.vx = 0; return; }
|
|
95
|
+
} else if (s.vx < 0) {
|
|
96
|
+
const edge = Math.floor(s.x - W / 2);
|
|
97
|
+
for (let y = top; y <= bot; y++) if (tile(s, edge, y) === 1) { s.x = edge + 1 + W / 2 + 0.0001; s.vx = 0; return; }
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function collideY(s, prevBottom) {
|
|
102
|
+
const left = Math.floor(s.x - W / 2 + 0.01), right = Math.floor(s.x + W / 2 - 0.01);
|
|
103
|
+
s.onGround = false;
|
|
104
|
+
if (s.vy > 0) {
|
|
105
|
+
const edge = Math.floor(s.y + H / 2);
|
|
106
|
+
for (let x = left; x <= right; x++) {
|
|
107
|
+
const t = tile(s, x, edge);
|
|
108
|
+
if (t === 1 || (t === 2 && prevBottom <= edge + 0.001)) { s.y = edge - H / 2 - 0.0001; s.vy = 0; s.onGround = true; return; }
|
|
109
|
+
}
|
|
110
|
+
} else if (s.vy < 0) {
|
|
111
|
+
const edge = Math.floor(s.y - H / 2);
|
|
112
|
+
for (let x = left; x <= right; x++) if (tile(s, x, edge) === 1) { s.y = edge + 1 + H / 2 + 0.0001; s.vy = 0; return; }
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function touches(s, kind) {
|
|
117
|
+
const left = Math.floor(s.x - W / 2 + 0.05), right = Math.floor(s.x + W / 2 - 0.05);
|
|
118
|
+
const top = Math.floor(s.y - H / 2 + 0.05), bot = Math.floor(s.y + H / 2 - 0.05);
|
|
119
|
+
for (let y = top; y <= bot; y++) for (let x = left; x <= right; x++) if (tile(s, x, y) === kind) return true;
|
|
120
|
+
return false;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function step(s, dt, ctx) {
|
|
124
|
+
if (s.won || s.lost) return;
|
|
125
|
+
const c = s.cfg;
|
|
126
|
+
s.t += dt;
|
|
127
|
+
if (s.time && s.t > s.time) { s.lost = true; ctx.emit({ type: 'lost', why: 'time' }); return; }
|
|
128
|
+
// input → speed
|
|
129
|
+
const want = s.dir * c.speed;
|
|
130
|
+
const rate = s.dir ? c.accel : c.accel * 0.8;
|
|
131
|
+
s.vx += Math.max(-rate * dt, Math.min(rate * dt, want - s.vx));
|
|
132
|
+
if (s.dir) s.facing = s.dir;
|
|
133
|
+
// jump: buffered press, coyote time, cut when let go
|
|
134
|
+
if (s.jumpHeld && !s.jumpWas) s.buffered = c.buffer || dt;
|
|
135
|
+
s.jumpWas = s.jumpHeld;
|
|
136
|
+
s.coyote = s.onGround ? c.coyote : Math.max(0, s.coyote - dt);
|
|
137
|
+
if (s.buffered > 0 && (s.onGround || s.coyote > 0)) {
|
|
138
|
+
s.vy = -Math.sqrt(2 * c.gravity * c.jump);
|
|
139
|
+
s.buffered = 0; s.coyote = 0; s.onGround = false; s.cut = false;
|
|
140
|
+
ctx.emit({ type: 'jump' });
|
|
141
|
+
}
|
|
142
|
+
s.buffered = Math.max(0, s.buffered - dt);
|
|
143
|
+
if (!s.jumpHeld && s.vy < 0 && !s.cut) { s.vy *= 0.5; s.cut = true; }
|
|
144
|
+
s.vy = Math.min(26, s.vy + c.gravity * dt);
|
|
145
|
+
// move and collide
|
|
146
|
+
const prevBottom = s.y + H / 2;
|
|
147
|
+
s.x += s.vx * dt; collideX(s);
|
|
148
|
+
s.y += s.vy * dt; collideY(s, prevBottom);
|
|
149
|
+
if (s.y - H / 2 > s.h + 2) { die(s, ctx, 'fell'); return; }
|
|
150
|
+
if (touches(s, 3)) { die(s, ctx, 'spikes'); return; }
|
|
151
|
+
// walkers
|
|
152
|
+
for (const e of s.enemies) {
|
|
153
|
+
if (!e.alive) continue;
|
|
154
|
+
const nx = e.x + e.vx * c.enemySpeed * dt;
|
|
155
|
+
const ahead = Math.floor(nx + Math.sign(e.vx) * 0.45), row = Math.floor(e.y), below = Math.floor(e.y + 0.5);
|
|
156
|
+
if (tile(s, ahead, row) === 1 || (tile(s, ahead, below) !== 1 && tile(s, ahead, below) !== 2)) e.vx = -e.vx; else e.x = nx;
|
|
157
|
+
if (Math.abs(e.x - s.x) < (W + 0.8) / 2 && Math.abs(e.y - s.y) < (H + 0.9) / 2) {
|
|
158
|
+
if (s.vy > 0 && s.y < e.y - 0.25) { e.alive = false; s.vy = -Math.sqrt(2 * c.gravity * c.jump) * 0.6; s.score += 50; ctx.emit({ type: 'stomp', x: e.x, y: e.y }); }
|
|
159
|
+
else { die(s, ctx, 'walker'); return; }
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
// coins, checkpoints, the door
|
|
163
|
+
for (const k of s.coins) if (!k.got && Math.abs(k.x - s.x) < 0.6 && Math.abs(k.y - s.y) < 0.7) { k.got = true; s.coinsGot++; s.score += 10; ctx.emit({ type: 'coin', x: k.x, y: k.y }); }
|
|
164
|
+
for (const cp of s.checkpoints) if (!cp.on && Math.abs(cp.x - s.x) < 0.6 && Math.abs(cp.y - s.y) < 0.8) { cp.on = true; s.respawn = { x: cp.x, y: cp.y }; ctx.emit({ type: 'checkpoint' }); }
|
|
165
|
+
if (Math.abs(s.door.x - s.x) < 0.6 && Math.abs(s.door.y - s.y) < 0.8 && s.coinsGot >= s.need) {
|
|
166
|
+
s.won = true; s.score += 100 + Math.round(s.lives * 20); ctx.emit({ type: 'won', t: s.t });
|
|
167
|
+
}
|
|
168
|
+
const d = Math.hypot(s.door.x - s.x, s.door.y - s.y);
|
|
169
|
+
s.best = Math.max(s.best, 1 - d / s.dist0);
|
|
170
|
+
s.far = Math.max(s.far, s.x);
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const ACTIONS = {
|
|
174
|
+
/** Hold a direction (−1 or "left", 0 or "none", 1 or "right") and the jump button (true while held). */
|
|
175
|
+
input(s, ctx, dir = 0, jump = false) { const d = dir === 'left' ? -1 : dir === 'right' ? 1 : Number(dir) || 0; s.dir = Math.max(-1, Math.min(1, Math.round(d))); s.jumpHeld = !!jump; },
|
|
176
|
+
left(s) { s.dir = -1; },
|
|
177
|
+
right(s) { s.dir = 1; },
|
|
178
|
+
stop(s) { s.dir = 0; },
|
|
179
|
+
/** Press jump (held until release). */
|
|
180
|
+
jump(s) { s.jumpHeld = true; },
|
|
181
|
+
release(s) { s.jumpHeld = false; },
|
|
182
|
+
};
|
|
183
|
+
|
|
184
|
+
export function create({ game, level, seed = 1, hooks = {} }) {
|
|
185
|
+
const cfg = settingsOf(game);
|
|
186
|
+
const sim = createSim({
|
|
187
|
+
seed,
|
|
188
|
+
setup: (ctx) => { const s = setup(level, cfg); hooks.setup?.(s, ctx, level); return s; },
|
|
189
|
+
step: (s, dt, ctx) => {
|
|
190
|
+
step(s, dt, ctx);
|
|
191
|
+
hooks.step?.(s, dt, ctx);
|
|
192
|
+
if (!s.won && !s.lost) { if (hooks.won?.(s)) { s.won = true; ctx.emit({ type: 'won' }); } else if (hooks.lost?.(s)) { s.lost = true; ctx.emit({ type: 'lost', why: 'rules' }); } }
|
|
193
|
+
},
|
|
194
|
+
actions: { ...ACTIONS, ...(hooks.actions ?? {}) },
|
|
195
|
+
report: (s) => ({
|
|
196
|
+
won: s.won, lost: s.lost, x: round(s.x), y: round(s.y), vx: round(s.vx), vy: round(s.vy), onGround: s.onGround, facing: s.facing,
|
|
197
|
+
coins: s.coinsGot, coinsTotal: s.coins.length, need: s.need, lives: s.lives, deaths: s.deaths.length, t: round(s.t),
|
|
198
|
+
progress: round(s.best), score: hooks.score ? hooks.score(s) : s.score, w: s.w, h: s.h,
|
|
199
|
+
}),
|
|
200
|
+
});
|
|
201
|
+
sim.kit = kit;
|
|
202
|
+
sim.value = () => value(sim.state);
|
|
203
|
+
sim.sense = () => sense(sim.state);
|
|
204
|
+
return sim;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const round = (v) => Math.round(v * 1000) / 1000;
|
|
208
|
+
|
|
209
|
+
function value(s) {
|
|
210
|
+
if (s.won) return 1e6 + s.lives * 1000 - s.t;
|
|
211
|
+
if (s.lost) return -1e6;
|
|
212
|
+
const d = Math.hypot(s.door.x - s.x, s.door.y - s.y);
|
|
213
|
+
const missing = Math.max(0, s.need - s.coinsGot);
|
|
214
|
+
let coinPull = 0;
|
|
215
|
+
if (missing) { const left = s.coins.filter((k) => !k.got); if (left.length) coinPull = Math.min(...left.map((k) => Math.hypot(k.x - s.x, k.y - s.y))); }
|
|
216
|
+
return -(missing ? coinPull + missing * 30 : d) * 10 - s.deaths.length * 60 + s.coinsGot * 5 + (s.onGround ? 2 : 0);
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/** What is ahead of the runner, for a bot that reacts: a wall, a gap, spikes, a walker, the door's side. */
|
|
220
|
+
function sense(s) {
|
|
221
|
+
const dir = s.need > s.coinsGot && s.coins.some((k) => !k.got)
|
|
222
|
+
? Math.sign(s.coins.filter((k) => !k.got).sort((a, b) => Math.abs(a.x - s.x) - Math.abs(b.x - s.x))[0].x - s.x) || 1
|
|
223
|
+
: Math.sign(s.door.x - s.x) || 1;
|
|
224
|
+
// look as far ahead as the runner goes in a quarter of a second (at least a tile and a half)
|
|
225
|
+
const reach = Math.max(1.5, Math.abs(s.vx) * 0.25 + 0.6), row = Math.floor(s.y), feet = Math.floor(s.y + H / 2 + 0.1);
|
|
226
|
+
const cols = []; for (let d = W / 2 + 0.2; d <= W / 2 + reach; d += 0.5) cols.push(Math.floor(s.x + dir * d));
|
|
227
|
+
const near = [...new Set(cols)];
|
|
228
|
+
const wall = near.slice(0, 2).some((c) => tile(s, c, row) === 1 || tile(s, c, row - 1) === 1);
|
|
229
|
+
const gap = near.some((c) => { for (let k = 0; k < 4; k++) { const t = tile(s, c, feet + k); if (t === 1 || t === 2) return false; if (t === 3) return true; } return true; });
|
|
230
|
+
const spikes = near.some((c) => tile(s, c, row) === 3 || tile(s, c, feet) === 3);
|
|
231
|
+
const walker = s.enemies.some((e) => e.alive && Math.sign(e.x - s.x) === dir && Math.abs(e.x - s.x) < 2.4 && Math.abs(e.y - s.y) < 1.2);
|
|
232
|
+
const doorAbove = Math.abs(s.door.x - s.x) < 2 && s.door.y < s.y - 1;
|
|
233
|
+
return { dir, wall, gap, spikes, walker, doorAbove, onGround: s.onGround };
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/** Easier and harder versions of a level, the smallest change first (play()'s fixes, the editor's buttons). */
|
|
237
|
+
export function easier(lv) {
|
|
238
|
+
const out = [];
|
|
239
|
+
if (lv.time) out.push({ change: { time: Math.round(lv.time * 1.5) }, say: `time ${lv.time} → ${Math.round(lv.time * 1.5)} s` });
|
|
240
|
+
const map = lv.map ?? [];
|
|
241
|
+
if (/[E^]/.test(map.join(''))) out.push({ change: { map: map.map((r) => r.replace(/[E^]/g, ' ')) }, say: 'without its walkers and spikes' });
|
|
242
|
+
if (lv.coins) out.push({ change: { coins: Math.max(0, lv.coins - 2) }, say: `coins asked ${lv.coins} → ${Math.max(0, lv.coins - 2)}` });
|
|
243
|
+
return out;
|
|
244
|
+
}
|
|
245
|
+
export function harder(lv) {
|
|
246
|
+
const map = (lv.map ?? []).map(String), out = [];
|
|
247
|
+
// a walker on the ground where there is room, away from the start and the door
|
|
248
|
+
const ground = map.length - 1, row = map[ground - 1] ?? '';
|
|
249
|
+
const spots = [...row].map((c, x) => (c === ' ' && map[ground][x] === '#' && x > 4 && x < row.length - 4 ? x : -1)).filter((x) => x >= 0);
|
|
250
|
+
if (spots.length) { const x = spots[Math.floor(spots.length / 2)]; const m = [...map]; m[ground - 1] = row.slice(0, x) + 'E' + row.slice(x + 1); out.push({ change: { map: m }, say: 'a walker more' }); }
|
|
251
|
+
if (lv.time) out.push({ change: { time: Math.round(lv.time * 0.8) }, say: `time ${lv.time} → ${Math.round(lv.time * 0.8)} s` });
|
|
252
|
+
return out;
|
|
253
|
+
}
|