@nodetool-ai/game-runtime 0.8.19 → 0.8.21

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.
Files changed (64) hide show
  1. package/dist/.nodetool-build-stamp +1 -1
  2. package/dist/adventure.d.ts +42 -0
  3. package/dist/adventure.d.ts.map +1 -0
  4. package/dist/adventure.js +733 -0
  5. package/dist/adventure.js.map +1 -0
  6. package/dist/index.d.ts +1 -0
  7. package/dist/index.d.ts.map +1 -1
  8. package/dist/index.js +1 -0
  9. package/dist/index.js.map +1 -1
  10. package/dist/native-browser/assets.d.ts +19 -0
  11. package/dist/native-browser/assets.d.ts.map +1 -0
  12. package/dist/native-browser/assets.js +70 -0
  13. package/dist/native-browser/assets.js.map +1 -0
  14. package/dist/native-browser/index.d.ts +6 -0
  15. package/dist/native-browser/index.d.ts.map +1 -0
  16. package/dist/native-browser/index.js +5 -0
  17. package/dist/native-browser/index.js.map +1 -0
  18. package/dist/native-browser/input.d.ts +70 -0
  19. package/dist/native-browser/input.d.ts.map +1 -0
  20. package/dist/native-browser/input.js +298 -0
  21. package/dist/native-browser/input.js.map +1 -0
  22. package/dist/native-browser/saves.d.ts +37 -0
  23. package/dist/native-browser/saves.d.ts.map +1 -0
  24. package/dist/native-browser/saves.js +187 -0
  25. package/dist/native-browser/saves.js.map +1 -0
  26. package/dist/native-browser/session.d.ts +46 -0
  27. package/dist/native-browser/session.d.ts.map +1 -0
  28. package/dist/native-browser/session.js +206 -0
  29. package/dist/native-browser/session.js.map +1 -0
  30. package/dist/native-browser/wasm.d.ts +28 -0
  31. package/dist/native-browser/wasm.d.ts.map +1 -0
  32. package/dist/native-browser/wasm.js +68 -0
  33. package/dist/native-browser/wasm.js.map +1 -0
  34. package/dist/native-browser/worker.d.ts +8 -0
  35. package/dist/native-browser/worker.d.ts.map +1 -0
  36. package/dist/native-browser/worker.js +109 -0
  37. package/dist/native-browser/worker.js.map +1 -0
  38. package/dist/native-editor-client.d.ts +1283 -0
  39. package/dist/native-editor-client.d.ts.map +1 -0
  40. package/dist/native-editor-client.js +106 -0
  41. package/dist/native-editor-client.js.map +1 -0
  42. package/dist/native-game-export.mjs +112 -0
  43. package/dist/native-game-notices.txt +934 -0
  44. package/dist/native-game-web-export.mjs +125 -0
  45. package/dist/native-json-save-files.d.ts +8 -0
  46. package/dist/native-json-save-files.d.ts.map +1 -0
  47. package/dist/native-json-save-files.js +95 -0
  48. package/dist/native-json-save-files.js.map +1 -0
  49. package/dist/native-template.d.ts +14 -0
  50. package/dist/native-template.d.ts.map +1 -0
  51. package/dist/native-template.js +99 -0
  52. package/dist/native-template.js.map +1 -0
  53. package/dist/native-worker.d.ts +36 -0
  54. package/dist/native-worker.d.ts.map +1 -0
  55. package/dist/native-worker.js +158 -0
  56. package/dist/native-worker.js.map +1 -0
  57. package/dist/native.d.ts +49 -0
  58. package/dist/native.d.ts.map +1 -0
  59. package/dist/native.js +305 -0
  60. package/dist/native.js.map +1 -0
  61. package/dist/systems/presentation2d.d.ts.map +1 -1
  62. package/dist/systems/presentation2d.js +3 -1
  63. package/dist/systems/presentation2d.js.map +1 -1
  64. package/package.json +32 -7
@@ -0,0 +1,733 @@
1
+ /**
2
+ * The guided Game flow's top-down adventure: a generated dungeon built from a
3
+ * design's layout choices.
4
+ *
5
+ * {@link createAdventureGame} lays out rooms joined by corridors on a tile
6
+ * grid, then fills them: gems to collect, enemies that patrol or chase,
7
+ * hazards that hurt, and a sealed exit that opens once every gem is taken.
8
+ * The player has health, a hurt flash and knockback. Losing all health
9
+ * restarts the level and reaching the open exit wins it. Everything is pure
10
+ * and seeded, so one design always builds the same level.
11
+ *
12
+ * The document starts on the `builtin:` placeholders. Once the flow has drawn
13
+ * the art, {@link bindAdventureArt} reads the frame and tile rectangles the
14
+ * asset preparation wrote and points the sprites, animations and wall tiles
15
+ * at them, and adds the level music when a track was generated.
16
+ */
17
+ import { gameDocument } from "@nodetool-ai/protocol";
18
+ /** The scene the adventure plays in. A lost run transitions back into it. */
19
+ export const ADVENTURE_SCENE_ID = "level";
20
+ /** Animations of each adventure spritesheet slot, in sheet row order. */
21
+ export const ADVENTURE_SHEETS = {
22
+ player: { idle: 1, walk: 4 },
23
+ enemy: { idle: 2, move: 2 },
24
+ gem: { idle: 1 },
25
+ hazard: { idle: 1 },
26
+ exit: { closed: 1, open: 1 }
27
+ };
28
+ const CELL = 32;
29
+ const ROOM_CELL_WIDTH = 13;
30
+ const ROOM_CELL_HEIGHT = 11;
31
+ const GRID = {
32
+ small: { cols: 3, rows: 2, gems: 5 },
33
+ medium: { cols: 3, rows: 3, gems: 7 },
34
+ large: { cols: 4, rows: 3, gems: 9 }
35
+ };
36
+ const TUNING = {
37
+ relaxed: { health: 5, enemiesPerRoom: 0.6, hazardsPerRoom: 0.6, chaseShare: 0.3, patrolSpeed: 1.6, chaseSpeed: 2, sight: 4.5 },
38
+ normal: { health: 4, enemiesPerRoom: 0.9, hazardsPerRoom: 1, chaseShare: 0.5, patrolSpeed: 2, chaseSpeed: 2.5, sight: 5.5 },
39
+ hard: { health: 3, enemiesPerRoom: 1.3, hazardsPerRoom: 1.6, chaseShare: 0.65, patrolSpeed: 2.4, chaseSpeed: 3, sight: 6.5 }
40
+ };
41
+ /** A small, fast, seeded generator (mulberry32). */
42
+ function seededRandom(seed) {
43
+ let state = seed >>> 0;
44
+ return () => {
45
+ state = (state + 0x6d2b79f5) >>> 0;
46
+ let value = state;
47
+ value = Math.imul(value ^ (value >>> 15), value | 1);
48
+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
49
+ return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
50
+ };
51
+ }
52
+ /** A stable seed for a piece of text, such as the design's title. */
53
+ export function adventureSeed(text) {
54
+ let hash = 2166136261;
55
+ for (let index = 0; index < text.length; index += 1) {
56
+ hash = Math.imul(hash ^ text.charCodeAt(index), 16777619);
57
+ }
58
+ return hash >>> 0;
59
+ }
60
+ const centerOf = (room) => ({
61
+ x: Math.floor((room.left + room.right) / 2),
62
+ y: Math.floor((room.top + room.bottom) / 2)
63
+ });
64
+ function carve(floor, x0, y0, x1, y1) {
65
+ for (let y = Math.min(y0, y1); y <= Math.max(y0, y1); y += 1) {
66
+ for (let x = Math.min(x0, x1); x <= Math.max(x0, x1); x += 1) {
67
+ floor[y][x] = true;
68
+ }
69
+ }
70
+ }
71
+ /** A two-tile-wide corridor between two room centres: across, then down, then across. */
72
+ function corridor(floor, from, to, horizontal) {
73
+ const a = centerOf(from);
74
+ const b = centerOf(to);
75
+ if (horizontal) {
76
+ const middle = Math.floor((a.x + b.x) / 2);
77
+ carve(floor, a.x, a.y, middle, a.y + 1);
78
+ carve(floor, middle, a.y, middle + 1, b.y + 1);
79
+ carve(floor, middle, b.y, b.x, b.y + 1);
80
+ }
81
+ else {
82
+ const middle = Math.floor((a.y + b.y) / 2);
83
+ carve(floor, a.x, a.y, a.x + 1, middle);
84
+ carve(floor, a.x, middle, b.x + 1, middle + 1);
85
+ carve(floor, b.x, middle, b.x + 1, b.y);
86
+ }
87
+ }
88
+ function generateLayout(size, random) {
89
+ const { cols, rows } = GRID[size];
90
+ const width = cols * ROOM_CELL_WIDTH + 2;
91
+ const height = rows * ROOM_CELL_HEIGHT + 2;
92
+ const floor = Array.from({ length: height }, () => Array.from({ length: width }, () => false));
93
+ const between = (low, high) => low + Math.floor(random() * (high - low + 1));
94
+ const rooms = [];
95
+ for (let row = 0; row < rows; row += 1) {
96
+ for (let col = 0; col < cols; col += 1) {
97
+ const roomWidth = between(6, 10);
98
+ const roomHeight = between(5, 8);
99
+ const left = 1 + col * ROOM_CELL_WIDTH + between(1, ROOM_CELL_WIDTH - roomWidth - 1);
100
+ const top = 1 + row * ROOM_CELL_HEIGHT + between(1, ROOM_CELL_HEIGHT - roomHeight - 1);
101
+ const room = { col, row, left, top, right: left + roomWidth - 1, bottom: top + roomHeight - 1 };
102
+ rooms.push(room);
103
+ carve(floor, room.left, room.top, room.right, room.bottom);
104
+ }
105
+ }
106
+ const at = (col, row) => col >= 0 && row >= 0 && col < cols && row < rows ? rooms[row * cols + col] : undefined;
107
+ const key = (a, b) => [a.row * cols + a.col, b.row * cols + b.col].sort((x, y) => x - y).join(":");
108
+ const links = new Map();
109
+ const neighbours = (room) => [at(room.col + 1, room.row), at(room.col - 1, room.row), at(room.col, room.row + 1), at(room.col, room.row - 1)]
110
+ .filter((entry) => entry !== undefined);
111
+ // A random spanning tree over the room grid, so every room is reachable.
112
+ const corners = [at(0, 0), at(cols - 1, 0), at(0, rows - 1), at(cols - 1, rows - 1)].filter((entry) => entry !== undefined);
113
+ const start = corners[Math.floor(random() * corners.length)];
114
+ const visited = new Set([start]);
115
+ const stack = [start];
116
+ while (stack.length > 0) {
117
+ const current = stack[stack.length - 1];
118
+ const open = neighbours(current).filter((room) => !visited.has(room));
119
+ if (open.length === 0) {
120
+ stack.pop();
121
+ continue;
122
+ }
123
+ const next = open[Math.floor(random() * open.length)];
124
+ links.set(key(current, next), [current, next]);
125
+ visited.add(next);
126
+ stack.push(next);
127
+ }
128
+ // A few extra doors make loops, so a chaser can be led around.
129
+ const extra = 1 + Math.floor(rooms.length / 4);
130
+ for (let attempt = 0; attempt < extra * 6 && links.size < rooms.length - 1 + extra; attempt += 1) {
131
+ const room = rooms[Math.floor(random() * rooms.length)];
132
+ const options = neighbours(room).filter((other) => !links.has(key(room, other)));
133
+ const other = options[Math.floor(random() * options.length)];
134
+ if (other) {
135
+ links.set(key(room, other), [room, other]);
136
+ }
137
+ }
138
+ for (const [a, b] of links.values()) {
139
+ corridor(floor, a, b, a.row === b.row);
140
+ }
141
+ // Rooms by link distance from the start: the exit goes in the farthest one.
142
+ const distance = new Map([[start, 0]]);
143
+ const queue = [start];
144
+ while (queue.length > 0) {
145
+ const current = queue.shift();
146
+ for (const [a, b] of links.values()) {
147
+ const other = a === current ? b : b === current ? a : undefined;
148
+ if (other && !distance.has(other)) {
149
+ distance.set(other, distance.get(current) + 1);
150
+ queue.push(other);
151
+ }
152
+ }
153
+ }
154
+ const byDistance = [...rooms].sort((a, b) => distance.get(a) - distance.get(b));
155
+ return { width, height, floor, rooms, start, exit: byDistance[byDistance.length - 1], byDistance };
156
+ }
157
+ const PLAYER_SCRIPT = `(input) => {
158
+ const { tick, pressed, events, entity, params } = input;
159
+ const me = entity.id;
160
+ const s = input.state ?? { hp: params.health, gems: 0, taken: [], hurt: 0, knockX: 0, knockY: 0, dead: 0,
161
+ won: false, open: false, goal: false, anim: "", noteUntil: 0, sealedAt: -999 };
162
+ const commands = [];
163
+ const ui = (id, fields) => commands.push({ kind: "ui", id, ...fields });
164
+ const note = (text, ticks) => { ui("hud-note", { text, visible: true }); s.noteUntil = ticks > 0 ? tick + ticks : 0; };
165
+ if (tick <= 1) {
166
+ commands.push({ kind: "hud", id: "score", text: " ", x: 0, y: 0 });
167
+ commands.push({ kind: "hud", id: "win", text: " ", x: 0, y: 0 });
168
+ ui("hud-health", { value: s.hp, max: params.health });
169
+ ui("hud-gems", { text: "0 / " + params.gems });
170
+ note(entity.props.title, 180);
171
+ }
172
+ const hit = (other) => {
173
+ if (s.hurt > 0 || s.dead > 0 || s.won) return;
174
+ s.hp -= 1;
175
+ s.hurt = 70;
176
+ const source = world.get(other);
177
+ let dx = source ? entity.x - source.x : 0;
178
+ let dy = source ? entity.y - source.y : 1;
179
+ const length = Math.hypot(dx, dy) || 1;
180
+ s.knockX = (dx / length) * 9;
181
+ s.knockY = (dy / length) * 9;
182
+ commands.push({ kind: "emit", event: "hurt" });
183
+ commands.push({ kind: "emitParticles", emitter: "hurt", count: 18 });
184
+ ui("hud-health", { value: Math.max(0, s.hp) });
185
+ if (s.hp <= 0) {
186
+ s.dead = 1;
187
+ commands.push({ kind: "emit", event: "lose" });
188
+ note("You were caught. Starting over...", 0);
189
+ }
190
+ };
191
+ const seen = new Set();
192
+ for (const event of events) {
193
+ if (event.kind === "win") {
194
+ s.won = true;
195
+ note("Level cleared!", 0);
196
+ ui("hud-goal", { text: "You made it out with every gem." });
197
+ commands.push({ kind: "emitParticles", emitter: "sparkle", count: 40 });
198
+ }
199
+ if (event.kind !== "contact" || event.phase === "exit") continue;
200
+ const other = event.entityId === me ? event.otherId : event.otherId === me ? event.entityId : "";
201
+ if (!other || seen.has(other)) continue;
202
+ seen.add(other);
203
+ if (other.startsWith("gem") && !s.taken.includes(other) && s.dead === 0) {
204
+ s.taken.push(other);
205
+ s.gems += 1;
206
+ commands.push({ kind: "despawn", entityId: other });
207
+ commands.push({ kind: "emit", event: "gem" });
208
+ commands.push({ kind: "emitParticles", emitter: "sparkle", count: 16 });
209
+ ui("hud-gems", { text: s.gems + " / " + params.gems });
210
+ if (s.gems >= params.gems && !s.open) {
211
+ s.open = true;
212
+ commands.push({ kind: "emit", event: "unlock" });
213
+ note("The exit is open!", 150);
214
+ ui("hud-goal", { text: "Every gem found. Get to the exit!" });
215
+ }
216
+ } else if (other.startsWith("enemy") || other.startsWith("hazard")) {
217
+ hit(other);
218
+ } else if (other === "exit" && !s.won && s.dead === 0) {
219
+ if (s.open && !s.goal) {
220
+ s.goal = true;
221
+ commands.push({ kind: "spawn", prefabId: "goal", x: entity.x, y: entity.y });
222
+ } else if (!s.open && tick - s.sealedAt > 120) {
223
+ s.sealedAt = tick;
224
+ note("Sealed. " + (params.gems - s.gems) + " gems still to find.", 120);
225
+ }
226
+ }
227
+ }
228
+ if (s.noteUntil > 0 && tick >= s.noteUntil) {
229
+ s.noteUntil = 0;
230
+ ui("hud-note", { visible: false });
231
+ }
232
+ let vx = 0;
233
+ let vy = 0;
234
+ if (s.dead > 0) {
235
+ s.dead += 1;
236
+ if (s.dead > 150) commands.push({ kind: "sceneTransition", sceneId: "${ADVENTURE_SCENE_ID}" });
237
+ } else if (!s.won) {
238
+ const x = (pressed.includes("right") ? 1 : 0) - (pressed.includes("left") ? 1 : 0);
239
+ const y = (pressed.includes("up") ? 1 : 0) - (pressed.includes("down") ? 1 : 0);
240
+ const length = Math.hypot(x, y) || 1;
241
+ vx = (x / length) * params.speed;
242
+ vy = (y / length) * params.speed;
243
+ }
244
+ if (Math.abs(s.knockX) + Math.abs(s.knockY) > 0.05) {
245
+ vx += s.knockX;
246
+ vy += s.knockY;
247
+ s.knockX *= 0.8;
248
+ s.knockY *= 0.8;
249
+ } else {
250
+ s.knockX = 0;
251
+ s.knockY = 0;
252
+ }
253
+ commands.push({ kind: "setVelocity", x: vx, y: vy });
254
+ const anim = Math.abs(vx) + Math.abs(vy) > 0.1 ? "walk" : "idle";
255
+ if (anim !== s.anim) {
256
+ s.anim = anim;
257
+ commands.push({ kind: "playAnimation", clip: anim });
258
+ }
259
+ if (s.hurt > 0) {
260
+ s.hurt -= 1;
261
+ commands.push({ kind: "setVisual", opacity: s.hurt === 0 || Math.floor(s.hurt / 4) % 2 === 0 ? 1 : 0.35,
262
+ tint: s.hurt > 55 ? "#ff8080" : "#ffffff" });
263
+ }
264
+ if (vx !== 0) commands.push({ kind: "setVisual", flipX: vx < 0 });
265
+ return { state: s, commands };
266
+ }`;
267
+ const ENEMY_SCRIPT = `(input) => {
268
+ const { tick, entity, params, random } = input;
269
+ const p = entity.props;
270
+ const s = input.state ?? { dir: random() < 0.5 ? -1 : 1, chasing: false, anim: "", wait: 0 };
271
+ const commands = [];
272
+ let vx = 0;
273
+ let vy = 0;
274
+ if (params.mode === "chase") {
275
+ const hero = world.get("player");
276
+ const dx = hero ? hero.x - entity.x : 0;
277
+ const dy = hero ? hero.y - entity.y : 0;
278
+ const distance = Math.hypot(dx, dy);
279
+ if (hero && distance < params.sight) s.chasing = true;
280
+ if (s.chasing && (!hero || distance > params.sight * 1.8)) s.chasing = false;
281
+ if (s.chasing && distance > 0.05) {
282
+ vx = (dx / distance) * params.speed;
283
+ vy = (dy / distance) * params.speed;
284
+ } else {
285
+ const hx = p.homeX - entity.x;
286
+ const hy = p.homeY - entity.y;
287
+ const home = Math.hypot(hx, hy);
288
+ if (home > 0.2) {
289
+ vx = (hx / home) * params.speed * 0.6;
290
+ vy = (hy / home) * params.speed * 0.6;
291
+ }
292
+ }
293
+ } else {
294
+ const along = p.axis === "x" ? entity.x : entity.y;
295
+ const blocked = p.axis === "x" ? (s.dir > 0 ? entity.touching.right : entity.touching.left)
296
+ : (s.dir > 0 ? entity.touching.up : entity.touching.down);
297
+ if (s.wait > 0) {
298
+ s.wait -= 1;
299
+ } else if (blocked || (s.dir > 0 && along >= p.max) || (s.dir < 0 && along <= p.min)) {
300
+ s.dir = -s.dir;
301
+ s.wait = 20;
302
+ } else if (p.axis === "x") {
303
+ vx = s.dir * params.speed;
304
+ } else {
305
+ vy = s.dir * params.speed;
306
+ }
307
+ }
308
+ commands.push({ kind: "setVelocity", x: vx, y: vy });
309
+ const anim = Math.abs(vx) + Math.abs(vy) > 0.1 ? "move" : "idle";
310
+ if (anim !== s.anim) {
311
+ s.anim = anim;
312
+ commands.push({ kind: "playAnimation", clip: anim });
313
+ }
314
+ if (Math.abs(vx) > 0.1) commands.push({ kind: "setVisual", flipX: vx < 0 });
315
+ return { state: s, commands };
316
+ }`;
317
+ const EXIT_SCRIPT = `(input) => {
318
+ const s = input.state ?? { open: false };
319
+ const commands = [];
320
+ if (!s.open && input.events.some((event) => event.kind === "trigger" && event.event === "unlock")) {
321
+ s.open = true;
322
+ commands.push({ kind: "playAnimation", clip: "open" });
323
+ commands.push({ kind: "emitParticles", emitter: "swirl" });
324
+ commands.push({ kind: "setVisual", tint: "#ffffff" });
325
+ }
326
+ return { state: s, commands };
327
+ }`;
328
+ function cameraScript(minX, maxX, minY, maxY) {
329
+ return `(input) => {
330
+ const { entity, events, random } = input;
331
+ const s = input.state ?? { x: entity.x, y: entity.y, shake: 0 };
332
+ for (const event of events) {
333
+ if (event.kind === "trigger" && event.event === "hurt") s.shake = Math.max(s.shake, 0.35);
334
+ if (event.kind === "trigger" && event.event === "unlock") s.shake = Math.max(s.shake, 0.2);
335
+ }
336
+ const hero = world.get("player");
337
+ if (hero) {
338
+ s.x += (hero.x - s.x) * 0.12;
339
+ s.y += (hero.y - s.y) * 0.12;
340
+ }
341
+ s.x = Math.max(${minX}, Math.min(${maxX}, s.x));
342
+ s.y = Math.max(${minY}, Math.min(${maxY}, s.y));
343
+ const x = s.x + (random() * 2 - 1) * s.shake;
344
+ const y = s.y + (random() * 2 - 1) * s.shake;
345
+ s.shake *= 0.85;
346
+ if (s.shake < 0.01) s.shake = 0;
347
+ return { state: s, commands: [{ kind: "setPosition", x, y }] };
348
+ }`;
349
+ }
350
+ /** Frame rectangles of a placeholder sheet, row-major, one row per animation. */
351
+ function nominalClips(slot) {
352
+ const animations = ADVENTURE_SHEETS[slot] ?? { idle: 1 };
353
+ const clips = {};
354
+ Object.entries(animations).forEach(([name, count], row) => {
355
+ clips[name] = {
356
+ frames: Array.from({ length: count }, (_, col) => ({ x: col * CELL, y: row * CELL, width: CELL, height: CELL })),
357
+ ticksPerFrame: name === "walk" || name === "move" ? 8 : 20,
358
+ loop: true
359
+ };
360
+ });
361
+ return clips;
362
+ }
363
+ function animatorFor(slot, first) {
364
+ const clips = nominalClips(slot);
365
+ const clip = clips[first];
366
+ return { frames: clip.frames, ticksPerFrame: clip.ticksPerFrame, loop: true, clips };
367
+ }
368
+ const placeholder = (slot, mediaKind) => mediaKind
369
+ ? { assetId: `builtin:${slot}`, digest: `builtin:${slot}-v1`, mediaKind, width: 1, height: 1 }
370
+ : { assetId: `builtin:${slot}`, digest: `builtin:${slot}-v1`, width: CELL, height: CELL };
371
+ /** Build a playable top-down adventure. */
372
+ export function createAdventureGame(id, options = {}) {
373
+ const size = options.size ?? "medium";
374
+ const difficulty = options.difficulty ?? "normal";
375
+ const tuning = TUNING[difficulty];
376
+ const random = seededRandom(options.seed ?? adventureSeed(options.title ?? id));
377
+ const layout = generateLayout(size, random);
378
+ const { width, height, floor } = layout;
379
+ // Tile (x, y) has its centre at world (x - width / 2 + 0.5, height / 2 - y - 0.5).
380
+ const worldX = (x) => x - width / 2 + 0.5;
381
+ const worldY = (y) => height / 2 - y - 0.5;
382
+ const isFloor = (x, y) => floor[y]?.[x] === true;
383
+ const floorTiles = [];
384
+ const wallTiles = [];
385
+ for (let y = 0; y < height; y += 1) {
386
+ for (let x = 0; x < width; x += 1) {
387
+ if (isFloor(x, y)) {
388
+ floorTiles.push({ x: worldX(x), y: worldY(y), width: 1, height: 1 });
389
+ continue;
390
+ }
391
+ // Solid ground fills every cell between the rooms, so no void shows on screen.
392
+ wallTiles.push({ x: worldX(x), y: worldY(y), width: 1, height: 1 });
393
+ }
394
+ }
395
+ // Free interior tiles of a room: floor on every side, so nothing blocks a doorway.
396
+ const used = new Set();
397
+ const freeTiles = (room) => {
398
+ const tiles = [];
399
+ for (let y = room.top + 1; y < room.bottom; y += 1) {
400
+ for (let x = room.left + 1; x < room.right; x += 1) {
401
+ if (!used.has(`${x},${y}`)) {
402
+ tiles.push({ x, y });
403
+ }
404
+ }
405
+ }
406
+ return tiles;
407
+ };
408
+ const take = (room, spread = 1) => {
409
+ const tiles = freeTiles(room);
410
+ if (tiles.length === 0) {
411
+ return null;
412
+ }
413
+ const tile = tiles[Math.floor(random() * tiles.length)];
414
+ for (let dy = -spread; dy <= spread; dy += 1) {
415
+ for (let dx = -spread; dx <= spread; dx += 1) {
416
+ used.add(`${tile.x + dx},${tile.y + dy}`);
417
+ }
418
+ }
419
+ return tile;
420
+ };
421
+ const startTile = centerOf(layout.start);
422
+ for (let dy = -2; dy <= 2; dy += 1) {
423
+ for (let dx = -2; dx <= 2; dx += 1) {
424
+ used.add(`${startTile.x + dx},${startTile.y + dy}`);
425
+ }
426
+ }
427
+ const exitTile = centerOf(layout.exit);
428
+ for (let dy = -1; dy <= 1; dy += 1) {
429
+ for (let dx = -1; dx <= 1; dx += 1) {
430
+ used.add(`${exitTile.x + dx},${exitTile.y + dy}`);
431
+ }
432
+ }
433
+ const away = layout.byDistance.slice(1);
434
+ const entities = [];
435
+ const entity = (value) => {
436
+ entities.push(value);
437
+ };
438
+ const halfWidth = 10;
439
+ const halfHeight = 5.625;
440
+ const minX = -width / 2 + halfWidth;
441
+ const maxX = width / 2 - halfWidth;
442
+ const minY = -height / 2 + halfHeight;
443
+ const maxY = height / 2 - halfHeight;
444
+ const clampCamera = (low, high) => (low > high ? [0, 0] : [low, high]);
445
+ const [cameraMinX, cameraMaxX] = clampCamera(minX, maxX);
446
+ const [cameraMinY, cameraMaxY] = clampCamera(minY, maxY);
447
+ entity({
448
+ id: "camera", name: "Camera",
449
+ transform2d: { x: worldX(startTile.x), y: worldY(startTile.y) },
450
+ camera2d: { width: 20, height: 11.25 },
451
+ behaviors: [{ kind: "script", source: cameraScript(cameraMinX, cameraMaxX, cameraMinY, cameraMaxY), maxCommands: 1 }],
452
+ particles: { emitters: [{
453
+ id: "dust", rate: 6, maxParticles: 96, shape: { kind: "box", size: { x: 22, y: 13 } },
454
+ lifetime: { min: 5, max: 9 }, speed: { min: 0.03, max: 0.15 }, size: { min: 0.03, max: 0.07 },
455
+ color: { min: "#c9b48a", max: "#fff1cf" }, opacity: 0.55,
456
+ opacityOverLifetime: [{ t: 0, value: 0 }, { t: 0.2, value: 1 }, { t: 0.8, value: 0.7 }, { t: 1, value: 0 }],
457
+ gravity: { x: 0.01, y: 0.02 }, blend: "additive", unlit: true, layer: 9
458
+ }] }
459
+ });
460
+ entity({
461
+ id: "floor", name: "Floor", transform2d: { x: 0, y: 0 },
462
+ tilemap: { assetId: "floor", tiles: floorTiles, layer: -10 }
463
+ });
464
+ entity({
465
+ id: "walls", name: "Walls", transform2d: { x: 0, y: 0 },
466
+ tilemap: { assetId: "wall", tiles: wallTiles, layer: -5, solid: true }
467
+ });
468
+ const gemCount = GRID[size].gems;
469
+ entity({
470
+ id: "player", name: "Player", tags: ["hero"], props: { title: options.title?.trim() || "Find every gem" },
471
+ transform2d: { x: worldX(startTile.x), y: worldY(startTile.y) },
472
+ sprite: { assetId: "player", width: 1.1, height: 1.1, layer: 3, frame: nominalClips("player")["idle"].frames[0] },
473
+ animator: animatorFor("player", "idle"),
474
+ body2d: { type: "kinematic" },
475
+ collider2d: { width: 0.62, height: 0.62 },
476
+ light2d: { color: "#ffd9a0", intensity: 1.2, radius: 5.5, falloff: 1.4 },
477
+ behaviors: [
478
+ {
479
+ kind: "script", source: PLAYER_SCRIPT, maxCommands: 32,
480
+ params: {
481
+ speed: { type: "number", default: 4.2, minimum: 1, maximum: 12 },
482
+ health: { type: "number", default: tuning.health, minimum: 1, maximum: 20, integer: true },
483
+ gems: { type: "number", default: gemCount, minimum: 1, maximum: 64, integer: true }
484
+ }
485
+ },
486
+ { kind: "winWhenCollected", count: 1 }
487
+ ],
488
+ particles: { emitters: [
489
+ {
490
+ id: "sparkle", playOnStart: false, loop: false, rate: 0, maxParticles: 128,
491
+ shape: { kind: "circle", radius: 0.2 }, lifetime: { min: 0.4, max: 0.9 }, speed: { min: 1.5, max: 4 },
492
+ size: { min: 0.06, max: 0.14 }, color: { min: "#ffd25a", max: "#fff6c8" }, drag: 2.5,
493
+ opacityOverLifetime: [{ t: 0, value: 1 }, { t: 1, value: 0 }], blend: "additive", unlit: true, layer: 6
494
+ },
495
+ {
496
+ id: "hurt", playOnStart: false, loop: false, rate: 0, maxParticles: 64,
497
+ shape: { kind: "circle", radius: 0.2 }, lifetime: { min: 0.3, max: 0.6 }, speed: { min: 2, max: 5 },
498
+ size: { min: 0.06, max: 0.12 }, color: { min: "#ff3b3b", max: "#ff9a7a" }, drag: 3,
499
+ opacityOverLifetime: [{ t: 0, value: 1 }, { t: 1, value: 0 }], blend: "additive", unlit: true, layer: 6
500
+ }
501
+ ] }
502
+ });
503
+ // Gems spread over every room but the start, the far rooms first.
504
+ for (let index = 0; index < gemCount; index += 1) {
505
+ const room = away[index % away.length];
506
+ const tile = take(room);
507
+ if (!tile) {
508
+ continue;
509
+ }
510
+ entity({
511
+ id: `gem${index}`, name: `Gem ${index + 1}`, tags: ["gem"],
512
+ transform2d: { x: worldX(tile.x), y: worldY(tile.y) },
513
+ sprite: { assetId: "gem", width: 0.75, height: 0.75, layer: 2 },
514
+ collider2d: { width: 0.6, height: 0.6, sensor: true },
515
+ light2d: { color: "#ffcf5a", intensity: 0.9, radius: 1.8, falloff: 1.5 },
516
+ visualAnimation: { tracks: [
517
+ { property: "scaleX", from: 0.9, to: 1.08, durationTicks: 40 + (index % 3) * 6, repeat: true, pingPong: true, easing: "easeInOut" },
518
+ { property: "scaleY", from: 0.9, to: 1.08, durationTicks: 40 + (index % 3) * 6, repeat: true, pingPong: true, easing: "easeInOut" }
519
+ ] }
520
+ });
521
+ }
522
+ // The real count, in case a cramped room had no free tile.
523
+ const placedGems = entities.filter((entry) => entry.id.startsWith("gem")).length;
524
+ const player = entities.find((entry) => entry.id === "player");
525
+ const playerScript = player.behaviors[0];
526
+ if (playerScript?.kind === "script" && playerScript.params?.["gems"]?.type === "number") {
527
+ playerScript.params["gems"] = { ...playerScript.params["gems"], default: placedGems };
528
+ }
529
+ const enemyCount = Math.max(1, Math.round(away.length * tuning.enemiesPerRoom));
530
+ for (let index = 0; index < enemyCount; index += 1) {
531
+ const room = away[(index * 2 + 1) % away.length];
532
+ const tile = take(room, 2);
533
+ if (!tile) {
534
+ continue;
535
+ }
536
+ const chase = random() < tuning.chaseShare;
537
+ const axis = room.right - room.left >= room.bottom - room.top ? "x" : "y";
538
+ const bounds = axis === "x"
539
+ ? { min: worldX(room.left) + 0.5, max: worldX(room.right) - 0.5 }
540
+ : { min: worldY(room.bottom) + 0.5, max: worldY(room.top) - 0.5 };
541
+ const sprite = { assetId: "enemy", width: 1, height: 1, layer: 3, frame: nominalClips("enemy")["idle"].frames[0] };
542
+ if (chase) {
543
+ sprite.tint = "#ffc4c4";
544
+ }
545
+ entity({
546
+ id: `enemy${index}`, name: chase ? `Hunter ${index + 1}` : `Patroller ${index + 1}`, tags: ["enemy"],
547
+ props: { axis, min: bounds.min, max: bounds.max, homeX: worldX(tile.x), homeY: worldY(tile.y) },
548
+ transform2d: { x: worldX(tile.x), y: worldY(tile.y) },
549
+ sprite,
550
+ animator: animatorFor("enemy", "idle"),
551
+ body2d: { type: "kinematic" },
552
+ collider2d: { width: 0.7, height: 0.7 },
553
+ behaviors: [{
554
+ kind: "script", source: ENEMY_SCRIPT, maxCommands: 8,
555
+ params: {
556
+ mode: { type: "enum", options: chase ? ["chase", "patrol"] : ["patrol", "chase"] },
557
+ speed: { type: "number", default: chase ? tuning.chaseSpeed : tuning.patrolSpeed, minimum: 0.5, maximum: 10 },
558
+ sight: { type: "number", default: tuning.sight, minimum: 1, maximum: 20 }
559
+ }
560
+ }]
561
+ });
562
+ }
563
+ const hazardCount = Math.round(away.length * tuning.hazardsPerRoom);
564
+ for (let index = 0; index < hazardCount; index += 1) {
565
+ const room = away[(index * 3) % away.length];
566
+ const tile = take(room);
567
+ if (!tile) {
568
+ continue;
569
+ }
570
+ entity({
571
+ id: `hazard${index}`, name: `Hazard ${index + 1}`, tags: ["hazard"],
572
+ transform2d: { x: worldX(tile.x), y: worldY(tile.y) },
573
+ sprite: { assetId: "hazard", width: 1, height: 1, layer: -2 },
574
+ collider2d: { width: 0.7, height: 0.7, sensor: true },
575
+ light2d: { color: "#ff5a3a", intensity: 0.7, radius: 1.5, falloff: 1.6 },
576
+ particles: { emitters: [{
577
+ id: "embers", rate: 3, maxParticles: 24, shape: { kind: "box", size: { x: 0.7, y: 0.5 } },
578
+ lifetime: { min: 0.6, max: 1.2 }, speed: { min: 0.2, max: 0.6 }, size: { min: 0.03, max: 0.07 },
579
+ color: { min: "#ff6a2a", max: "#ffc070" }, gravity: { x: 0, y: 0.8 },
580
+ opacityOverLifetime: [{ t: 0, value: 1 }, { t: 1, value: 0 }], blend: "additive", unlit: true, layer: 4
581
+ }] }
582
+ });
583
+ }
584
+ entity({
585
+ id: "exit", name: "Exit", tags: ["exit"],
586
+ transform2d: { x: worldX(exitTile.x) + 0.5, y: worldY(exitTile.y) - 0.5 },
587
+ sprite: { assetId: "exit", width: 1.8, height: 1.8, layer: -1, tint: "#8a8aa8", frame: nominalClips("exit")["closed"].frames[0] },
588
+ animator: { ...animatorFor("exit", "closed"), loop: false },
589
+ collider2d: { width: 1, height: 1, sensor: true },
590
+ light2d: { color: "#9a7cff", intensity: 1.1, radius: 3.2, falloff: 1.4 },
591
+ behaviors: [{ kind: "script", source: EXIT_SCRIPT, maxCommands: 4 }],
592
+ particles: { emitters: [{
593
+ id: "swirl", playOnStart: false, loop: true, rate: 24, maxParticles: 96,
594
+ shape: { kind: "circle", radius: 0.9, fromEdge: true }, lifetime: { min: 0.8, max: 1.4 }, speed: { min: 0.2, max: 0.6 },
595
+ size: { min: 0.05, max: 0.11 }, color: { min: "#b49cff", max: "#f0e8ff" }, gravity: { x: 0, y: 0.6 },
596
+ opacityOverLifetime: [{ t: 0, value: 0 }, { t: 0.3, value: 1 }, { t: 1, value: 0 }], blend: "additive", unlit: true, layer: 5
597
+ }] }
598
+ });
599
+ entity({
600
+ id: "goal", name: "Goal (spawned at the open exit)", templateOnly: true,
601
+ transform2d: { x: 0, y: 0 },
602
+ collider2d: { width: 0.4, height: 0.4, sensor: true },
603
+ behaviors: [{ kind: "collectible", score: 1 }]
604
+ });
605
+ entity({ id: "sound-gem", name: "Gem sound", transform2d: { x: 0, y: 0 }, behaviors: [],
606
+ audioSource: { assetId: "sfx.collect", onEvent: "gem", volume: 0.7 } });
607
+ entity({ id: "sound-hurt", name: "Hurt sound", transform2d: { x: 0, y: 0 }, behaviors: [],
608
+ audioSource: { assetId: "sfx.hurt", onEvent: "hurt", volume: 0.8 } });
609
+ entity({ id: "sound-unlock", name: "Exit sound", transform2d: { x: 0, y: 0 }, behaviors: [],
610
+ audioSource: { assetId: "sfx.collect", onEvent: "unlock", volume: 1 } });
611
+ const ui = {
612
+ nodes: [
613
+ { kind: "panel", id: "hud-panel", anchor: { x: 0, y: 0 }, offset: { x: 20, y: 20 }, width: 300, height: 92, color: "#0b0d18", opacity: 0.72, cornerRadius: 16 },
614
+ { kind: "text", id: "hud-health-label", anchor: { x: 0, y: 0 }, offset: { x: 38, y: 32 }, text: "Health", size: 18, color: "#c9d1ff" },
615
+ { kind: "bar", id: "hud-health", anchor: { x: 0, y: 0 }, offset: { x: 38, y: 62 }, width: 150, height: 16, value: tuning.health, max: tuning.health, color: "#ff5a6e", background: "#3a2030" },
616
+ { kind: "text", id: "hud-gems-label", anchor: { x: 0, y: 0 }, offset: { x: 214, y: 32 }, text: "Gems", size: 18, color: "#ffe39a" },
617
+ { kind: "text", id: "hud-gems", anchor: { x: 0, y: 0 }, offset: { x: 214, y: 54 }, text: `0 / ${placedGems}`, size: 26, color: "#ffffff" },
618
+ { kind: "text", id: "hud-goal", anchor: { x: 0.5, y: 1 }, offset: { x: 0, y: -26 }, text: "Collect every gem, then reach the exit.", size: 20, color: "#e8e4ff", align: "center" },
619
+ { kind: "text", id: "hud-note", anchor: { x: 0.5, y: 0.5 }, offset: { x: 0, y: 96 }, text: "", size: 40, color: "#ffffff", align: "center", visible: false }
620
+ ]
621
+ };
622
+ return gameDocument.parse({
623
+ schemaVersion: 4,
624
+ engineVersion: "3",
625
+ id,
626
+ revision: "adventure-v1",
627
+ entrySceneId: ADVENTURE_SCENE_ID,
628
+ pixelsPerUnit: CELL,
629
+ tickRate: 60,
630
+ inputActions: ["left", "right", "up", "down"],
631
+ renderEffects: [{ kind: "bloom", threshold: 0.72, softness: 0.25, radius: 12, intensity: 0.6, required: false }],
632
+ assets: {
633
+ player: placeholder("player"),
634
+ enemy: placeholder("enemy"),
635
+ gem: placeholder("gem"),
636
+ hazard: placeholder("hazard"),
637
+ exit: placeholder("exit"),
638
+ floor: placeholder("floor"),
639
+ wall: placeholder("wall"),
640
+ "sfx.collect": placeholder("sfx.collect", "audio"),
641
+ "sfx.hurt": placeholder("sfx.hurt", "audio")
642
+ },
643
+ scenes: [{
644
+ id: ADVENTURE_SCENE_ID,
645
+ name: options.title?.trim() || "Adventure",
646
+ lighting: { ambient: { color: "#6a74a0", intensity: 0.62 }, points: [] },
647
+ ui,
648
+ entities
649
+ }]
650
+ });
651
+ }
652
+ /** Edge bits of a wall tile that faces floor, as the tileset preparation numbers them. */
653
+ function wallMask(tile, floorAt) {
654
+ const key = (x, y) => `${x},${y}`;
655
+ return (floorAt.has(key(tile.x, tile.y + 1)) ? 1 : 0) |
656
+ (floorAt.has(key(tile.x + 1, tile.y)) ? 2 : 0) |
657
+ (floorAt.has(key(tile.x, tile.y - 1)) ? 4 : 0) |
658
+ (floorAt.has(key(tile.x - 1, tile.y)) ? 8 : 0);
659
+ }
660
+ /**
661
+ * Point an adventure's sprites, animations and wall tiles at the art the flow
662
+ * generated, and play the level music when a track was generated. A slot that
663
+ * still holds its `builtin:` placeholder is left as it is.
664
+ */
665
+ export function bindAdventureArt(document) {
666
+ const next = structuredClone(document);
667
+ const generated = (slot) => {
668
+ const binding = next.assets[slot];
669
+ return binding !== undefined && !binding.assetId.startsWith("builtin:");
670
+ };
671
+ const clipsBySlot = new Map();
672
+ for (const [slot, animations] of Object.entries(ADVENTURE_SHEETS)) {
673
+ if (!generated(slot)) {
674
+ continue;
675
+ }
676
+ const clips = {};
677
+ let complete = true;
678
+ // The sheet prompt fills frames row-major with no gaps, one animation after another.
679
+ let index = 0;
680
+ Object.entries(animations).forEach(([name, count]) => {
681
+ const frames = [];
682
+ for (let offset = 0; offset < count; offset += 1, index += 1) {
683
+ const frame = next.assets[`${slot}.frame.${index}`]?.frame;
684
+ if (!frame) {
685
+ complete = false;
686
+ return;
687
+ }
688
+ frames.push(frame);
689
+ }
690
+ clips[name] = { frames, ticksPerFrame: name === "walk" || name === "move" ? 8 : 20, loop: true };
691
+ });
692
+ if (complete) {
693
+ clipsBySlot.set(slot, clips);
694
+ }
695
+ }
696
+ const floorAt = new Set();
697
+ for (const scene of next.scenes) {
698
+ for (const entity of scene.entities) {
699
+ if (entity.id === "floor" && entity.tilemap) {
700
+ for (const tile of entity.tilemap.tiles) {
701
+ floorAt.add(`${tile.x},${tile.y}`);
702
+ }
703
+ }
704
+ }
705
+ }
706
+ for (const scene of next.scenes) {
707
+ for (const entity of scene.entities) {
708
+ const sprite = entity.sprite;
709
+ const clips = sprite ? clipsBySlot.get(sprite.assetId) : undefined;
710
+ if (sprite && clips) {
711
+ const names = Object.keys(clips);
712
+ const first = clips[names[0]];
713
+ sprite.frame = first.frames[0];
714
+ if (entity.animator || first.frames.length > 1) {
715
+ entity.animator = { frames: first.frames, ticksPerFrame: first.ticksPerFrame, loop: entity.animator?.loop ?? true, clips };
716
+ }
717
+ }
718
+ if (entity.id === "walls" && entity.tilemap && generated("wall") && next.assets["wall.tile.0"]?.frame) {
719
+ for (const tile of entity.tilemap.tiles) {
720
+ const frame = next.assets[`wall.tile.${wallMask(tile, floorAt)}`]?.frame;
721
+ if (frame) {
722
+ tile.frame = frame;
723
+ }
724
+ }
725
+ }
726
+ }
727
+ if (scene.id === ADVENTURE_SCENE_ID && generated("music.level") && !scene.music) {
728
+ scene.music = { assetId: "music.level", volume: 0.55, fadeInTicks: 90, fadeOutTicks: 60 };
729
+ }
730
+ }
731
+ return gameDocument.parse(next);
732
+ }
733
+ //# sourceMappingURL=adventure.js.map