spriteforge 0.1.1__py3-none-any.whl

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 (218) hide show
  1. spriteforge/__init__.py +1 -0
  2. spriteforge/__main__.py +3 -0
  3. spriteforge/agents/__init__.py +0 -0
  4. spriteforge/agents/assets.py +109 -0
  5. spriteforge/agents/cancellation.py +12 -0
  6. spriteforge/agents/director.py +50 -0
  7. spriteforge/agents/models.py +63 -0
  8. spriteforge/agents/roles/art-director.md +15 -0
  9. spriteforge/agents/roles/art-reviewer.md +14 -0
  10. spriteforge/agents/roles/director.md +14 -0
  11. spriteforge/agents/roles/game-designer.md +15 -0
  12. spriteforge/agents/roles/level-tile-designer.md +16 -0
  13. spriteforge/agents/roles/librarian.md +13 -0
  14. spriteforge/agents/roles/menu-designer.md +15 -0
  15. spriteforge/agents/roles/pixel-artist.md +14 -0
  16. spriteforge/agents/roles/programmer.md +14 -0
  17. spriteforge/agents/roles/qa-playtester.md +13 -0
  18. spriteforge/agents/roles/sound-director.md +14 -0
  19. spriteforge/agents/roles.py +39 -0
  20. spriteforge/agents/router.py +233 -0
  21. spriteforge/agents/router_eval.py +145 -0
  22. spriteforge/agents/routing_state.py +133 -0
  23. spriteforge/agents/runtime.py +430 -0
  24. spriteforge/agents/workflow.py +389 -0
  25. spriteforge/app/__init__.py +0 -0
  26. spriteforge/app/agents_view.py +248 -0
  27. spriteforge/app/chat.py +114 -0
  28. spriteforge/app/extensions.py +115 -0
  29. spriteforge/app/index.html +279 -0
  30. spriteforge/app/local_only.py +49 -0
  31. spriteforge/app/server.py +358 -0
  32. spriteforge/app/static/assets/index-L2s1wlcp.css +1 -0
  33. spriteforge/app/static/assets/index-aBfzgLQl.js +71 -0
  34. spriteforge/app/static/assets/press-start-2p-latin-400-normal-BKfmdmKK.woff +0 -0
  35. spriteforge/app/static/assets/press-start-2p-latin-400-normal-xj9lRvVs.woff2 +0 -0
  36. spriteforge/app/static/index.html +13 -0
  37. spriteforge/app/static/press-start-2p-LICENSE.txt +93 -0
  38. spriteforge/app/studio.py +278 -0
  39. spriteforge/app/workers.py +73 -0
  40. spriteforge/cli.py +241 -0
  41. spriteforge/config.py +193 -0
  42. spriteforge/config.yaml +157 -0
  43. spriteforge/core/__init__.py +0 -0
  44. spriteforge/core/acting.py +16 -0
  45. spriteforge/core/cost.py +236 -0
  46. spriteforge/core/credentials.py +24 -0
  47. spriteforge/core/demo.py +79 -0
  48. spriteforge/core/forms.py +20 -0
  49. spriteforge/core/gates.py +175 -0
  50. spriteforge/core/security.py +42 -0
  51. spriteforge/core/state.py +222 -0
  52. spriteforge/core/team.py +15 -0
  53. spriteforge/core/usage.py +68 -0
  54. spriteforge/game/__init__.py +0 -0
  55. spriteforge/game/actors.py +377 -0
  56. spriteforge/game/agent_tools.py +178 -0
  57. spriteforge/game/art.py +2097 -0
  58. spriteforge/game/art_checks.py +190 -0
  59. spriteforge/game/art_review.py +518 -0
  60. spriteforge/game/build.py +134 -0
  61. spriteforge/game/bundle.py +1178 -0
  62. spriteforge/game/cli.py +119 -0
  63. spriteforge/game/codegen.py +433 -0
  64. spriteforge/game/codeinfo.py +154 -0
  65. spriteforge/game/dbsource.py +137 -0
  66. spriteforge/game/design.py +342 -0
  67. spriteforge/game/export.py +62 -0
  68. spriteforge/game/gamedb.py +191 -0
  69. spriteforge/game/image_cache.py +61 -0
  70. spriteforge/game/lessons.py +259 -0
  71. spriteforge/game/level_gen.py +118 -0
  72. spriteforge/game/level_preview.py +97 -0
  73. spriteforge/game/levels.py +934 -0
  74. spriteforge/game/loops.py +38 -0
  75. spriteforge/game/menus.py +712 -0
  76. spriteforge/game/mock_game.js +109 -0
  77. spriteforge/game/mock_platformer.js +58 -0
  78. spriteforge/game/motion.py +881 -0
  79. spriteforge/game/pipeline.py +1768 -0
  80. spriteforge/game/plan.py +502 -0
  81. spriteforge/game/playtest.py +318 -0
  82. spriteforge/game/qa.py +664 -0
  83. spriteforge/game/qa_checks.py +223 -0
  84. spriteforge/game/qa_runtime.py +565 -0
  85. spriteforge/game/reach.py +807 -0
  86. spriteforge/game/record.py +138 -0
  87. spriteforge/game/research.py +262 -0
  88. spriteforge/game/revision.py +225 -0
  89. spriteforge/game/sdk/API.md +104 -0
  90. spriteforge/game/sdk/FLOW.md +19 -0
  91. spriteforge/game/sdk/LEVELS.md +65 -0
  92. spriteforge/game/sdk/sf.js +418 -0
  93. spriteforge/game/sdk/sfflow.js +442 -0
  94. spriteforge/game/sdk/sflevel.js +683 -0
  95. spriteforge/game/sdk/sfsound-editor.js +225 -0
  96. spriteforge/game/sdk/sfsound.js +260 -0
  97. spriteforge/game/sdk/sounds.html +67 -0
  98. spriteforge/game/sounds.py +793 -0
  99. spriteforge/game/story.py +188 -0
  100. spriteforge/game/structure.py +98 -0
  101. spriteforge/game/team_reports.py +394 -0
  102. spriteforge/game/tilesets.py +70 -0
  103. spriteforge/game/title_art.py +186 -0
  104. spriteforge/genres/__init__.py +0 -0
  105. spriteforge/library/__init__.py +15 -0
  106. spriteforge/library/cli.py +126 -0
  107. spriteforge/library/describe.py +242 -0
  108. spriteforge/library/looks.py +154 -0
  109. spriteforge/library/models.py +79 -0
  110. spriteforge/library/store.py +422 -0
  111. spriteforge/library/tilesets/README.md +32 -0
  112. spriteforge/library/tilesets/gandalf-seasons.json +111 -0
  113. spriteforge/library/tilesets/pixel-crawler-dungeon.json +66 -0
  114. spriteforge/mcp/__init__.py +0 -0
  115. spriteforge/mcp/cli.py +58 -0
  116. spriteforge/mcp/client.py +57 -0
  117. spriteforge/mcp/filesystem_read.py +32 -0
  118. spriteforge/mcp/gamedb.py +56 -0
  119. spriteforge/mcp/library.py +179 -0
  120. spriteforge/mcp/memory.py +37 -0
  121. spriteforge/mcp/pixel_tools.py +145 -0
  122. spriteforge/mcp/registry.py +145 -0
  123. spriteforge/mcp/service.py +224 -0
  124. spriteforge/mcp/templates/context7.json +6 -0
  125. spriteforge/mcp/templates/fetch.json +6 -0
  126. spriteforge/mcp/templates/filesystem-read.json +6 -0
  127. spriteforge/mcp/templates/pixel-tools.json +6 -0
  128. spriteforge/memory/README.md +10 -0
  129. spriteforge/memory/__init__.py +0 -0
  130. spriteforge/memory/cli.py +131 -0
  131. spriteforge/memory/okf/__init__.py +1 -0
  132. spriteforge/memory/okf/catalog.py +331 -0
  133. spriteforge/memory/okf/codec.py +63 -0
  134. spriteforge/memory/okf/git.py +104 -0
  135. spriteforge/memory/okf/indexes.py +50 -0
  136. spriteforge/memory/okf/models.py +114 -0
  137. spriteforge/memory/okf/search.py +53 -0
  138. spriteforge/memory/okf/seed.py +81 -0
  139. spriteforge/memory/okf/seeds/genres.yaml +121 -0
  140. spriteforge/memory/okf/seeds/other.yaml +150 -0
  141. spriteforge/memory/okf/store.py +402 -0
  142. spriteforge/memory/okf/validate.py +115 -0
  143. spriteforge/pixel/__init__.py +17 -0
  144. spriteforge/pixel/atlas.py +110 -0
  145. spriteforge/pixel/grid.py +174 -0
  146. spriteforge/pixel/palette.py +156 -0
  147. spriteforge/pixel/palettes/dungeon.json +9 -0
  148. spriteforge/pixel/postprocess.py +170 -0
  149. spriteforge/pixel/preview.py +40 -0
  150. spriteforge/pixel/schemas.py +139 -0
  151. spriteforge/pixel/source.py +237 -0
  152. spriteforge/pixel/terrain.py +48 -0
  153. spriteforge/pixel/validate.py +138 -0
  154. spriteforge/prompts/anim_frame.txt +1 -0
  155. spriteforge/prompts/character.txt +1 -0
  156. spriteforge/prompts/item.txt +1 -0
  157. spriteforge/prompts/tile.txt +1 -0
  158. spriteforge/prompts/ui.txt +1 -0
  159. spriteforge/providers/__init__.py +0 -0
  160. spriteforge/providers/base.py +97 -0
  161. spriteforge/providers/http.py +38 -0
  162. spriteforge/providers/mock.py +111 -0
  163. spriteforge/providers/muse_image.py +60 -0
  164. spriteforge/providers/muse_search.py +91 -0
  165. spriteforge/providers/muse_spark.py +66 -0
  166. spriteforge/skills/__init__.py +0 -0
  167. spriteforge/skills/builtin/LICENSE-awesome-gamedev-agent-skills.txt +201 -0
  168. spriteforge/skills/builtin/NOTICE-awesome-gamedev-agent-skills.txt +15 -0
  169. spriteforge/skills/builtin/THIRD_PARTY.md +21 -0
  170. spriteforge/skills/builtin/audio-design/SKILL.md +190 -0
  171. spriteforge/skills/builtin/game-feel/SKILL.md +174 -0
  172. spriteforge/skills/builtin/game-ui-ux/SKILL.md +167 -0
  173. spriteforge/skills/builtin/level-design/SKILL.md +169 -0
  174. spriteforge/skills/builtin/phaser-arcade-physics/SKILL.md +17 -0
  175. spriteforge/skills/builtin/physics-tuning/SKILL.md +164 -0
  176. spriteforge/skills/builtin/pixel-art-prompting/SKILL.md +12 -0
  177. spriteforge/skills/builtin/platformer/SKILL.md +153 -0
  178. spriteforge/skills/builtin/puzzle/SKILL.md +143 -0
  179. spriteforge/skills/builtin/sprite-animation-frames/SKILL.md +11 -0
  180. spriteforge/skills/builtin/tileset-design/SKILL.md +10 -0
  181. spriteforge/skills/catalog.py +200 -0
  182. spriteforge/skills/cli.py +41 -0
  183. spriteforge/stages/__init__.py +0 -0
  184. spriteforge/stages/asset_context.py +301 -0
  185. spriteforge/stages/asset_models.py +192 -0
  186. spriteforge/stages/asset_render.py +366 -0
  187. spriteforge/stages/asset_review.py +140 -0
  188. spriteforge/stages/asset_store.py +94 -0
  189. spriteforge/stages/chat_changes.py +236 -0
  190. spriteforge/stages/concept.py +42 -0
  191. spriteforge/stages/game.py +1699 -0
  192. spriteforge/stages/game_confirm.py +112 -0
  193. spriteforge/stages/game_final.py +220 -0
  194. spriteforge/stages/game_record.py +246 -0
  195. spriteforge/stages/gameplay.py +218 -0
  196. spriteforge/stages/intake.py +372 -0
  197. spriteforge/stages/preview_assets.py +212 -0
  198. spriteforge/stages/preview_models.py +167 -0
  199. spriteforge/stages/preview_render.py +169 -0
  200. spriteforge/stages/preview_repair.py +61 -0
  201. spriteforge/stages/preview_review.py +169 -0
  202. spriteforge/stages/production.py +170 -0
  203. spriteforge/stages/references.py +105 -0
  204. spriteforge/stages/rewind.py +128 -0
  205. spriteforge/stages/workflow.py +440 -0
  206. spriteforge/templates/phaser/audit.js +45 -0
  207. spriteforge/templates/phaser/font.png +0 -0
  208. spriteforge/templates/phaser/font.xml +1 -0
  209. spriteforge/templates/phaser/preview.html +9 -0
  210. spriteforge/templates/phaser/room.js +49 -0
  211. spriteforge/templates/phaser/vendor/LICENSE.md +20 -0
  212. spriteforge/templates/phaser/vendor/phaser.min.js +1 -0
  213. spriteforge-0.1.1.dist-info/METADATA +364 -0
  214. spriteforge-0.1.1.dist-info/RECORD +218 -0
  215. spriteforge-0.1.1.dist-info/WHEEL +5 -0
  216. spriteforge-0.1.1.dist-info/entry_points.txt +2 -0
  217. spriteforge-0.1.1.dist-info/licenses/LICENSE +27 -0
  218. spriteforge-0.1.1.dist-info/top_level.txt +1 -0
@@ -0,0 +1,683 @@
1
+ /* SpriteForge level engine (L2.3): side-view platformer levels as data.
2
+
3
+ The build loads it after sf.js when the game has levels (window.SF_LEVELS from levels.js:
4
+ the plan's movement and every level). `sf.level.build(scene, hooks)` builds the current
5
+ level in the game's scene: a tilemap of its solid, one-way and hazard tiles, a sprite per
6
+ thing (crates, breakable blocks, pickups, patrolling enemies, checkpoints, the exit), the
7
+ player moved with the plan's numbers (the same model code checks levels with: game/reach.py),
8
+ the camera, checkpoints and respawns, and the level flow (level_start, level_complete, the
9
+ next level, win). The game's code supplies the mechanics through `hooks.touch(thing, how)`.
10
+
11
+ ?level=n starts at level n; ?only=1 stops after it (the playtest plays one level at a time).
12
+ With menus (sfflow.js, L2.5) the flow shows the level intro, the results between levels and
13
+ victory; Continue and Level select start at a saved level (sf.level.n).
14
+ In autoplay the SDK's bot follows the route code found for the level (window.sf.bot says
15
+ where it is). */
16
+ (function () {
17
+ 'use strict';
18
+ const sf = window.sf;
19
+ const data = window.SF_LEVELS || null;
20
+ const params = new URLSearchParams(location.search);
21
+ const count = data ? data.levels.length : 0;
22
+ const first = Math.max(1, Math.min(count || 1, Number(params.get('level')) || 1));
23
+ const level = (sf.level = {data, count, n: first, first, only: params.has('only'),
24
+ advancing: false, current: null, build}); // fmt: skip
25
+ sf.bot = null;
26
+ sf.halted = false;
27
+ if (!data) return;
28
+
29
+ const KINDS = ['crate', 'breakable', 'pickup', 'enemy', 'checkpoint', 'exit', 'lever', 'gate'];
30
+ const SOLID = {crate: true, breakable: true, gate: true};
31
+ const PATROL_SPEED = 1.5; // tiles/s
32
+
33
+ /* The route bot is the autoplay of a level game (the game does not write one). */
34
+ const start = sf.start;
35
+ sf.start = function (opts) {
36
+ opts = Object.assign({}, opts || {});
37
+ opts.autoplay = botPolicy;
38
+ opts.gravity = data.movement.gravity * 16 * (((window.SF_ASSETS || {}).scale) || 1);
39
+ return start(opts);
40
+ };
41
+
42
+ function dangerMarks(ctx, x, T) {
43
+ ctx.fillStyle = 'rgba(208, 40, 40, 0.45)';
44
+ ctx.fillRect(x, 0, T, T);
45
+ const n = Math.max(2, Math.round(T / 8)), w = T / n, h = Math.max(4, Math.round(T * 0.4));
46
+ for (let k = 0; k < n; k++) {
47
+ ctx.fillStyle = '#f0f0f0';
48
+ ctx.beginPath();
49
+ ctx.moveTo(x + k * w, h);
50
+ ctx.lineTo(x + k * w + w / 2, 0);
51
+ ctx.lineTo(x + (k + 1) * w, h);
52
+ ctx.closePath();
53
+ ctx.fill();
54
+ if (T >= 24) { ctx.strokeStyle = '#401010'; ctx.stroke(); }
55
+ }
56
+ }
57
+
58
+ function tileTexture(scene, L) {
59
+ const key = '__sf_tiles_' + L.n, T = L.tile, chars = Object.keys(L.data.tiles);
60
+ if (!scene.textures.exists(key)) {
61
+ const canvas = scene.textures.createCanvas(key, Math.max(1, chars.length) * T, T);
62
+ const ctx = canvas.context;
63
+ ctx.imageSmoothingEnabled = false;
64
+ chars.forEach((ch, i) => {
65
+ const t = L.data.tiles[ch];
66
+ if (sf.has(t.entity)) {
67
+ const tex = scene.textures.get(t.entity), fr = tex.has(0) ? tex.get(0) : tex.get();
68
+ ctx.drawImage(fr.source.image, fr.cutX, fr.cutY, fr.cutWidth, fr.cutHeight, i * T, 0, T, T);
69
+ // A hazard drawn with the same art as ground the player stands on would look safe
70
+ // (live 2026-11-03: the foundry's hazard blocks were its floor tile, and the hero died
71
+ // standing on them): tint it red and put spikes on its top.
72
+ const shared = t.kind === 'hazard' && Object.values(L.data.tiles)
73
+ .some(o => o !== t && o.kind !== 'hazard' && o.entity === t.entity);
74
+ if (shared) dangerMarks(ctx, i * T, T);
75
+ } else {
76
+ ctx.fillStyle = t.kind === 'hazard' ? '#d04040' : t.kind === 'one_way' ? '#a08060' : '#607080';
77
+ ctx.fillRect(i * T, t.kind === 'one_way' ? 0 : 0, T, t.kind === 'one_way' ? T / 3 : T);
78
+ }
79
+ });
80
+ canvas.refresh();
81
+ }
82
+ return {key, index: Object.fromEntries(chars.map((ch, i) => [ch, i]))};
83
+ }
84
+
85
+ function build(scene, hooks) {
86
+ hooks = hooks || {};
87
+ const d = data.levels[level.n - 1], mv = data.movement;
88
+ const s = sf.assets.scale || 1, T = 16 * s, W = d.cols * T, H = d.rows * T;
89
+ const world = scene.physics.world;
90
+ const L = {n: level.n, name: d.name, data: d, tile: T, width: W, height: H, hooks,
91
+ things: {}, list: [], groups: {}, checkpoint: null, done: false, over: false,
92
+ facing: 1, grounded: false, dashing: false, autoAnim: true, t0: sf.clock.now,
93
+ standFrame: -1}; // fmt: skip
94
+ level.current = L;
95
+ world.gravity.y = mv.gravity * T;
96
+ world.TILE_BIAS = T;
97
+ world.OVERLAP_BIAS = Math.max(4, T / 4);
98
+ world.setBounds(0, 0, W, H);
99
+ world.setBoundsCollision(true, true, false, false);
100
+
101
+ // Tiles: one tilemap layer; one-way tiles collide on top only; hazards do not collide.
102
+ const tex = tileTexture(scene, L);
103
+ const grid = d.map.map(row => Array.from(row, ch => (ch in tex.index ? tex.index[ch] : -1)));
104
+ const map = scene.make.tilemap({data: grid, tileWidth: T, tileHeight: T});
105
+ const tileset = map.addTilesetImage(tex.key, tex.key, T, T, 0, 0);
106
+ const layer = (L.layer = map.createLayer(0, tileset, 0, 0));
107
+ const kindOf = {};
108
+ for (const [ch, t] of Object.entries(d.tiles)) kindOf[tex.index[ch]] = t.kind;
109
+ layer.setCollision(Object.keys(kindOf).map(Number).filter(i => kindOf[i] === 'solid'));
110
+ layer.forEachTile(t => { if (kindOf[t.index] === 'one_way') t.setCollision(false, false, true, false); });
111
+ layer.setDepth(-10);
112
+ L.hazardAt = (x, y, w, h) => layer.getTilesWithinWorldXY(x, y, w, h).some(t => kindOf[t.index] === 'hazard');
113
+
114
+ // Things.
115
+ for (const k of KINDS) L.groups[k] = scene.physics.add.group();
116
+ for (const td of d.things) {
117
+ if (td.kind === 'start') continue;
118
+ const t = Object.assign({}, td, {sprites: [], open: false, taken: false, drop: null, touched: -1});
119
+ for (const [c, r] of td.cells) t.sprites.push(place(scene, L, t, c, r));
120
+ t.sprite = t.sprites[0];
121
+ t.x = t.sprite.x; t.y = t.sprite.y;
122
+ if (t.kind === 'enemy') t.dir = 1;
123
+ L.things[t.id] = t;
124
+ L.list.push(t);
125
+ }
126
+
127
+ // The player, feet on the start cell's floor.
128
+ const p = (L.player = sf.sprite(scene, (d.start[0] + 0.5) * T, (d.start[1] + 0.5) * T, d.player));
129
+ p.body.setMaxVelocity(T * 100, mv.max_fall * T);
130
+ p.setCollideWorldBounds(true);
131
+ p.body.reset(p.x, (d.start[1] + 1) * T - (p.body.bottom - p.y));
132
+ p.setDepth(10);
133
+ L.spawnAt = [p.x, p.y];
134
+ dressPlayer(scene, L);
135
+ // A one-way tile holds a body only when its feet were on or above the tile's top before
136
+ // this step (coming down onto it), as game/reach.py assumes. Arcade alone snaps a body up
137
+ // onto any tile it overlaps by less than TILE_BIAS: a jump that peaked a few pixels under
138
+ // a one-way platform landed on it (live 2026-11-03, level 2 of the slime game).
139
+ const fromAbove = (o, tile) => kindOf[tile.index] !== 'one_way'
140
+ || o.body.prev.y + o.body.height <= tile.pixelY + 1;
141
+ scene.physics.add.collider(p, layer, null, fromAbove);
142
+ scene.physics.add.collider(L.groups.enemy, layer, null, fromAbove);
143
+ const touch = (_, o) => touched(L, o.getData('thing'));
144
+ // Standing on a solid thing counts as ground (body.touching is no use: Arcade sets it for
145
+ // overlaps too, so passing through a coin in mid-air would read as a landing).
146
+ const solid = (pl, o) => {
147
+ if (pl.body.bottom <= o.body.top + 2) L.standFrame = sf.clock.now;
148
+ touch(pl, o);
149
+ };
150
+ scene.physics.add.collider(p, L.groups.crate, solid);
151
+ scene.physics.add.collider(p, L.groups.breakable, solid);
152
+ scene.physics.add.collider(p, L.groups.gate, solid);
153
+ scene.physics.add.overlap(p, L.groups.lever, (_, o) => pull(L, o.getData('thing')));
154
+ scene.physics.add.overlap(p, L.groups.pickup, touch);
155
+ scene.physics.add.overlap(p, L.groups.enemy, touch);
156
+ scene.physics.add.overlap(p, L.groups.checkpoint, (_, o) => checkpoint(L, o.getData('thing')));
157
+ scene.physics.add.overlap(p, L.groups.exit, () => complete(scene, L));
158
+
159
+ const cam = scene.cameras.main;
160
+ cam.setBounds(0, 0, W, H);
161
+ cam.startFollow(p, true, 0.2, 0.2);
162
+ backdrop(scene, L);
163
+
164
+ // The controller: the plan's numbers (tiles) at the tile size; the jump peaks at mv.jump
165
+ // under Arcade's stepping (as game/reach.py assumes).
166
+ const dt = 1 / (world.fps || 60), g = mv.gravity;
167
+ const v0 = (g * dt / 2 + Math.sqrt((g * dt / 2) ** 2 + 2 * g * mv.jump)) * T;
168
+ const dashSpeed = mv.dash > 0 ? mv.dash / (mv.dash_steps * dt) * T : 0;
169
+ const c = (L.control = {lastGround: -1, buffer: -1, rising: false, dashSteps: 0, dashDir: 1,
170
+ dashReady: 0, airDash: true, prevA: false, prevB: false, inputX: 0,
171
+ safeUntil: 0}); // fmt: skip
172
+ world.on('worldstep', onStep);
173
+ scene.events.once('shutdown', () => world.off('worldstep', onStep));
174
+ function onStep() {
175
+ if (c.dashSteps > 0 && p.body) {
176
+ c.dashSteps--;
177
+ if (c.dashSteps === 0) {
178
+ p.body.setAllowGravity(true);
179
+ p.body.setVelocityX(c.inputX * mv.speed * T);
180
+ L.dashing = false;
181
+ } else p.body.setVelocity(c.dashDir * dashSpeed, 0);
182
+ }
183
+ }
184
+ // Scene listeners outlive scene.restart(): remove them when this level shuts down.
185
+ const onUpdate = () => control(scene, L, mv, v0, dashSpeed);
186
+ scene.events.on('update', onUpdate);
187
+ scene.events.once('shutdown', () => {
188
+ scene.events.off('update', onUpdate);
189
+ if (level.current === L) level.current = null;
190
+ });
191
+
192
+ if (!(sf.flow && sf.flow.active)) { // with menus the flow shows the level's intro
193
+ const label = sf.text(scene, sf.screen()[0] / 2, 30 * s, 'Level ' + L.n + ': ' + L.name,
194
+ {originX: 0.5, color: '#f4d35e', sdk: true}); // fmt: skip
195
+ scene.time.delayedCall(1800, () => label.destroy());
196
+ }
197
+ sf.state.level = L.n;
198
+ sf.bot = {level: L.n, step: 0, steps: d.route.length, status: 'playing', detail: ''};
199
+ L.bot = {i: 0, phase: 'start', t0: 0, retries: 0, resume: 0, frame: -1, out: null, dashed: false,
200
+ stepStart: sf.clock.now, last: -1}; // fmt: skip
201
+ sf.event('level_start', {n: L.n});
202
+ return L;
203
+ }
204
+
205
+ /* The level's background (L2.7 live run): the design's background images were drawn but no
206
+ game drew them (live 2026-11-03: three Muse backdrops, an empty sky in every level). The
207
+ engine draws one behind each level: the background whose id shares a word with the level's
208
+ name ('background_jungle' for 'Jungle River Base'), else the backgrounds in turn; it fills
209
+ the screen and scrolls slower than the camera (its `parallax`, default 0.3), but never so
210
+ far that it repeats: a Muse picture is not seamless (a screen-wide one stands still). A game that
211
+ draws a background itself keeps its own: the engine's is removed. */
212
+ const BACK_WORDS = s => String(s || '').toLowerCase().split(/[^a-z0-9]+/).filter(w => w.length > 2 && w !== 'background');
213
+ function backdrop(scene, L) {
214
+ const backs = Object.entries(sf.assets.images || {}).filter(([, a]) => a.role === 'background');
215
+ if (!backs.length) return null;
216
+ const want = new Set(BACK_WORDS(L.name));
217
+ const [id, a] = backs.find(([k]) => BACK_WORDS(k).some(w => want.has(w))) || backs[(L.n - 1) % backs.length];
218
+ const tex = scene.textures.get(id);
219
+ const src = tex && tex.getSourceImage && tex.getSourceImage();
220
+ if (!src || !src.height) return null;
221
+ const [w, h] = sf.screen(), k = h / src.height;
222
+ const room = Math.max(0, src.width * k - w), travel = Math.max(1, L.width - w);
223
+ const factor = Math.min(a.parallax == null ? 0.3 : +a.parallax, room / travel);
224
+ const bg = scene.add.tileSprite(0, 0, w, h, id).setOrigin(0).setScrollFactor(0).setDepth(-100);
225
+ bg.setTileScale(k, k);
226
+ L.backdrop = bg;
227
+ L.backdropId = id;
228
+ const cam = scene.cameras.main;
229
+ const follow = () => { if (bg.active) bg.tilePositionX = cam.scrollX * factor / k; };
230
+ scene.events.on('update', follow);
231
+ scene.events.once('shutdown', () => scene.events.off('update', follow));
232
+ scene.events.once('update', () => { // after the game's create(): its own background wins
233
+ const ids = new Set(backs.map(([k2]) => k2));
234
+ const own = scene.children.list.some(o => o !== bg && o.texture && ids.has(o.texture.key));
235
+ if (own) { bg.destroy(); L.backdrop = null; }
236
+ });
237
+ return bg;
238
+ }
239
+
240
+ /* The player's skin (L2.4): what is drawn. L.player keeps its physics body, its animations
241
+ and whatever the game sets on it (tint, alpha, visible, flip); the skin copies them every
242
+ frame and adds what must not touch the body: the squash and stretch of jumps and landings,
243
+ the lift of a hop's airborne frames, a form's tint and particles, flashes. */
244
+ function rowsOf(key) { return ((sf.assets.sprites[key] || {}).rows) || {}; }
245
+ function dressPlayer(scene, L) {
246
+ const p = L.player;
247
+ const skin = (L.skin = scene.add.sprite(p.x, p.y, p.texture.key, p.frame.name).setOrigin(0.5, 1));
248
+ skin.setDepth(p.depth + 1);
249
+ p.willRender = () => false;
250
+ L.squash = {a: 0, t0: 0, dur: 1};
251
+ L.flash = {color: 0, until: -1};
252
+ L.form = null;
253
+ L.wasGrounded = true;
254
+ L.landUntil = -1;
255
+ L.dripAt = 0;
256
+ skin.sfFx = e => {
257
+ const now = sf.clock.now;
258
+ if (e.squash) L.squash = {a: e.squash, t0: now, dur: Math.max(0.1, e.seconds || 0.25)};
259
+ if (e.flash) L.flash = {color: parseInt(e.flash.slice(1), 16), until: now + 0.09};
260
+ };
261
+ const onPost = () => dress(L);
262
+ scene.events.on('postupdate', onPost);
263
+ scene.events.once('shutdown', () => scene.events.off('postupdate', onPost));
264
+ }
265
+ function dress(L) {
266
+ const p = L.player, k = L.skin;
267
+ if (!p || !k || !p.active || !k.active) return;
268
+ if (k.texture.key !== p.texture.key) k.setTexture(p.texture.key, p.frame.name);
269
+ else if (k.frame.name !== p.frame.name) k.setFrame(p.frame.name);
270
+ k.setFlipX(p.flipX).setVisible(p.visible).setAlpha(p.alpha);
271
+ const now = sf.clock.now, s = L.squash;
272
+ const a = s.a * Math.max(0, 1 - (now - s.t0) / s.dur);
273
+ k.setScale(p.scaleX * (1 + a), p.scaleY * (1 - a));
274
+ let lift = 0;
275
+ const cur = p.anims && p.anims.currentAnim, frame = p.anims && p.anims.currentFrame;
276
+ if (cur && frame) {
277
+ const row = rowsOf(p.texture.key)[cur.key.split(':').pop()];
278
+ if (row && row.lift) lift = row.lift[frame.index - 1] || 0;
279
+ }
280
+ k.x = p.x;
281
+ k.y = p.y + (1 - p.originY) * p.displayHeight - lift;
282
+ if (L.flash.until >= now) k.setTintFill(L.flash.color);
283
+ else if (L.form && !L.form.row && L.form.tint) k.setTint(parseInt(L.form.tint.slice(1), 16));
284
+ else if (p.isTinted) k.setTint(p.tintTopLeft, p.tintTopRight, p.tintBottomLeft, p.tintBottomRight);
285
+ else k.clearTint();
286
+ if (L.form && !L.form.row && L.form.particles && now >= L.dripAt) { // a form without its row
287
+ L.dripAt = now + 0.25;
288
+ sf.particles(k.scene, k.x, k.y - k.displayHeight / 2, 2, [L.form.particles], 25, 0.5);
289
+ }
290
+ }
291
+ // The row the player shows: the form's row while a form lasts, else the row that plays
292
+ // that way (move, jump, fall, land, dash, idle), else the older names.
293
+ function playerAnim(scene, L, grounded, moving, now) {
294
+ const key = L.player.texture.key, rows = rowsOf(key);
295
+ const has = n => n && scene.anims.exists(key + ':' + n);
296
+ const by = kind => Object.keys(rows).find(n => rows[n].plays === kind && !rows[n].form);
297
+ if (L.form && has(L.form.row)) return L.form.row;
298
+ const vy = L.player.body.velocity.y;
299
+ const pick = (...names) => names.find(has) || names[names.length - 1];
300
+ if (L.dashing) return pick(by('dash'), 'dash', by('move'), 'walk');
301
+ if (!grounded) return vy > 0 ? pick(by('fall'), by('jump'), 'jump') : pick(by('jump'), 'jump');
302
+ if (now < L.landUntil) return pick(by('land'), 'idle');
303
+ if (moving) return pick(by('move'), 'walk', 'move', 'run', 'walk');
304
+ return pick(by('idle'), 'idle');
305
+ }
306
+
307
+ function flag(scene, T) { // a checkpoint the design gave no art: a pole and a flag
308
+ const key = '__sf_flag_' + T;
309
+ if (!scene.textures.exists(key)) {
310
+ const g = scene.make.graphics({x: 0, y: 0, add: false});
311
+ g.fillStyle(0xd8d8e0).fillRect(T * 0.1, 0, T * 0.1, T);
312
+ g.fillStyle(0x4a90e2).fillRect(T * 0.2, T * 0.05, T * 0.55, T * 0.35);
313
+ g.generateTexture(key, Math.ceil(T * 0.8), T);
314
+ g.destroy();
315
+ }
316
+ return key;
317
+ }
318
+
319
+ function leverArt(scene, T) { // a lever on a base, handle up (pulled: flipped)
320
+ const key = '__sf_lever_' + T;
321
+ if (!scene.textures.exists(key)) {
322
+ const g = scene.make.graphics({x: 0, y: 0, add: false});
323
+ g.fillStyle(0x6a6a78).fillRect(T * 0.2, T * 0.75, T * 0.6, T * 0.25);
324
+ g.lineStyle(Math.max(2, T / 8), 0xc8c8d0).lineBetween(T * 0.5, T * 0.8, T * 0.75, T * 0.2);
325
+ g.fillStyle(0xe04040).fillCircle(T * 0.75, T * 0.2, T * 0.12);
326
+ g.generateTexture(key, T, T);
327
+ g.destroy();
328
+ }
329
+ return key;
330
+ }
331
+
332
+ function gateArt(scene, T) { // one cell of iron bars
333
+ const key = '__sf_gate_' + T;
334
+ if (!scene.textures.exists(key)) {
335
+ const g = scene.make.graphics({x: 0, y: 0, add: false});
336
+ g.fillStyle(0x3a3a48).fillRect(0, 0, T, T * 0.12).fillRect(0, T * 0.88, T, T * 0.12);
337
+ g.fillStyle(0x8a8a9a);
338
+ for (let i = 0; i < 4; i++) g.fillRect(T * (0.08 + i * 0.25), 0, T * 0.1, T);
339
+ g.generateTexture(key, T, T);
340
+ g.destroy();
341
+ }
342
+ return key;
343
+ }
344
+
345
+ function pull(L, t) { // a lever pulled: it stays down and opens every gate named for it
346
+ if (!t || t.taken || L.done) return;
347
+ t.taken = true;
348
+ const o = t.sprite;
349
+ if (o && o.active) {
350
+ const k = o.texture.key;
351
+ const anim = ['pull', 'pulled', 'on', 'active', 'open'].find(a => o.scene.anims.exists(k + ':' + a));
352
+ if (anim) o.anims.play({key: k + ':' + anim, repeat: 0}); else o.setFlipX(!o.flipX);
353
+ sf.fx('pickup', o.x, o.y, null, t.entity + ' lever');
354
+ }
355
+ sf.event('lever', {n: L.n, id: t.id});
356
+ const name = String(t.gives || '').trim().toLowerCase();
357
+ for (const g of L.list) {
358
+ if (g.kind === 'gate' && !g.open && String(g.needs || '').trim().toLowerCase() === name) api.open(g);
359
+ }
360
+ if (L.hooks.lever) {
361
+ try { L.hooks.lever(t); } catch (e) { sf.errors.push('lever hook: ' + e.message); }
362
+ }
363
+ }
364
+
365
+ function place(scene, L, t, c, r) {
366
+ const T = L.tile;
367
+ const x = (c + 0.5) * T;
368
+ // A checkpoint, lever or gate the design gave no art: the SDK draws one.
369
+ const drawn = !sf.has(t.entity) && {checkpoint: flag, lever: leverArt, gate: gateArt}[t.kind];
370
+ const o = drawn
371
+ ? scene.physics.add.sprite(x, (r + 0.5) * T, drawn(scene, T))
372
+ : sf.sprite(scene, x, (r + 0.5) * T, t.entity);
373
+ o.setData('thing', t);
374
+ L.groups[t.kind].add(o);
375
+ const b = o.body;
376
+ if (t.kind === 'enemy') {
377
+ b.setAllowGravity(true);
378
+ o.y = (r + 1) * T - (b.bottom - o.y) - 1;
379
+ const rows = rowsOf(o.texture.key);
380
+ sf.play(o, Object.keys(rows).find(n => rows[n].plays === 'move') || 'walk');
381
+ return o;
382
+ }
383
+ b.setAllowGravity(false);
384
+ b.setImmovable(true);
385
+ if (SOLID[t.kind] || t.kind === 'pickup') b.setSize(T / o.scaleX, T / o.scaleY, true);
386
+ if (t.kind !== 'pickup' && !SOLID[t.kind]) o.y = (r + 1) * T - o.displayHeight / 2; // stands on the floor
387
+ o.setDepth(t.kind === 'exit' || t.kind === 'checkpoint' ? 5 : 6);
388
+ return o;
389
+ }
390
+
391
+ function touched(L, t) {
392
+ if (!t || t.open || L.done || t.kind === 'gate') return; // gates open by their lever
393
+ if (t.kind === 'lever') { pull(L, t); return; }
394
+ const now = sf.clock.now;
395
+ if (now - t.touched < 0.2) return;
396
+ t.touched = now;
397
+ const how = L.dashing ? 'dash' : 'touch';
398
+ if (L.hooks.touch) {
399
+ try { L.hooks.touch(t, how); } catch (e) { sf.errors.push('touch hook: ' + e.message); }
400
+ } else if (t.kind === 'pickup') L.take(t);
401
+ }
402
+
403
+ function checkpoint(L, t) {
404
+ if (!t || L.checkpoint === t) return;
405
+ L.checkpoint = t;
406
+ L.bot.resume = L.bot.i;
407
+ sf.play(t.sprite, 'active');
408
+ sf.fx('checkpoint', t.sprite.x, t.sprite.y, t.sprite);
409
+ sf.event('checkpoint', {n: L.n, id: t.id});
410
+ if (L.hooks.checkpoint) L.hooks.checkpoint(t);
411
+ }
412
+
413
+ function complete(scene, L) {
414
+ if (L.done) return;
415
+ L.done = true;
416
+ L.player.body.setVelocity(0, 0);
417
+ sf.fx('exit', L.player.x, L.player.y, L.skin);
418
+ sf.event('level_complete', {n: L.n});
419
+ if (L.hooks.complete) L.hooks.complete(L.n);
420
+ const [w, h] = sf.screen();
421
+ const last = L.n >= count;
422
+ if (sf.flow && sf.flow.active && !level.only) {
423
+ // The flow shows the results (next level, title) or, after the last level, victory.
424
+ if (last) { L.over = true; sf.event('win'); } else sf.flow.levelDone(L.n);
425
+ return;
426
+ }
427
+ sf.text(scene, w / 2, h / 2, last ? 'YOU WIN!' : 'LEVEL CLEAR', {originX: 0.5, size: 12, sdk: true});
428
+ if (last) {
429
+ L.over = true;
430
+ sf.event('win');
431
+ } else if (level.only) {
432
+ sf.halted = true;
433
+ } else {
434
+ scene.time.delayedCall(1000, () => { level.n = L.n + 1; level.advancing = true; scene.scene.restart(); });
435
+ }
436
+ if (last || level.only) {
437
+ const enter = scene.input.keyboard && scene.input.keyboard.addKey('ENTER');
438
+ if (enter) enter.once('down', () => { level.n = level.first; sf.halted = false; scene.scene.restart(); });
439
+ }
440
+ }
441
+
442
+ /* The game's code calls these. */
443
+ const api = {
444
+ open(t) { // a crate dissolved, a wall broken, an enemy beaten
445
+ if (!t || t.open) return;
446
+ t.open = true;
447
+ t.sprites.forEach((o, i) => {
448
+ if (i === 0 || i === t.sprites.length - 1) sf.fx(t.kind === 'enemy' ? 'kill' : 'break', o.x, o.y, o, t.entity + ' ' + t.needs + ' ' + t.kind);
449
+ });
450
+ for (const o of t.sprites) {
451
+ if (o.body) o.body.enable = false;
452
+ const scene = o.scene;
453
+ // The row that plays when it goes: break or die (the motion design), else older names;
454
+ // a breakable tile (an image) shows its crumble sprite `<entity>_break`.
455
+ const rowed = key => Object.keys(rowsOf(key)).find(n => ['break', 'die'].includes(rowsOf(key)[n].plays));
456
+ let key = o.texture.key;
457
+ if (!rowed(key) && !['break', 'die', 'death', 'open'].some(a => scene && scene.anims.exists(key + ':' + a))
458
+ && sf.has(t.entity + '_break') && scene) {
459
+ key = t.entity + '_break';
460
+ o.setTexture(key, 0);
461
+ }
462
+ const anim = [rowed(key), 'break', 'die', 'death', 'open'].find(a => a && scene && scene.anims.exists(key + ':' + a));
463
+ if (!anim) { o.destroy(); continue; }
464
+ // Played once whatever the animation's own repeat says (a looping 'die' left beaten
465
+ // enemies dying forever, live 2026-11-02), and removed at the end; a timer makes sure.
466
+ o.anims.play({key: key + ':' + anim, repeat: 0});
467
+ o.once('animationcomplete', () => o.destroy());
468
+ scene.time.delayedCall(2000, () => { if (o.active) o.destroy(); });
469
+ }
470
+ },
471
+ drop(t) { // what a crate holds appears where it was
472
+ if (!t || !t.holds || t.drop) return t ? t.drop : null;
473
+ const L = level.current, T = L.tile;
474
+ const dt = {id: t.id + '>', kind: 'pickup', entity: t.holds, col: t.col, row: t.row,
475
+ cells: [[t.col, t.row]], needs: '', opened_by: 'never', holds: '', gives: t.gives}; // fmt: skip
476
+ const d = Object.assign(dt, {sprites: [], open: false, taken: false, drop: null, touched: -1});
477
+ const o = place(L.player.scene, L, d, t.col, t.row);
478
+ d.sprites.push(o); d.sprite = o; d.x = o.x; d.y = o.y;
479
+ L.things[d.id] = d; L.list.push(d);
480
+ t.drop = d;
481
+ return d;
482
+ },
483
+ take(t) { // a pickup collected; one that gives a form ability turns the player into it
484
+ if (!t || t.taken) return;
485
+ t.taken = true;
486
+ t.open = true;
487
+ const forms = sf.assets.forms || {};
488
+ if (t.gives && forms[t.gives]) level.form(t.gives);
489
+ else if (t.sprite) sf.fx('pickup', t.sprite.x, t.sprite.y, null, t.entity + ' ' + (t.gives || ''));
490
+ for (const o of t.sprites) o.destroy();
491
+ },
492
+ form(ability) { // the player shows a form (its row, or a tint with particles); '' ends it
493
+ const L = level.current;
494
+ if (!L || !L.skin) return;
495
+ const f = ability ? (sf.assets.forms || {})[ability] : null;
496
+ const name = f ? ability : '';
497
+ if ((L.form ? L.form.name : '') === name) return;
498
+ L.form = f ? Object.assign({name}, f) : null;
499
+ sf.state.form = name;
500
+ sf.fx('transform', L.player.x, L.player.y, L.skin, name);
501
+ sf.event('form', {ability: name});
502
+ },
503
+ respawn(cause) { // back to the last checkpoint (or the start)
504
+ const L = level.current;
505
+ if (!L || L.done) return;
506
+ const p = L.player, T = L.tile, c = L.control;
507
+ const at = L.checkpoint ? [(L.checkpoint.col + 0.5) * T, (L.checkpoint.row + 1) * T] : null;
508
+ sf.fx('hurt', p.x, p.y, L.skin, cause);
509
+ c.dashSteps = 0; L.dashing = false; p.body.setAllowGravity(true);
510
+ if (at) p.body.reset(at[0], at[1] - (p.body.bottom - p.y));
511
+ else p.body.reset(L.spawnAt[0], L.spawnAt[1]);
512
+ p.body.setVelocity(0, 0);
513
+ c.safeUntil = sf.clock.now + 0.3;
514
+ L.bot.respawned = true;
515
+ sf.event('respawn', {n: L.n, cause: String(cause || '')});
516
+ if (L.hooks.respawn) L.hooks.respawn(cause);
517
+ },
518
+ };
519
+ for (const [name, fn] of Object.entries(api)) level[name] = fn;
520
+ level.thing = id => level.current && level.current.things[id];
521
+
522
+ function control(scene, L, mv, v0, dashSpeed) {
523
+ const p = L.player, b = p.body;
524
+ if (!b || L.done) return;
525
+ const T = L.tile, c = L.control, now = sf.clock.now;
526
+ const inp = sf.input(scene);
527
+ const grounded = (L.grounded = b.blocked.down || L.standFrame === now);
528
+ if (grounded) { c.lastGround = now; c.airDash = true; }
529
+ c.inputX = inp.x;
530
+ if (!c.dashSteps) b.setVelocityX(inp.x * mv.speed * T);
531
+ if (inp.x) L.facing = Math.sign(inp.x);
532
+ const jump = inp.action || inp.y < -0.5; // Space (or up) jumps; X/Shift dashes
533
+ if (jump && !c.prevA) c.buffer = now;
534
+ if (c.buffer >= 0 && now - c.buffer <= 0.1 && c.lastGround >= 0 && now - c.lastGround <= Math.max(mv.coyote, 0.001) + 1e-6 && !c.dashSteps) {
535
+ b.setVelocityY(-v0);
536
+ c.buffer = -1; c.lastGround = -1; c.rising = true;
537
+ sf.event('jump');
538
+ sf.fx('jump', p.x, b.bottom, L.skin);
539
+ }
540
+ if (c.rising && !jump && b.velocity.y < 0) { b.setVelocityY(b.velocity.y * 0.5); c.rising = false; }
541
+ if (b.velocity.y >= 0) c.rising = false;
542
+ if (inp.action2 && !c.prevB && dashSpeed > 0 && now >= c.dashReady && (grounded || c.airDash) && !c.dashSteps) {
543
+ c.dashSteps = mv.dash_steps;
544
+ c.dashDir = inp.x ? Math.sign(inp.x) : L.facing;
545
+ c.dashReady = now + mv.cooldown;
546
+ if (!grounded) c.airDash = false;
547
+ c.rising = false;
548
+ b.setAllowGravity(false);
549
+ b.setVelocity(c.dashDir * dashSpeed, 0);
550
+ L.dashing = true;
551
+ sf.event('dash');
552
+ sf.fx('dash', p.x, b.center.y, L.skin);
553
+ }
554
+ c.prevA = jump; c.prevB = inp.action2;
555
+ if (grounded && !L.wasGrounded && b.velocity.y >= 0) { // landed: squash, dust, the land row
556
+ const land = Object.entries(rowsOf(p.texture.key)).find(([, r]) => r.plays === 'land');
557
+ if (land) L.landUntil = now + (land[1].lift || [0]).length / Math.max(1, land[1].fps);
558
+ sf.fx('land', p.x, b.bottom, L.skin);
559
+ }
560
+ L.wasGrounded = grounded;
561
+ if (L.autoAnim) {
562
+ sf.play(p, playerAnim(scene, L, grounded, Math.abs(b.velocity.x) > 1, now));
563
+ p.setFlipX(L.facing < 0);
564
+ }
565
+ // Pits and hazards send the player back to the last checkpoint.
566
+ if (now >= c.safeUntil) {
567
+ if (b.top > L.height + T) level.respawn('pit');
568
+ else if (L.hazardAt(b.x + 2, b.y + 2, b.width - 4, b.height - 4)) level.respawn('hazard');
569
+ }
570
+ for (const t of L.list) { // enemies walk their patrol
571
+ if (t.kind !== 'enemy' || t.open || !t.sprite.body || !t.patrol) continue;
572
+ const o = t.sprite, lo = (t.patrol[0] + 0.5) * T, hi = (t.patrol[1] + 0.5) * T;
573
+ if (o.x <= lo) t.dir = 1;
574
+ if (o.x >= hi) t.dir = -1;
575
+ o.body.setVelocityX(t.dir * (t.speed || PATROL_SPEED) * T * (sf.settings.multiplier || 1));
576
+ o.setFlipX(t.dir < 0);
577
+ t.x = o.x; t.y = o.y;
578
+ }
579
+ sf.state.level = L.n;
580
+ sf.state.x = Math.round(p.x);
581
+ sf.state.y = Math.round(p.y);
582
+ sf.state.time = +(now - L.t0).toFixed(2);
583
+ }
584
+
585
+ /* ---------- the route bot ------------------------------------------------------------------ */
586
+ function botPolicy(scene) {
587
+ const L = level.current;
588
+ if (!L || !L.player || !L.player.body) return {};
589
+ const B = L.bot, now = sf.clock.now;
590
+ if (B.frame === now && B.out) return B.out; // one decision per frame, however often asked
591
+ B.frame = now;
592
+ B.out = decide(L, B, now) || {};
593
+ return B.out;
594
+ }
595
+
596
+ function stuck(B, detail) {
597
+ B.status = 'stuck';
598
+ sf.bot.status = 'stuck';
599
+ sf.bot.detail = detail;
600
+ return {};
601
+ }
602
+
603
+ function decide(L, B, now) {
604
+ const d = L.data, mv = data.movement, T = L.tile, p = L.player, b = p.body;
605
+ if (L.done || B.status === 'stuck') return {};
606
+ if (B.respawned) {
607
+ B.respawned = false;
608
+ B.retries++;
609
+ if (B.retries > 3) return stuck(B, 'sent back to a checkpoint more than 3 times');
610
+ B.i = B.resume; B.phase = 'start'; B.stepStart = now;
611
+ }
612
+ if (B.i >= d.route.length) return stuck(B, 'the route ended before the exit');
613
+ const st = d.route[B.i];
614
+ sf.bot.step = B.i;
615
+ const x = b.center.x / T, feet = b.bottom / T, grounded = L.grounded;
616
+ const frame = B.last >= 0 && now > B.last ? now - B.last : 1 / 30; // seconds per frame
617
+ B.last = now;
618
+ const fps = 1 / frame;
619
+ const steer = tx => Math.max(-1, Math.min(1, (tx - x) * fps / mv.speed));
620
+ const next = () => { B.i++; B.phase = 'start'; B.stepStart = now; B.dashed = false; return null; };
621
+ if (B.phase === 'start') { B.phase = 'approach'; B.stepStart = now; }
622
+ const age = now - B.stepStart;
623
+ if (age > 10) return stuck(B, 'step ' + B.i + ' (' + st.do + (st.thing ? ' ' + st.thing : '') + ') took over 10 s at x=' + x.toFixed(2) + ', feet=' + feet.toFixed(2));
624
+ if (st.do === 'walk') {
625
+ if (Math.abs(st.x - x) < 0.06 && grounded) { next(); return {x: 0}; }
626
+ return {x: steer(st.x)};
627
+ }
628
+ if (st.do === 'jump' || st.do === 'fall') {
629
+ const w = data.body[0];
630
+ if (B.phase === 'approach') {
631
+ const ax = st.do === 'fall' ? st.x0 - st.side * (w + 0.04) : st.x0;
632
+ if (Math.abs(ax - x) < 0.05 && grounded && Math.abs(b.velocity.x) < T * 0.5 * mv.speed + 1) {
633
+ B.phase = 'air'; B.t0 = now; B.left = false;
634
+ } else return {x: steer(ax)};
635
+ }
636
+ if (B.phase === 'air') {
637
+ const t = now - B.t0;
638
+ if (st.do === 'jump' && t > 0.1 && grounded || st.do === 'fall' && B.left && grounded) {
639
+ const want = st.cell[1];
640
+ if (Math.abs((feet - 1) - want) < 0.3) { next(); return {x: 0}; }
641
+ B.retries++;
642
+ if (B.retries > 3) return stuck(B, 'step ' + B.i + ' (' + st.do + ') landed at x=' + x.toFixed(2) + ', row ' + Math.round(feet - 1) + ' instead of row ' + want);
643
+ B.phase = 'approach';
644
+ return {x: 0};
645
+ }
646
+ if (!grounded) B.left = true;
647
+ let vx = t < st.wait - 1e-6 ? 0 : st.vx;
648
+ let dash = false;
649
+ if (st.dash >= 0 && !B.dashed && t >= st.dash - 1e-6) { B.dashed = true; dash = true; }
650
+ if (B.dashed && !dash) vx = st.after;
651
+ return {x: vx / mv.speed, action: st.do === 'jump', action2: dash};
652
+ }
653
+ }
654
+ if (st.do === 'touch' || st.do === 'dash') {
655
+ const t = L.things[st.thing];
656
+ if (!t || t.open) return next() || {x: 0};
657
+ if (B.phase === 'approach') {
658
+ if (Math.abs(st.x - x) < 0.08 && grounded) { B.phase = 'push'; B.t0 = now; B.lastDash = -9; }
659
+ else return {x: steer(st.x)};
660
+ }
661
+ const tx = (t.sprite && t.sprite.active ? t.sprite.x : (t.col + 0.5) * T) / T;
662
+ const side = Math.sign(tx - x) || 1;
663
+ if (now - B.t0 > 6) return stuck(B, 'the ' + t.kind + ' ' + t.id + ' (' + t.entity + ') at column ' + t.col + ' did not open when touched' + (st.do === 'dash' ? ' with a dash' : '') + ' (the game\'s touch hook)');
664
+ if (st.do === 'dash' && now - B.lastDash > mv.cooldown + 0.1 && now >= L.control.dashReady) {
665
+ B.lastDash = now;
666
+ return {x: side, action2: true};
667
+ }
668
+ return {x: side};
669
+ }
670
+ if (st.do === 'collect') {
671
+ const t = L.things[st.thing], target = st.drop ? t && t.drop : t;
672
+ if (!target || target.taken || target.open) {
673
+ if (Math.abs(st.x - x) < 0.1 || age > 2) return next() || {x: 0};
674
+ return {x: steer(st.x)};
675
+ }
676
+ if (age > 4) return next() || {x: 0}; // not collected: the game's touch hook decides
677
+ const tx = (target.sprite && target.sprite.active ? target.sprite.x : (target.col + 0.5) * T) / T;
678
+ return {x: steer(tx)};
679
+ }
680
+ if (st.do === 'exit') return {x: steer(st.x + 0.3)};
681
+ return next() || {};
682
+ }
683
+ })();