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,712 @@
1
+ """Menus as data (L2.5): the Menu Designer writes them, code fits and checks them, the SDK
2
+ renders them (`sdk/sfflow.js`) in the game's style.
3
+
4
+ `MenuSpec` (strict; Menu Designer, Muse Spark) is the theme (colours the SDK draws panels and
5
+ text with), every screen with its title, subtitle and items (a label and an action), the
6
+ credits, and what Muse Image draws for the title background and the emblem (no text: the SDK
7
+ draws all text). Screens: title (press Enter), main, pause, settings, controls, credits,
8
+ victory, and with a way to lose game_over, and with several levels results and level_select
9
+ (its level items come from the saved progress; the spec gives its other items).
10
+
11
+ The Menu Designer writes the screens and a colour intent from the design (at G2 approval the
12
+ art is not drawn yet); `fit_theme` snaps the theme to the colours measured from the build's
13
+ locked art and repairs text contrast. `fit_menu` repairs what code can (unknown actions with a
14
+ known meaning, missing screens and items, overlong labels); `menu_problems` is the validator:
15
+ every screen reachable from the title, every action known and allowed where it is, a way out
16
+ of every screen (Escape is the SDK's: back to the screen before, resume on pause, the title
17
+ after a level ends), every label fitting the font on its panel, readable text on its panel.
18
+ """
19
+
20
+ import colorsys
21
+ import io
22
+ import re
23
+
24
+ import numpy as np
25
+ from PIL import Image
26
+ from pydantic import Field
27
+
28
+ from spriteforge.agents.models import Contract
29
+ from spriteforge.library.looks import colour_gap, hex_of, measure, rgb_of
30
+
31
+ from .art import look_palette
32
+ from .design import GameDesign
33
+ from .structure import GameStructure
34
+
35
+ SCREENS = ("title", "main", "pause", "settings", "controls", "credits", "level_select",
36
+ "results", "game_over", "victory") # fmt: skip
37
+ ACTIONS = {
38
+ "main": "open the main menu (the title screen's prompt)",
39
+ "start": "a new game from level 1",
40
+ "continue": "play on from the last level unlocked",
41
+ "level_select": "open the level select",
42
+ "settings": "open the settings",
43
+ "controls": "open the controls",
44
+ "credits": "open the credits",
45
+ "resume": "close the pause menu",
46
+ "restart": "start the current level again",
47
+ "retry": "play the level just lost again",
48
+ "next_level": "play the next level",
49
+ "title": "back to the title screen",
50
+ "back": "back to the screen before",
51
+ "difficulty": "cycle easy / normal / hard",
52
+ "fewer_flashes": "toggle fewer flashes (no screen flash or shake)",
53
+ "sound": "toggle the sound on / off (M does it anywhere)",
54
+ }
55
+ # Words a model may use for an action, mapped to the action they mean.
56
+ SYNONYMS = {
57
+ "play": "start", "new_game": "start", "new": "start", "begin": "start", "start_game": "start",
58
+ "load": "continue", "resume_game": "resume", "unpause": "resume", "options": "settings",
59
+ "quit": "title", "quit_to_title": "title", "exit": "title", "menu": "title",
60
+ "main_menu": "main", "press_start": "main", "press_enter": "main", "levels": "level_select",
61
+ "select_level": "level_select", "try_again": "retry", "restart_level": "restart",
62
+ "next": "next_level", "continue_level": "next_level", "return": "back", "close": "back",
63
+ "help": "controls", "how_to_play": "controls", "flashes": "fewer_flashes",
64
+ "reduce_flashes": "fewer_flashes", "set_difficulty": "difficulty", "audio": "sound",
65
+ "mute": "sound", "sfx": "sound", "sound_effects": "sound", "toggle_sound": "sound",
66
+ } # fmt: skip
67
+ # What each screen may offer, and what it must offer (the first item is the default).
68
+ ALLOWED = {
69
+ "title": {"main", "start"},
70
+ "main": {"start", "continue", "level_select", "settings", "controls", "credits"},
71
+ "pause": {"resume", "restart", "settings", "controls", "title"},
72
+ "settings": {"difficulty", "fewer_flashes", "sound", "controls", "back"},
73
+ "controls": {"back"},
74
+ "credits": {"back"},
75
+ "level_select": {"back"},
76
+ "results": {"next_level", "restart", "title"},
77
+ "game_over": {"retry", "title"},
78
+ "victory": {"credits", "title", "start"},
79
+ }
80
+ REQUIRED = {
81
+ "title": ["main"], "main": ["start", "settings", "credits"],
82
+ "pause": ["resume", "restart", "title"], "settings": ["difficulty", "fewer_flashes", "sound", "back"],
83
+ "controls": ["back"], "credits": ["back"], "level_select": ["back"],
84
+ "results": ["next_level", "title"], "game_over": ["retry", "title"],
85
+ "victory": ["title", "credits"],
86
+ } # fmt: skip
87
+ LABELS = {
88
+ "main": "Press Enter", "start": "Start", "continue": "Continue", "level_select": "Level select",
89
+ "settings": "Settings", "controls": "Controls", "credits": "Credits", "resume": "Resume",
90
+ "restart": "Restart level", "retry": "Retry", "next_level": "Next level",
91
+ "title": "Quit to title", "back": "Back", "difficulty": "Difficulty",
92
+ "fewer_flashes": "Fewer flashes", "sound": "Sound",
93
+ } # fmt: skip
94
+ TITLES = {
95
+ "title": "", "main": "", "pause": "Paused", "settings": "Settings", "controls": "Controls",
96
+ "credits": "Credits", "level_select": "Level select", "results": "Level clear",
97
+ "game_over": "Game over", "victory": "Victory",
98
+ } # fmt: skip
99
+ DIFFICULTY = {"easy": 0.75, "normal": 1.0, "hard": 1.35}
100
+ VALUED = {"difficulty", "fewer_flashes", "sound"} # settings the SDK shows with their value
101
+ MAX_ITEMS = 7
102
+ # The SDK's text: a monospace font at 8 px (items), 12 px (screen titles), 16 px (the game's
103
+ # title on the title screen), times the art scale; a character is at most 0.62 em wide.
104
+ CHAR_EM, ITEM_PX, TITLE_PX, BIG_PX = 0.62, 8, 12, 16
105
+ PANEL_MAX, PANEL_PAD = 260, 10 # panel width cap and inner padding (px at scale 1)
106
+ MARK = 2 # characters of the highlight marker ("> ") and the value shown after settings
107
+ VALUE = len(": normal")
108
+
109
+
110
+ class MenuItem(Contract):
111
+ label: str = Field(description="what the player reads, short (e.g. 'Start', 'Settings')")
112
+ action: str = Field(description="one of: " + ", ".join(ACTIONS))
113
+
114
+
115
+ class Screen(Contract):
116
+ id: str = Field(description="one of: " + ", ".join(SCREENS))
117
+ title: str = Field(description="the heading ('' on the title and main screens: the game's "
118
+ "title is shown there)") # fmt: skip
119
+ subtitle: str = Field(description="one short line under the heading, or ''")
120
+ items: list[MenuItem] = Field(description="in order; the first is selected when it opens")
121
+
122
+
123
+ class Theme(Contract):
124
+ panel: str = Field(description="#RRGGBB of the menu panel (dark, from the game's look)")
125
+ border: str = Field(description="#RRGGBB of the panel's frame")
126
+ text: str = Field(description="#RRGGBB of item text (readable on the panel)")
127
+ highlight: str = Field(description="#RRGGBB of the selected item and headings")
128
+ dim: str = Field(description="#RRGGBB of locked items (locked levels)")
129
+ style: str = Field(description="panel style: framed (a 1 px frame), double (two frames) or solid")
130
+
131
+
132
+ class MenuSpec(Contract):
133
+ title: str = Field(description="the game's title as the title screen shows it")
134
+ subtitle: str = Field(description="a short tagline under the title, or ''")
135
+ theme: Theme
136
+ screens: list[Screen]
137
+ credits: list[str] = Field(description="leave [] (code writes the credits: what made the "
138
+ "game and the art's credits; never invent people or "
139
+ "music)") # fmt: skip
140
+ title_art: str = Field(description="what the title screen's background picture shows (a "
141
+ "scene from the game; never text)") # fmt: skip
142
+ emblem: str = Field(description="the emblem over the title: one object or creature of the "
143
+ "game on a plain background (never text)") # fmt: skip
144
+
145
+ def screen(self, sid: str) -> Screen | None:
146
+ return next((s for s in self.screens if s.id == sid), None)
147
+
148
+
149
+ # --- what a game needs ------------------------------------------------------------------------
150
+
151
+
152
+ def needed_screens(structure: GameStructure) -> list[str]:
153
+ out = ["title", "main", "pause", "settings", "controls", "credits", "victory"]
154
+ if structure.lose.strip():
155
+ out.append("game_over")
156
+ if len(structure.levels) > 1:
157
+ out += ["results", "level_select"]
158
+ return [s for s in SCREENS if s in out]
159
+
160
+
161
+ def allowed(sid: str, structure: GameStructure) -> set[str]:
162
+ acts = set(ALLOWED.get(sid, set()))
163
+ if len(structure.levels) < 2:
164
+ acts -= {"continue", "level_select", "next_level"}
165
+ return acts
166
+
167
+
168
+ def required(sid: str, structure: GameStructure) -> list[str]:
169
+ return [a for a in REQUIRED.get(sid, []) if a in allowed(sid, structure)]
170
+
171
+
172
+ def action_of(text: str) -> str:
173
+ key = re.sub(r"[^a-z0-9]+", "_", text.lower()).strip("_")
174
+ return key if key in ACTIONS else SYNONYMS.get(key, key)
175
+
176
+
177
+ # --- the font and the panel -------------------------------------------------------------------
178
+
179
+
180
+ def panel_width(screen_w: int, scale: int = 1) -> float:
181
+ return min(screen_w / scale - 32, PANEL_MAX)
182
+
183
+
184
+ def text_width(text: str, px: int) -> float:
185
+ return len(text) * px * CHAR_EM
186
+
187
+
188
+ def max_chars(screen_w: int, scale: int, px: int, extra: int = 0) -> int:
189
+ room = panel_width(screen_w, scale) - 2 * PANEL_PAD
190
+ return int(room // (px * CHAR_EM)) - extra
191
+
192
+
193
+ def fits(text: str, screen_w: int, scale: int, px: int, extra: int = 0) -> bool:
194
+ return len(text) <= max_chars(screen_w, scale, px, extra)
195
+
196
+
197
+ def clip(text: str, limit: int) -> str:
198
+ text = re.sub(r"\s+", " ", text).strip()
199
+ if len(text) <= limit:
200
+ return text
201
+ cut = text[: max(1, limit)].rsplit(" ", 1)[0]
202
+ return cut if len(cut) >= limit // 2 else text[:limit]
203
+
204
+
205
+ # --- colours and contrast -----------------------------------------------------------------------
206
+
207
+ HEX = re.compile(r"^#[0-9A-Fa-f]{6}$")
208
+
209
+
210
+ def luminance(hex_code: str) -> float:
211
+ rgb = np.array(rgb_of(hex_code)) / 255
212
+ lin = np.where(rgb <= 0.03928, rgb / 12.92, ((rgb + 0.055) / 1.055) ** 2.4)
213
+ return float(lin @ np.array([0.2126, 0.7152, 0.0722]))
214
+
215
+
216
+ def contrast(a: str, b: str) -> float:
217
+ """WCAG contrast ratio of two colours (1-21)."""
218
+ la, lb = sorted((luminance(a), luminance(b)), reverse=True)
219
+ return (la + 0.05) / (lb + 0.05)
220
+
221
+
222
+ def saturation(hex_code: str) -> float:
223
+ return colorsys.rgb_to_hsv(*(c / 255 for c in rgb_of(hex_code)))[1]
224
+
225
+
226
+ def value(hex_code: str) -> float:
227
+ return max(rgb_of(hex_code)) / 255
228
+
229
+
230
+ def mix(a: str, b: str, t: float) -> str:
231
+ return hex_of(np.array(rgb_of(a)) * (1 - t) + np.array(rgb_of(b)) * t)
232
+
233
+
234
+ def readable(colour: str, panel: str, ratio: float) -> str:
235
+ """`colour`, moved toward white (or black on a light panel) until it reads on `panel`."""
236
+ if contrast(colour, panel) >= ratio:
237
+ return colour.upper()
238
+ toward = "#FFFFFF" if luminance(panel) < 0.4 else "#000000"
239
+ for step in range(1, 21):
240
+ c = mix(colour, toward, step / 20)
241
+ if contrast(c, panel) >= ratio:
242
+ return c
243
+ return toward
244
+
245
+
246
+ MIN_TEXT, MIN_HIGHLIGHT, MIN_DIM, MIN_BORDER = 4.5, 3.0, 1.6, 1.4
247
+ SNAP_GAP = 25 # delta E: an art colour this close to the designer's stands in for it
248
+
249
+
250
+ def default_theme(look: str = "") -> Theme:
251
+ named = look_palette(look)
252
+ accent = next((c for c in named if 0.15 < luminance(c) < 0.8), "#F4D35E")
253
+ return Theme(panel="#10121C", border=accent, text="#E8E8F0", highlight=accent, dim="#6A6F80",
254
+ style="framed") # fmt: skip
255
+
256
+
257
+ def art_colours(pngs: list[bytes]) -> list[tuple[str, float]]:
258
+ """(hex, weight) of the main colours measured from the locked art, all images together."""
259
+ weights: dict[str, float] = {}
260
+ for data in pngs:
261
+ try:
262
+ look = measure(Image.open(io.BytesIO(data)))
263
+ except Exception: # noqa: BLE001, S112 -- an unreadable image adds no colours
264
+ continue
265
+ for c in look.colours:
266
+ weights[c.hex] = weights.get(c.hex, 0) + c.share
267
+ return sorted(weights.items(), key=lambda kv: -kv[1])
268
+
269
+
270
+ def nearest(colour: str, palette: list[str]) -> str:
271
+ target = np.array(rgb_of(colour), dtype=float)
272
+ return min(palette, key=lambda c: float(np.sum((np.array(rgb_of(c)) - target) ** 2)))
273
+
274
+
275
+ def fit_theme(theme: Theme, colours: list[tuple[str, float]]) -> tuple[Theme, list[str]]:
276
+ """The theme in the art's measured colours: the panel is the art's darkest colour (darkened
277
+ to a panel), the highlight and frame the art colour nearest the designer's, then text,
278
+ highlight, dim and frame are made readable on the panel. Without art, only contrast."""
279
+ notes = []
280
+ t = theme.model_copy()
281
+ for name in ("panel", "border", "text", "highlight", "dim"):
282
+ if not HEX.match(getattr(t, name)):
283
+ setattr(t, name, getattr(default_theme(), name))
284
+ notes.append(f"theme {name} was not a #RRGGBB colour: the default is used")
285
+ if t.style not in {"framed", "double", "solid"}:
286
+ notes.append(f"panel style {t.style!r} is not framed, double or solid: framed is used")
287
+ t.style = "framed"
288
+ palette = [c for c, _ in colours]
289
+ if palette:
290
+ darkest = min(palette, key=luminance)
291
+ t.panel = mix(darkest, "#000000", 0.55) if luminance(darkest) > 0.02 else darkest
292
+ # The highlight is the art's colourful colour nearest the designer's: the selected item
293
+ # must stand out from the plain text, not just be readable.
294
+ vivid = [c for c in palette if saturation(c) >= 0.3 and value(c) >= 0.35]
295
+ want = theme.highlight if HEX.match(theme.highlight) else "#F4D35E"
296
+ near = min(vivid, key=lambda c: colour_gap(c, want)) if vivid else None
297
+ # Snap to the art only when it has a colour like the one asked for; a colour the art does
298
+ # not have stays (live 2026-11-02: "acid green" was snapped to the art's gold).
299
+ t.highlight = near if near and colour_gap(near, want) <= SNAP_GAP else want
300
+ if t.highlight == want and near:
301
+ notes.append(f"highlight {want} kept: the art has no colour like it (nearest {near})")
302
+ t.border = mix(t.highlight, t.panel, 0.3)
303
+ lightest = max(palette, key=luminance)
304
+ t.text = mix(lightest, "#FFFFFF", 0.5)
305
+ t.dim = mix(t.text, t.panel, 0.55)
306
+ notes.append("theme colours taken from the locked art's measured colours")
307
+ # The highlight reads at least as well as item text (4.5); the validator accepts 3.
308
+ for name, ratio in (("text", MIN_TEXT), ("highlight", MIN_TEXT), ("dim", MIN_DIM),
309
+ ("border", MIN_BORDER)): # fmt: skip
310
+ before = getattr(t, name)
311
+ after = readable(before, t.panel, ratio)
312
+ if after.upper() != before.upper():
313
+ setattr(t, name, after)
314
+ notes.append(f"theme {name} {before} was hard to read on the panel: {after}")
315
+ for name in ("panel", "border", "text", "highlight", "dim"):
316
+ setattr(t, name, getattr(t, name).upper())
317
+ return t, notes
318
+
319
+
320
+ class MenuRecord(Contract):
321
+ """The menus of a game as the run keeps them (game/menus/vM.json): the spec fitted by
322
+ code, the structure it was fitted to, what code repaired and what it could not."""
323
+
324
+ spec: MenuSpec
325
+ structure: GameStructure
326
+ notes: list[str]
327
+ problems: list[str]
328
+ retried: bool
329
+ by: str
330
+ why: str = "" # "written from design v1", "G3: <the human's words>"
331
+
332
+
333
+ # --- the offline Menu Designer, fit and the validator -------------------------------------------
334
+
335
+
336
+ def fallback_menu(design: GameDesign, structure: GameStructure) -> MenuSpec:
337
+ """Offline Menu Designer: every screen the game needs with its plain labels, a theme from
338
+ the design's look words."""
339
+ screens = []
340
+ for sid in needed_screens(structure):
341
+ acts = list(REQUIRED.get(sid, []))
342
+ if sid == "main":
343
+ acts = ["start", "continue", "level_select", "settings", "controls", "credits"]
344
+ if sid == "pause":
345
+ acts = ["resume", "restart", "settings", "title"]
346
+ if sid == "victory": # Enter plays again (as Enter after a win always did)
347
+ acts = ["start", "credits", "title"]
348
+ acts = [a for a in acts if a in allowed(sid, structure)]
349
+ subtitle = {"game_over": design.lose, "victory": structure.win}.get(sid, "")
350
+ label = lambda a: "Play again" if (sid, a) == ("victory", "start") else LABELS[a]
351
+ screens.append(Screen(id=sid, title=TITLES[sid], subtitle=subtitle[:60],
352
+ items=[MenuItem(label=label(a), action=a) for a in acts])) # fmt: skip
353
+ return MenuSpec(title=design.title, subtitle=design.pitch.split(".")[0][:60],
354
+ theme=default_theme(design.look), screens=screens,
355
+ credits=credit_lines(design),
356
+ title_art=f"{design.world}; {design.look}",
357
+ emblem=next((f"{e.look}" for e in design.entities if e.role == "player"), design.title)) # fmt: skip
358
+
359
+
360
+ def fit_menu(spec: MenuSpec, structure: GameStructure, design: GameDesign,
361
+ screen_w: int = 320, scale: int = 1) -> tuple[MenuSpec, list[str]]: # fmt: skip
362
+ """Repair what code can: actions named by a synonym, items not allowed where they are (or
363
+ in this game), duplicates, missing screens and items, empty or overlong labels and titles,
364
+ theme colours that are no colours."""
365
+ notes: list[str] = []
366
+ need = needed_screens(structure)
367
+ fallback = fallback_menu(design, structure)
368
+ by_id: dict[str, Screen] = {}
369
+ for s in spec.screens:
370
+ sid = action_of(s.id) if s.id not in SCREENS else s.id
371
+ sid = {"gameover": "game_over", "levels": "level_select", "options": "settings",
372
+ "win": "victory", "help": "controls"}.get(sid, sid) # fmt: skip
373
+ if sid not in need:
374
+ notes.append(f"screen {s.id!r} dropped: " + ("not a screen the SDK has" if sid not in SCREENS
375
+ else "this game does not need it")) # fmt: skip
376
+ continue
377
+ if sid in by_id:
378
+ notes.append(f"a second {sid} screen dropped")
379
+ continue
380
+ by_id[sid] = s.model_copy(update={"id": sid})
381
+ screens = []
382
+ item_room = max_chars(screen_w, scale, ITEM_PX, MARK)
383
+ for sid in need:
384
+ s = by_id.get(sid)
385
+ if s is None:
386
+ notes.append(f"screen {sid} was missing: added with its plain items")
387
+ s = fallback.screen(sid)
388
+ items, seen = [], set()
389
+ for it in s.items:
390
+ act = action_of(it.action)
391
+ if act not in ACTIONS:
392
+ notes.append(f"{sid}: item {it.label!r} dropped: unknown action {it.action!r}")
393
+ continue
394
+ if act not in allowed(sid, structure) or act in seen:
395
+ why = "repeated" if act in seen else "not allowed on this screen in this game"
396
+ notes.append(f"{sid}: item {it.label!r} ({act}) dropped: {why}")
397
+ continue
398
+ seen.add(act)
399
+ room = item_room - (VALUE if act in VALUED else 0)
400
+ said = it.label
401
+ if act in VALUED and SETTING_VALUE.search(said):
402
+ # The SDK shows the setting's value after the label (live 2026-11-02: the Menu
403
+ # Designer wrote "Difficulty: Normal", which would read "Difficulty: Normal: hard").
404
+ said = SETTING_VALUE.sub("", said)
405
+ notes.append(f"{sid}: label {it.label!r} carried its value: {said!r} (the SDK adds it)")
406
+ label = clip(said, room) or LABELS[act]
407
+ if label != re.sub(r"\s+", " ", said).strip():
408
+ notes.append(f"{sid}: label {it.label!r} shortened to {label!r} to fit the panel")
409
+ items.append(MenuItem(label=label, action=act))
410
+ for act in required(sid, structure):
411
+ if act not in seen:
412
+ notes.append(f"{sid}: the {act} item was missing: added")
413
+ ways_out = [i for i, x in enumerate(items) if x.action in {"back", "title"}]
414
+ at = ways_out[0] if ways_out and act not in {"back", "title"} else len(items)
415
+ items.insert(at, MenuItem(label=LABELS[act], action=act))
416
+ seen.add(act)
417
+ if len(items) > MAX_ITEMS:
418
+ notes.append(f"{sid}: {len(items)} items, at most {MAX_ITEMS}: the last ones dropped")
419
+ keep = set(required(sid, structure))
420
+ extra = [i for i in items if i.action not in keep][: MAX_ITEMS - len(keep)]
421
+ items = [i for i in items if i.action in keep or i in extra]
422
+ title = clip(s.title, max_chars(screen_w, scale, TITLE_PX))
423
+ subtitle = clip(s.subtitle, max_chars(screen_w, scale, ITEM_PX))
424
+ screens.append(Screen(id=sid, title=title, subtitle=subtitle, items=items))
425
+ # A screen nothing opens gets an item that opens it (main first, then settings, pause).
426
+ probe = spec.model_copy(update={"screens": screens})
427
+ for sid in [x for x in need if x not in reachable(probe, structure)]:
428
+ host = next((h for h in ("main", "settings", "pause") if sid in allowed(h, structure)
429
+ and len(probe.screen(h).items) < MAX_ITEMS), None) # fmt: skip
430
+ if host:
431
+ items = probe.screen(host).items
432
+ back = [i for i in items if i.action in {"back", "title"}]
433
+ rest = [i for i in items if i not in back]
434
+ probe.screen(host).items = [*rest, MenuItem(label=LABELS[sid], action=sid), *back]
435
+ notes.append(f"the {sid} screen could not be reached: {host} opens it now")
436
+ title = clip(spec.title, max_chars(screen_w, scale, BIG_PX)) or clip(design.title, max_chars(screen_w, scale, BIG_PX))
437
+ if title != spec.title.strip():
438
+ notes.append(f"title {spec.title!r} shown as {title!r}")
439
+ theme, theme_notes = fit_theme(spec.theme, [])
440
+ fitted = spec.model_copy(update={
441
+ "title": title, "subtitle": clip(spec.subtitle, max_chars(screen_w, scale, ITEM_PX)),
442
+ "theme": theme, "screens": screens,
443
+ "credits": credit_lines(design),
444
+ "title_art": spec.title_art.strip()[:400] or fallback.title_art,
445
+ "emblem": spec.emblem.strip()[:300] or fallback.emblem,
446
+ }) # fmt: skip
447
+ said = [c.strip() for c in spec.credits if c.strip()]
448
+ if said and said != credit_lines(design):
449
+ notes.append("credits are written by code; the designer's lines were dropped: "
450
+ + "; ".join(said)[:200]) # fmt: skip
451
+ return fitted, notes + theme_notes
452
+
453
+
454
+ SETTING_VALUE = re.compile(r"\s*[:=-]?\s*\(?\b(easy|normal|hard|on|off)\b\)?\s*$", re.IGNORECASE)
455
+
456
+
457
+ def credit_lines(design: GameDesign) -> list[str]:
458
+ """The credits code writes: only what is true of every SpriteForge game (the art's credits
459
+ are added per build). A model's credits invented people and music (live 2026-11-02: "Made
460
+ by the Goo Squad", "Music: Chiptune Blips" for a game without sound)."""
461
+ return [clip(design.title, 36), "Made with SpriteForge", "Design and code: Muse Spark",
462
+ "Art: Muse Image and the art library"] # fmt: skip
463
+
464
+
465
+ def reachable(spec: MenuSpec, structure: GameStructure) -> set[str]:
466
+ """Screens a player can reach from the title: through items, and through play (Escape
467
+ pauses, finishing a level shows results, losing game over, the last level victory)."""
468
+ opens = {"main": "main", "level_select": "level_select", "settings": "settings",
469
+ "controls": "controls", "credits": "credits", "title": "title"} # fmt: skip
470
+ plays = {"start", "continue", "resume", "restart", "retry", "next_level"}
471
+ have = {s.id for s in spec.screens}
472
+ seen, todo, playing = set(), ["title"] if "title" in have else [], False
473
+ while todo:
474
+ sid = todo.pop()
475
+ if sid in seen:
476
+ continue
477
+ seen.add(sid)
478
+ s = spec.screen(sid)
479
+ for it in s.items if s else []:
480
+ if it.action in opens and opens[it.action] in have:
481
+ todo.append(opens[it.action])
482
+ playing = playing or it.action in plays
483
+ if playing:
484
+ todo += [x for x in ("pause", "results", "game_over", "victory") if x in have]
485
+ if len(structure.levels) < 2:
486
+ todo = [x for x in todo if x != "results"]
487
+ if not structure.lose.strip():
488
+ todo = [x for x in todo if x != "game_over"]
489
+ return seen
490
+
491
+
492
+ ESCAPE = {"pause": "resume", "results": "title", "game_over": "title", "victory": "title"}
493
+ EXITS = {"back", "resume", "title", "retry", "next_level", "start", "continue", "restart", "main"}
494
+
495
+
496
+ def menu_problems(spec: MenuSpec, structure: GameStructure, screen_w: int = 320,
497
+ scale: int = 1) -> list[str]: # fmt: skip
498
+ """What is wrong with a menu spec (empty when the SDK can render it as the rules say)."""
499
+ out = []
500
+ ids = [s.id for s in spec.screens]
501
+ for sid in ids:
502
+ if sid not in SCREENS:
503
+ out.append(f"unknown screen {sid!r}")
504
+ for sid in needed_screens(structure):
505
+ if sid not in ids:
506
+ out.append(f"the {sid} screen is missing")
507
+ for sid in sorted(set(ids) & set(SCREENS) - reachable(spec, structure)):
508
+ out.append(f"the {sid} screen cannot be reached from the title")
509
+ item_room = max_chars(screen_w, scale, ITEM_PX, MARK)
510
+ for s in spec.screens:
511
+ acts = [it.action for it in s.items]
512
+ for it in s.items:
513
+ if it.action not in ACTIONS:
514
+ out.append(f"{s.id}: item {it.label!r} has an unknown action {it.action!r}")
515
+ elif s.id in SCREENS and it.action not in allowed(s.id, structure):
516
+ out.append(f"{s.id}: item {it.label!r} ({it.action}) is not allowed there")
517
+ room = item_room - (VALUE if it.action in VALUED else 0)
518
+ if not it.label.strip():
519
+ out.append(f"{s.id}: an item has no label")
520
+ elif len(it.label) > room:
521
+ out.append(f"{s.id}: label {it.label!r} is {len(it.label)} characters; "
522
+ f"{room} fit the panel") # fmt: skip
523
+ for act in required(s.id, structure) if s.id in SCREENS else []:
524
+ if act not in acts:
525
+ out.append(f"{s.id}: the {act} item is missing")
526
+ if s.id in SCREENS and s.id != "title" and not (set(acts) & EXITS) and s.id not in ESCAPE:
527
+ out.append(f"{s.id}: no item leads out of it (back, resume or title)")
528
+ if s.id in ESCAPE and ESCAPE[s.id] == "title" and "title" not in ids:
529
+ out.append(f"{s.id}: Escape leads to the title screen, which is missing")
530
+ if len(s.title) > max_chars(screen_w, scale, TITLE_PX):
531
+ out.append(f"{s.id}: the heading {s.title!r} does not fit the panel")
532
+ if len(s.items) > MAX_ITEMS:
533
+ out.append(f"{s.id}: {len(s.items)} items; at most {MAX_ITEMS}")
534
+ if not spec.title.strip():
535
+ out.append("the title screen has no title")
536
+ elif len(spec.title) > max_chars(screen_w, scale, BIG_PX):
537
+ out.append(f"the title {spec.title!r} does not fit the screen")
538
+ t = spec.theme
539
+ colours = {n: getattr(t, n) for n in ("panel", "border", "text", "highlight", "dim")}
540
+ bad = [n for n, c in colours.items() if not HEX.match(c)]
541
+ out += [f"theme {n} {colours[n]!r} is not a #RRGGBB colour" for n in bad]
542
+ if not bad:
543
+ for name, ratio in (("text", MIN_TEXT), ("highlight", MIN_HIGHLIGHT), ("dim", MIN_DIM)):
544
+ got = contrast(colours[name], t.panel)
545
+ if got < ratio:
546
+ out.append(f"theme {name} {colours[name]} on the panel {t.panel} has contrast "
547
+ f"{got:.1f}; at least {ratio:g} reads") # fmt: skip
548
+ return out
549
+
550
+
551
+ def checked(spec: MenuSpec, structure: GameStructure, design: GameDesign, by: str,
552
+ retried: bool = False, notes: list[str] = (), why: str = "",
553
+ screen_w: int = 320, scale: int = 1) -> MenuRecord: # fmt: skip
554
+ """A Menu Designer's answer fitted and checked by code."""
555
+ fitted, repairs = fit_menu(spec, structure, design, screen_w, scale)
556
+ return MenuRecord(spec=fitted, structure=structure, notes=[*notes, *repairs],
557
+ problems=menu_problems(fitted, structure, screen_w, scale),
558
+ retried=retried, by=by, why=why) # fmt: skip
559
+
560
+
561
+ def refit(record: MenuRecord, structure: GameStructure, design: GameDesign) -> MenuRecord:
562
+ """The same menus for a changed structure (a design change: more or fewer levels, a way to
563
+ lose or none), fitted again by code; no model call."""
564
+ if record.structure == structure:
565
+ return record
566
+ again = checked(record.spec, structure, design, record.by, record.retried, record.notes,
567
+ f"refitted to design changes ({record.why})") # fmt: skip
568
+ return again
569
+
570
+
571
+ def retry_prompt(prompt: str, problems: list[str]) -> str:
572
+ return (prompt + "\n\nCode checked your answer and found these problems; answer again with "
573
+ "them fixed and everything else kept:\n" + "\n".join(f"* {p}" for p in problems))
574
+
575
+
576
+ # --- the Menu Designer's prompts -------------------------------------------------------------
577
+
578
+
579
+ def menu_rules(structure: GameStructure, screen_w: int = 320, scale: int = 1) -> str:
580
+ screens = "\n".join(
581
+ f"* {sid}: actions {', '.join(sorted(allowed(sid, structure)))}; must have "
582
+ f"{', '.join(required(sid, structure))}"
583
+ for sid in needed_screens(structure)
584
+ )
585
+ actions = "\n".join(f"* {a}: {what}" for a, what in ACTIONS.items())
586
+ return f"""The SDK renders every screen with its built-in monospace pixel font in the theme's
587
+ colours and handles the keys: arrows/WASD move the highlight, Enter/Space pick, Escape goes back
588
+ (on pause it resumes; after a level ends it goes to the title), the mouse works too. It shows the
589
+ title art behind the title and main screens, and the level's own picture behind pause, results,
590
+ game over and victory. Level select lists the levels from the saved progress (locked ones dim);
591
+ give it only a Back item. Settings items show their value after the label (Difficulty: normal):
592
+ write the label alone ('Difficulty', never 'Difficulty: Normal'). Code writes the credits.
593
+
594
+ Screens this game has (only these):
595
+ {screens}
596
+
597
+ Actions:
598
+ {actions}
599
+
600
+ Limits: at most {MAX_ITEMS} items a screen; item labels at most
601
+ {max_chars(screen_w, scale, ITEM_PX, MARK)} characters ({max_chars(screen_w, scale, ITEM_PX, MARK) - VALUE} for difficulty, fewer_flashes and sound), headings at most
602
+ {max_chars(screen_w, scale, TITLE_PX)}, the game's title at most {max_chars(screen_w, scale, BIG_PX)}. Text must read on the
603
+ panel (contrast 4.5 for item text, 3 for the highlight). Code fits the theme to the colours of the
604
+ game's locked art; give the colour intent from the design's look.
605
+ Write labels in the game's voice but keep their meaning plain (a player must know what 'Start'
606
+ and 'Quit to title' do). Muse Image draws the title background and the emblem from your two
607
+ descriptions in the game's art style; they never contain text or letters."""
608
+
609
+
610
+ def menu_prompt(design: GameDesign, structure: GameStructure, context: str = "",
611
+ screen_w: int = 320, scale: int = 1) -> str: # fmt: skip
612
+ return f"""Design the menus of this game as data: a MenuSpec with the theme, every screen and
613
+ its items, the credits, and what the title background and the emblem show.
614
+
615
+ {menu_rules(structure, screen_w, scale)}
616
+
617
+ Game: {design.title}. {design.pitch}
618
+ Look: {design.look}
619
+ Controls: {design.controls}
620
+ Win: {structure.win}. Lose: {structure.lose or "(cannot be lost)"}
621
+ Levels: {"; ".join(f"{lv.n}. {lv.name}: {lv.goal}" for lv in structure.levels)}
622
+ """ + (f"\nThe game's record (read-only excerpts):\n{context.strip()}\n" if context.strip() else "")
623
+
624
+
625
+ def menu_revision_prompt(spec: MenuSpec, feedback: str, design: GameDesign,
626
+ structure: GameStructure, screen_w: int = 320, scale: int = 1) -> str: # fmt: skip
627
+ return f"""Revise these menus for the human's feedback. Change only what the feedback asks
628
+ for; keep every other screen, label and colour as it is.
629
+
630
+ {menu_rules(structure, screen_w, scale)}
631
+
632
+ Game: {design.title}. Look: {design.look}
633
+
634
+ Feedback:
635
+ {feedback.strip()}
636
+
637
+ Current menus:
638
+ {spec.model_dump_json(indent=1)}"""
639
+
640
+
641
+ def offline_revision(spec: MenuSpec, feedback: str) -> MenuSpec:
642
+ """The offline Menu Designer's revision: a colour the feedback names becomes the highlight
643
+ and frame (the panel when it speaks of the panel or background); otherwise as it was."""
644
+ named = look_palette(feedback)
645
+ if not named:
646
+ return spec
647
+ theme = spec.theme.model_copy()
648
+ if re.search(r"\b(panel|background|box)\b", feedback, re.IGNORECASE):
649
+ theme.panel = named[0]
650
+ else:
651
+ theme.highlight = theme.border = named[0]
652
+ return spec.model_copy(update={"theme": theme})
653
+
654
+
655
+ # --- what the SDK loads ---------------------------------------------------------------------------
656
+
657
+
658
+ def menus_script(spec: MenuSpec, structure: GameStructure, design: GameDesign,
659
+ credits: list[str] = (), art: dict | None = None) -> dict: # fmt: skip
660
+ """window.SF_MENUS (menus.js). `art`: {"title": image id, "emblem": image id} of the title
661
+ art in the build's assets (absent: the SDK draws a plain panel)."""
662
+ lines = [c for c in spec.credits if c.strip()]
663
+ lines += [clip(c.split(" (")[0], 46) for c in credits if c.strip()][:6]
664
+ return {
665
+ "title": spec.title,
666
+ "subtitle": spec.subtitle,
667
+ "theme": spec.theme.model_dump(),
668
+ "screens": {s.id: {"title": s.title, "subtitle": s.subtitle,
669
+ "items": [i.model_dump() for i in s.items]} for s in spec.screens}, # fmt: skip
670
+ "levels": [lv.model_dump() for lv in structure.levels],
671
+ "can_lose": bool(structure.lose.strip()),
672
+ "controls": control_lines(design.controls),
673
+ "credits": lines[:8],
674
+ "difficulty": DIFFICULTY,
675
+ "art": art or {},
676
+ }
677
+
678
+
679
+ def control_lines(controls: str, width: int = 36, most: int = 6) -> list[str]:
680
+ """The design's controls as lines that fit the panel: split at ';' and line breaks, then at
681
+ ',' and words when a part is too long (live 2026-11-02: one long sentence was clipped)."""
682
+ out = []
683
+ for part in (p.strip() for p in re.split(r"[;\n]", controls) if p.strip()):
684
+ line = ""
685
+ for word in re.split(r"(?<=,)\s+|\s+", part):
686
+ if line and len(line) + 1 + len(word) > width:
687
+ out.append(line.rstrip(","))
688
+ line = word
689
+ else:
690
+ line = f"{line} {word}".strip()
691
+ if line:
692
+ out.append(line.rstrip(","))
693
+ return out[:most]
694
+
695
+
696
+ def menus_markdown(spec: MenuSpec, notes: list[str] = (), problems: list[str] = ()) -> str:
697
+ t = spec.theme
698
+ screens = "\n\n".join(
699
+ f"## {s.id}" + (f": {s.title}" if s.title else "") + (f"\n_{s.subtitle}_" if s.subtitle else "")
700
+ + "\n" + "\n".join(f"{i}. {it.label} ({it.action})" for i, it in enumerate(s.items, 1))
701
+ for s in spec.screens
702
+ ) # fmt: skip
703
+ return (
704
+ f"# Menus: {spec.title}\n\n{spec.subtitle}\n\n"
705
+ f"**Theme:** panel {t.panel}, frame {t.border} ({t.style}), text {t.text}, highlight "
706
+ f"{t.highlight}, locked {t.dim} \n**Title art:** {spec.title_art} \n"
707
+ f"**Emblem:** {spec.emblem}\n\n{screens}\n\n## Credits\n"
708
+ + ("\n".join(f"- {c}" for c in spec.credits) or "- (none)")
709
+ + ("\n\n## Repaired by code\n" + "\n".join(f"- {n}" for n in notes) if notes else "")
710
+ + ("\n\n## Problems code could not fix\n" + "\n".join(f"- {p}" for p in problems) if problems else "")
711
+ + "\n"
712
+ )