Spaces:
Sleeping

byte-vortex commited on
Commit
24ef39b
ยท
verified ยท
1 Parent(s): ab19780

Deploy Myco from CI

Browse files
Files changed (1) hide show
  1. ui/renderes.py +624 -0
ui/renderes.py ADDED
@@ -0,0 +1,624 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Markdown renderers for the Myco Gradio interface."""
2
+
3
+ from html import escape
4
+ from game.progression import (
5
+ AREA_UNLOCKS, current_area, next_area, next_mystery,
6
+ revealed_mysteries, unlocked_areas,
7
+ )
8
+ from game.state import CollectionState, EMPTY_DEX, MushroomState
9
+ from models.mushroom import Mushroom
10
+
11
+ import json
12
+ import ast
13
+
14
+ POISONOUS_MUSHROOM_NAMES = {
15
+ "Ghost Gill", "Pepper Pixie", "Ruby Knuckle", "Clockwork Chanterelle",
16
+ }
17
+
18
+ # ---------------------------------------------------------------------------
19
+ # Static UI fragments
20
+ # ---------------------------------------------------------------------------
21
+
22
+ def hero_markdown() -> str:
23
+ return """
24
+ <div class="myco-hero">
25
+ <div class="myco-mascot">๐Ÿ„</div>
26
+ <div>
27
+ <p class="eyebrow">Tiny AI forest game</p>
28
+ <h1>Myco</h1>
29
+ <p>Follow an AI mushroom companion through a glowing forest. Every discovery starts with Myco's intuition.</p>
30
+ </div>
31
+ </div>
32
+ """
33
+
34
+ def myco_talking_markdown(text: str) -> str:
35
+ safe_text = escape(str(text))
36
+ return f'''
37
+ <div class="myco-speech-container">
38
+ <div class="myco-bubble">
39
+ <span class="bubble-icon">๐Ÿ’ฌ</span>
40
+ <p class="myco-thought">{safe_text}</p>
41
+ </div>
42
+ </div>
43
+ '''
44
+
45
+ def home_forest_markdown() -> str:
46
+ return """
47
+ <div class="home-forest-postcard" aria-label="Animated Myco forest postcard">
48
+ <style>
49
+ .home-myco-wrapper, .home-brown-wrapper { position:relative; display:inline-block; }
50
+ .home-spore {
51
+ position:absolute; left:50%; top:20%; width:4px; height:4px;
52
+ background:#a8ffb2; border-radius:50%; filter:blur(0.5px);
53
+ box-shadow:0 0 6px #52ff6b,0 0 10px #fff;
54
+ opacity:0; pointer-events:none;
55
+ animation:floatHomeSpore var(--duration) ease-out infinite;
56
+ animation-delay:var(--delay);
57
+ }
58
+ @keyframes floatHomeSpore {
59
+ 0% { transform:translate(0,0) scale(1); opacity:0; }
60
+ 15% { opacity:1; }
61
+ 80% { opacity:0.7; }
62
+ 100% { transform:translate(var(--x),var(--y)) scale(0.2); opacity:0; }
63
+ }
64
+ </style>
65
+ <div class="home-sky">
66
+ <span class="home-milky-way">๐ŸŒŒ</span>
67
+ <span class="home-star star-one">โœจ</span>
68
+ <span class="home-star star-two">โœฆ</span>
69
+ <span class="home-star star-three">โœง</span>
70
+ </div>
71
+ <div class="home-forest-floor">
72
+ <span class="home-tree left">๐ŸŒฒ</span>
73
+ <span class="home-grass grass-left">๐ŸŒฟ</span>
74
+ <span class="home-myco-wrapper">
75
+ <span class="home-myco">๐Ÿ„</span>
76
+ <span class="home-spore" style="--x:-25px;--y:-45px;--duration:3.5s;--delay:0s;"></span>
77
+ <span class="home-spore" style="--x:20px;--y:-35px;--duration:4.2s;--delay:0.8s;"></span>
78
+ <span class="home-spore" style="--x:-5px;--y:-60px;--duration:3s;--delay:1.5s;"></span>
79
+ </span>
80
+ <span class="home-brown-wrapper">
81
+ <span class="home-brown-mushroom">๐Ÿ„โ€๐ŸŸซ</span>
82
+ <span class="home-spore" style="--x:-15px;--y:-40px;--duration:3.8s;--delay:0.4s;background:#ffeaa7;box-shadow:0 0 6px #fdcb6e,0 0 10px #fff;"></span>
83
+ <span class="home-spore" style="--x:25px;--y:-50px;--duration:4.5s;--delay:1.2s;background:#ffeaa7;box-shadow:0 0 6px #fdcb6e,0 0 10px #fff;"></span>
84
+ </span>
85
+ <span class="home-grass grass-right">๐Ÿƒ</span>
86
+ <span class="home-tree right">๐ŸŒณ</span>
87
+ <span class="home-moon">๐ŸŒ–</span>
88
+ </div>
89
+ <p><strong>The Milky Way is awake.</strong> Myco hears a brown mushroom whispering your first clue.</p>
90
+ <span class="home-whisper">"Tap Play. Let's find what the forest is hiding."</span>
91
+ </div>
92
+ """
93
+
94
+ def play_hook_markdown() -> str:
95
+ return """
96
+ <div class="play-hook">
97
+ <p class="eyebrow">Mission</p>
98
+ <h2>Goal: follow clues until Myco remembers the Impossible Mushroom.</h2>
99
+ <div class="hook-steps">
100
+ <span>1 ยท Move through the forest</span>
101
+ <span>2 ยท Search Clearing โ€” mushroom pops up!</span>
102
+ <span>3 ยท Myco reacts ยท Pick, Study, or Follow Whisper</span>
103
+ </div>
104
+ <p>Every clue advances one mystery.</p>
105
+ </div>
106
+ """
107
+
108
+ def game_intro_markdown() -> str:
109
+ return """
110
+ <div style="text-align:center;margin-bottom:.75rem;">
111
+ <h3>๐ŸŒฒ The Deep Forest</h3>
112
+ <p style="color:#359635;font-size:.9em;">
113
+ You step into the glowing undergrowth. Myco hops off your shoulder, its cap faintly pulsing.<br>
114
+ Click <strong>Search Clearing</strong> โ€” watch Myco run toward whatever pops up.
115
+ <span class="ai-tick-badge">๐Ÿค– Myco AI roaming</span>
116
+ </p>
117
+ </div>
118
+ """
119
+
120
+ # ---------------------------------------------------------------------------
121
+ # Forest scene โ€” accepts optional active_mushrooms list
122
+ # ---------------------------------------------------------------------------
123
+
124
+ def forest_scene(
125
+ current: "MushroomState | None",
126
+ collection: "CollectionState | None",
127
+ position: "tuple[int,int] | None" = None,
128
+ active_mushrooms: "list | None" = None, # โ† NEW: list of mushroom dicts
129
+ ) -> str:
130
+ import time
131
+ count = len(_safe_collection(collection))
132
+ area = current_area(count)
133
+ pos_x, pos_y = _safe_position(position)
134
+ pos_cls = f"pos-{pos_x}-{pos_y}"
135
+
136
+ # Safe defaults โ€” all variables set before any conditional
137
+ mushroom_name = "Hidden mushroom"
138
+ rarity = "common"
139
+ sprite = "โœจ"
140
+ status = "The moss is listening. Click Search Clearing to wake the forest."
141
+ omen = "Myco is waiting to sense the first spore."
142
+ event_label = "๐ŸŒŒ Dreaming Forest"
143
+ encounter = "The next clearing may reveal a memory, creature, or poison omen."
144
+ mystery_label = "The Wrong Memory"
145
+ score_total = "0"
146
+ health = "3"
147
+ reward_text = "Search a clearing to score spores."
148
+ state_cls = "state-waiting"
149
+
150
+ if current is not None:
151
+ mushroom_name = current.get("name", "Mystery cluster")
152
+ rarity = current.get("rarity", "Common").lower()
153
+ game_over = current.get("game_over") == "Yes"
154
+ event_label = f"{current.get('event_emoji','โœจ')} {current.get('event_title','Strange Omen')}"
155
+ encounter = current.get("encounter", "Go pick them up!")
156
+ mystery_label = current.get("mystery_title", "The Wrong Memory")
157
+ score_total = current.get("score_total", "0")
158
+ health = current.get("health", "3")
159
+ reward_text = current.get("reward_text", "Dodge the poison, collect the rest!")
160
+ state_cls = _scene_state_class(current)
161
+
162
+ if game_over:
163
+ status = "๐Ÿ’€ GAME OVER: You stepped on a poisonous mushroom!"
164
+ omen = "Press Search Clearing to start a new run."
165
+ elif current.get("picked") == "Yes":
166
+ status = "โœ… Area clear! Move to the next clearing."
167
+ omen = "Search the next clearing!"
168
+ else:
169
+ status = f"A {rarity} {mushroom_name} breaks through the moss!"
170
+ omen = "๐Ÿ„ Study it before picking!"
171
+
172
+ # Build roaming mushroom sprites from active_mushrooms
173
+ active_sprites = _build_active_sprites(active_mushrooms or [])
174
+ anim_key = str(int(time.time() * 1000))[-6:]
175
+
176
+ # CSS injected once โ€” not inside forest_scene
177
+ _FOREST_CSS = r'''<style>
178
+ /* โ”€โ”€ Base scene โ”€โ”€ */
179
+ .forest-scene {
180
+ position:relative; isolation:isolate; overflow:hidden; min-height:20rem;
181
+ padding:0.75rem; border-radius:28px;
182
+ background:
183
+ radial-gradient(circle at 50% 72%, rgba(255,239,173,.26), transparent 8rem),
184
+ radial-gradient(circle at 18% 24%, rgba(134,225,153,.22), transparent 10rem),
185
+ linear-gradient(180deg,#123626 0%,#245c3c 54%,#523b20 100%);
186
+ border:1px solid rgba(225,255,209,.25);
187
+ box-shadow:0 18px 48px rgba(8,30,20,.26);
188
+ color:#f9ffe9;
189
+ }
190
+ .scene-hud {
191
+ position:relative; z-index:3; display:flex; flex-wrap:wrap; gap:.4rem;
192
+ padding:.5rem .75rem; border-radius:999px;
193
+ background:rgba(13,38,28,.72); backdrop-filter:blur(6px);
194
+ font-size:.8rem; font-weight:800;
195
+ }
196
+ .scene-stage {
197
+ position:relative; height:13rem; margin:.6rem 0;
198
+ background:linear-gradient(transparent 62%,rgba(106,79,33,.55) 63%),
199
+ radial-gradient(ellipse at bottom,rgba(190,255,180,.2),transparent 60%);
200
+ border-radius:22px; overflow:hidden;
201
+ }
202
+ .scene-stage span { position:absolute; line-height:1; }
203
+ .tree-left { left:6%; bottom:18%; font-size:5rem; filter:drop-shadow(0 8px 12px rgba(0,0,0,.28)); }
204
+ .tree-right { right:7%; bottom:20%; font-size:4.75rem; filter:drop-shadow(0 8px 12px rgba(0,0,0,.28)); }
205
+ .grass-one { left:26%; bottom:14%; font-size:2.4rem; }
206
+ .grass-two { right:28%;bottom:16%; font-size:2.2rem; }
207
+ .sparkle-one { left:34%; top:18%; font-size:1.8rem; animation:twinkle 1.8s ease-in-out infinite; }
208
+ .sparkle-two { right:33%;top:24%; font-size:1.6rem; animation:twinkle 2.2s ease-in-out infinite reverse; }
209
+ @keyframes twinkle { 0%,100%{opacity:.3;transform:scale(.85);} 50%{opacity:1;transform:scale(1.18);} }
210
+ .myco-player {
211
+ font-size:4rem; z-index:2;
212
+ transition:left .32s cubic-bezier(.34,1.56,.64,1),bottom .32s cubic-bezier(.34,1.56,.64,1);
213
+ animation:myco-bob 2.4s ease-in-out infinite;
214
+ filter:drop-shadow(0 6px 14px rgba(255,92,92,.28));
215
+ }
216
+ @keyframes myco-bob { 0%,100%{transform:translateY(0);} 50%{transform:translateY(-.45rem);} }
217
+ .pos-0-0 .myco-player{left:14%;bottom:62%;} .pos-1-0 .myco-player{left:41%;bottom:62%;} .pos-2-0 .myco-player{left:67%;bottom:62%;}
218
+ .pos-0-1 .myco-player{left:14%;bottom:36%;} .pos-1-1 .myco-player{left:41%;bottom:36%;} .pos-2-1 .myco-player{left:67%;bottom:36%;}
219
+ .pos-0-2 .myco-player{left:14%;bottom:13%;} .pos-1-2 .myco-player{left:41%;bottom:13%;} .pos-2-2 .myco-player{left:67%;bottom:13%;}
220
+ .mushroom-sprite {
221
+ right:33%; bottom:22%; font-size:3.6rem; z-index:2;
222
+ filter:drop-shadow(0 6px 14px rgba(0,0,0,.3));
223
+ }
224
+ /* Roaming mushroom sprites โ€” placed by grid cell */
225
+ .roam-sprite {
226
+ font-size:2.2rem; z-index:2; transition:opacity .3s;
227
+ animation:roam-bob 2s ease-in-out infinite;
228
+ filter:drop-shadow(0 4px 8px rgba(0,0,0,.3));
229
+ }
230
+ @keyframes roam-bob { 0%,100%{transform:translateY(0);} 50%{transform:translateY(-.3rem);} }
231
+ .roam-0-0{left:10%;bottom:58%;} .roam-1-0{left:37%;bottom:58%;} .roam-2-0{left:63%;bottom:58%;}
232
+ .roam-0-1{left:10%;bottom:32%;} .roam-1-1{left:37%;bottom:32%;} .roam-2-1{left:63%;bottom:32%;}
233
+ .roam-0-2{left:10%;bottom:9%;} .roam-1-2{left:37%;bottom:9%;} .roam-2-2{left:63%;bottom:9%;}
234
+ .roam-poison { animation:roam-bob 2s ease-in-out infinite, poison-pulse 1.2s ease-in-out infinite; }
235
+ @keyframes poison-pulse { 0%,100%{filter:drop-shadow(0 0 10px rgba(255,62,91,.6));} 50%{filter:drop-shadow(0 0 28px rgba(255,62,91,1));} }
236
+ /* States */
237
+ .state-waiting .mushroom-sprite { opacity:0; }
238
+ .state-discovered .mushroom-sprite { animation:shroom-popup 0.7s cubic-bezier(.34,1.56,.64,1) both; }
239
+ .state-picked .mushroom-sprite { animation:shroom-catch 0.55s cubic-bezier(.34,1.56,.64,1) both; }
240
+ .state-danger .mushroom-sprite { animation:shroom-popup 0.7s cubic-bezier(.34,1.56,.64,1) both,poison-pulse 1.2s ease-in-out infinite 0.7s; filter:drop-shadow(0 0 18px rgba(255,62,91,.9)); }
241
+ .state-game-over {
242
+ animation:screen-shake .45s ease both;
243
+ background:
244
+ radial-gradient(circle at 30% 40%, rgba(255,0,0,.6), transparent 40%),
245
+ radial-gradient(circle at 70% 60%, rgba(180,0,0,.5), transparent 50%),
246
+ linear-gradient(180deg,#1a0000 0%,#5a0000 40%,#8b0000 70%,#1a0000 100%) !important;
247
+ border-color: rgba(255,50,50,.8) !important;
248
+ box-shadow: 0 0 60px rgba(255,0,0,.8), inset 0 0 40px rgba(180,0,0,.4) !important;
249
+ }
250
+ .state-game-over .myco-player {
251
+ animation: myco-fall .6s ease both;
252
+ filter: drop-shadow(0 0 20px rgba(255,0,0,1)) !important;
253
+ }
254
+ .state-game-over .scene-hud {
255
+ background: rgba(80,0,0,.9) !important;
256
+ border: 1px solid rgba(255,50,50,.6);
257
+ }
258
+ .state-game-over .score-burst {
259
+ background: rgba(180,0,30,.6) !important;
260
+ border-color: rgba(255,80,80,.8) !important;
261
+ animation: score-pop .3s ease both, poison-flash 0.5s ease-in-out 3;
262
+ }
263
+ @keyframes poison-flash {
264
+ 0%,100% { opacity:1; } 50% { opacity:0.3; }
265
+ }
266
+ @keyframes shroom-popup { 0%{opacity:0;transform:translateY(3rem) scale(.2);} 60%{opacity:1;transform:translateY(-.4rem) scale(1.18);} 100%{opacity:1;transform:translateY(0) scale(1);} }
267
+ @keyframes shroom-catch { 0%{opacity:1;transform:translateY(0) scale(1);} 40%{opacity:1;transform:translateY(-2.5rem) scale(1.3) rotate(15deg);} 100%{opacity:0;transform:translateY(-5rem) scale(.2) rotate(40deg);} }
268
+ @keyframes screen-shake { 0%,100%{transform:translateX(0);} 20%{transform:translateX(-8px);} 40%{transform:translateX(8px);} 60%{transform:translateX(-5px);} 80%{transform:translateX(5px);} }
269
+ .rarity-rare .mushroom-sprite { filter:drop-shadow(0 0 18px rgba(138,220,255,.9)); }
270
+ .rarity-legendary .mushroom-sprite { filter:drop-shadow(0 0 28px rgba(255,215,0,1)); animation:legendary-pulse 1s ease-in-out infinite 0.7s; }
271
+ @keyframes legendary-pulse { 0%,100%{filter:drop-shadow(0 0 18px rgba(255,215,0,.7));transform:scale(1);} 50%{filter:drop-shadow(0 0 36px rgba(255,215,0,1));transform:scale(1.1);} }
272
+ /* Grid map */
273
+ .forest-map { display:grid; grid-template-columns:repeat(3,1fr); gap:.3rem; margin:.4rem auto .6rem; max-width:9rem; padding:.4rem; border:1px solid rgba(255,255,255,.18); border-radius:14px; background:rgba(13,38,28,.58); }
274
+ .map-tile { display:grid; min-height:1.7rem; place-items:center; border-radius:8px; background:rgba(255,255,255,.1); font-weight:900; }
275
+ .map-tile.active { background:rgba(255,224,138,.92); color:#3d2c00!important; }
276
+ .map-tile.has-mush { background:rgba(100,200,100,.25); }
277
+ .map-tile.has-poison { background:rgba(200,60,60,.25); }
278
+ /* Caption / score */
279
+ .scene-caption { display:flex; justify-content:space-between; gap:.6rem; padding:.55rem .8rem; border-radius:14px; background:rgba(13,38,28,.68); backdrop-filter:blur(6px); align-items:center; }
280
+ .scene-caption span { color:#d9f4d4; }
281
+ .score-burst { margin:.65rem auto 0; max-width:520px; padding:.5rem .85rem; border-radius:999px; background:rgba(255,224,112,.18); border:1px solid rgba(255,244,190,.36); color:#fff7d6; font-weight:900; text-align:center; animation:score-pop .56s ease both; }
282
+ @keyframes score-pop { 0%{transform:scale(.92);opacity:0;} 45%{transform:scale(1.06);opacity:1;} 100%{transform:scale(1);opacity:1);} }
283
+ .story-moment { margin:.75rem auto 0; max-width:760px; padding:.8rem 1rem; border:1px solid rgba(255,234,166,.3); border-radius:18px; background:rgba(25,18,45,.72); color:#fff7d6; box-shadow:0 0 24px rgba(165,111,255,.22); }
284
+ .story-moment strong,.story-moment span { display:block; }
285
+ .story-moment span { margin-top:.2rem; color:#f6e7b2; }
286
+ .ai-tick-badge { display:inline-block; padding:.15rem .55rem; border-radius:999px; background:rgba(80,220,120,.22); border:1px solid rgba(80,220,120,.4); color:#90ffb8; font-size:.72rem; font-weight:800; animation:ai-pulse 2s ease-in-out infinite; }
287
+ @keyframes ai-pulse { 0%,100%{opacity:.6;} 50%{opacity:1;} }
288
+ .generating .forest-scene,.pending .forest-scene { opacity:.88!important; }
289
+ .progress-level,.progress-level-inner { display:none!important; }
290
+ </style>'''
291
+
292
+ def forest_scene_styles() -> str:
293
+ return "<style>" + _FOREST_CSS + "</style>"
294
+
295
+ return (
296
+ f'''
297
+ <div class="forest-scene rarity-{escape(rarity)} {pos_cls} {state_cls}" data-key="{anim_key}">
298
+ <div class="scene-hud">
299
+ <span>๐Ÿงญ {escape(area.name)}</span>
300
+ <span>๐ŸŽฎ ({pos_x+1},{pos_y+1})</span>
301
+ <span>๐Ÿ“– {count} found</span>
302
+ <span>โญ {escape(str(score_total))}</span>
303
+ <span>โค๏ธ {escape(str(health))}/3</span>
304
+ <span>{escape(event_label)}</span>
305
+ <span>๐Ÿงฉ {escape(mystery_label)}</span>
306
+ </div>
307
+
308
+ <div class="scene-stage" aria-label="Magical forest scene">
309
+ <span class="tree tree-left">๐ŸŒฒ</span>
310
+ <span class="tree tree-right">๐ŸŒฒ</span>
311
+ <span class="grass grass-one">๐ŸŒฟ</span>
312
+ <span class="grass grass-two">๐Ÿƒ</span>
313
+ <span class="myco-player" title="Myco">๐Ÿ„</span>
314
+ <span class="mushroom-sprite" title="{escape(mushroom_name)}">{escape(sprite)}</span>
315
+ {active_sprites}
316
+ <span class="sparkle sparkle-one">โœจ</span>
317
+ <span class="sparkle sparkle-two">โœฆ</span>
318
+ </div>
319
+
320
+ <div class="forest-map" aria-label="Forest grid">
321
+ {_movement_tiles(pos_x, pos_y, active_mushrooms)}
322
+ </div>
323
+
324
+ <div class="scene-caption">
325
+ <strong>{escape(str(status))}</strong>
326
+ <span>{escape(str(omen))}</span>
327
+ </div>
328
+ <div class="score-burst" aria-live="polite">{escape(str(reward_text))}</div>
329
+ <div class="story-moment">
330
+ <strong>{escape(str(event_label))}</strong>
331
+ <span>{escape(str(encounter))}</span>
332
+ </div>
333
+ </div>'''
334
+ )
335
+
336
+
337
+ # ---------------------------------------------------------------------------
338
+ # Active mushroom sprites builder
339
+ # ---------------------------------------------------------------------------
340
+
341
+ def _build_active_sprites(active_mushrooms: list) -> str:
342
+ """Render each roaming mushroom as a positioned sprite on the scene stage."""
343
+ sprites = []
344
+ for m in active_mushrooms:
345
+ if not isinstance(m, dict):
346
+ continue
347
+ if m.get("picked") == "Yes":
348
+ continue
349
+ mx = int(m.get("mush_x", 1))
350
+ my = int(m.get("mush_y", 1))
351
+ mx = max(0, min(2, mx))
352
+ my = max(0, min(2, my))
353
+ is_poison = m.get("poison") == "Yes"
354
+ icon = "โ˜ ๏ธ" if is_poison else ("๐Ÿ„โ€๐ŸŸซ" if m.get("rarity") == "Legendary" else "๐Ÿ„")
355
+ css_class = f"roam-sprite roam-{mx}-{my}" + (" roam-poison" if is_poison else "")
356
+ name = escape(str(m.get("name", "?")))
357
+ sprites.append(f'<span class="{css_class}" title="{name}">{icon}</span>')
358
+ return "\n ".join(sprites)
359
+
360
+
361
+ # ---------------------------------------------------------------------------
362
+ # Helpers
363
+ # ---------------------------------------------------------------------------
364
+
365
+ def _safe_position(position):
366
+ if position is None:
367
+ return (1, 1)
368
+ try:
369
+ x, y = position
370
+ return (max(0, min(2, int(x))), max(0, min(2, int(y))))
371
+ except Exception:
372
+ return (1, 1)
373
+
374
+
375
+ def _movement_tiles(active_x, active_y, active_mushrooms=None):
376
+ """Grid map tiles โ€” marks player, mushrooms, and poison cells."""
377
+ mush_coords = {}
378
+ for m in (active_mushrooms or []):
379
+ if not isinstance(m, dict):
380
+ continue
381
+ if m.get("picked") == "Yes":
382
+ continue
383
+ mx, my = int(m.get("mush_x", -1)), int(m.get("mush_y", -1))
384
+ if 0 <= mx <= 2 and 0 <= my <= 2:
385
+ mush_coords[(mx, my)] = m
386
+
387
+ tiles = []
388
+ for y in range(3):
389
+ for x in range(3):
390
+ is_player = (x, y) == (int(active_x), int(active_y))
391
+ mush = mush_coords.get((x, y))
392
+ if is_player:
393
+ css = "map-tile active"
394
+ icon = "๐Ÿ„"
395
+ elif mush:
396
+ is_p = mush.get("poison") == "Yes"
397
+ css = "map-tile has-poison" if is_p else "map-tile has-mush"
398
+ icon = "โ˜ ๏ธ" if is_p else "โœจ"
399
+ else:
400
+ css = "map-tile"
401
+ icon = "ยท"
402
+ tiles.append(f'<span class="{css}">{icon}</span>')
403
+ return "".join(tiles)
404
+
405
+
406
+ def _scene_state_class(current):
407
+ if not current:
408
+ return "state-waiting"
409
+ if current.get("game_over") == "Yes":
410
+ return "state-game-over"
411
+ if current.get("picked") == "Yes":
412
+ return "state-picked"
413
+ if current.get("poison") == "Yes":
414
+ return "state-danger"
415
+ return "state-discovered"
416
+
417
+
418
+ def _safe_collection(collection):
419
+ """Return a list of dicts, parsing any string entries that Gradio may have serialized."""
420
+ import json as _json
421
+ result = []
422
+ for entry in list(collection or []):
423
+ if isinstance(entry, str):
424
+ try:
425
+ entry = _json.loads(entry)
426
+ except Exception:
427
+ continue
428
+ if isinstance(entry, dict):
429
+ result.append(entry)
430
+ return result
431
+
432
+
433
+ # ---------------------------------------------------------------------------
434
+ # Game status panel
435
+ # ---------------------------------------------------------------------------
436
+
437
+ def game_status_markdown(
438
+ current: "MushroomState | None",
439
+ collection: "CollectionState | None",
440
+ position: "tuple[int,int] | None" = None,
441
+ ) -> str:
442
+ count = len(_safe_collection(collection))
443
+ pos_x, pos_y = _safe_position(position)
444
+ active_mystery = next_mystery(count)
445
+ mystery_line = _mystery_goal_line(active_mystery, count)
446
+
447
+ if current is None:
448
+ objective = "Goal: solve **one mystery** โ€” why does Myco remember a vanished forest?"
449
+ discovery = "No active discovery yet. Move Myco, then Search Clearing."
450
+ ai_job = "Myco AI is roaming โ€” watch it search, study, and collect automatically."
451
+ event = "**Event:** waiting for the first omen"
452
+ clue_line = mystery_line
453
+ thread_line = "**Mystery thread:** The Wrong Memory โ€” search the first clearing."
454
+ bloom_line = f"**Impossible bloom:** {_mystery_bloom_meter(count)}"
455
+ score_line = "**Score:** 0 spores ยท **Health:** 3/3"
456
+ else:
457
+ name = current.get("name", "Mystery mushroom")
458
+ studied = current.get("studied") == "Yes"
459
+ game_over = current.get("game_over") == "Yes"
460
+ picked = current.get("picked") == "Yes"
461
+ if game_over:
462
+ objective = "**๐Ÿ’€ GAME OVER** โ€” press **Search Clearing** to start a new run."
463
+ elif picked:
464
+ objective = "Current objective: **move to the next clearing and search again**."
465
+ else:
466
+ next_step = "Collect it to preserve the clue" if studied else "Study it, then Collect or Pick"
467
+ objective = f"Current objective: **{next_step}**."
468
+ bloom_line = f"**Impossible bloom:** {_mystery_bloom_meter(count)}"
469
+ score_line = (
470
+ f"**Score:** {current.get('score_total','0')} spores ยท "
471
+ f"**Health:** {current.get('health','3')}/3 ยท "
472
+ f"**Last:** {current.get('reward_text','โ€”')}"
473
+ )
474
+ discovery = f"Active discovery: **{name}** ยท Rarity: **{current.get('rarity','Unknown')}**"
475
+ event = f"**Event:** {current.get('event_emoji','โœจ')} {current.get('event_title','Strange Omen')}"
476
+ clue_line = f"**Clue:** {current.get('clue','Myco is still listening.')}"
477
+ thread_line = (
478
+ f"**Mystery thread:** {current.get('mystery_title','The Wrong Memory')} โ€” "
479
+ f"Next: {current.get('mystery_next','follow the whisper.')}"
480
+ )
481
+ ai_job = "Myco AI is watching โ€” it will study and collect automatically while you explore."
482
+
483
+ return "\n".join((
484
+ "### ๐ŸŽฎ Quest Log",
485
+ f"**MycoDex:** {count} discoveries ยท **Map:** ({pos_x+1},{pos_y+1})",
486
+ discovery, objective, score_line, bloom_line,
487
+ event, clue_line, thread_line, mystery_line, ai_job,
488
+ ))
489
+
490
+
491
+ # ---------------------------------------------------------------------------
492
+ # Mushroom card
493
+ # ---------------------------------------------------------------------------
494
+
495
+ def mushroom_card(
496
+ mushroom: "Mushroom | None",
497
+ clue: "str | None" = None,
498
+ secret: "str | None" = None,
499
+ state: "MushroomState | None" = None,
500
+ ) -> str:
501
+ if mushroom is None:
502
+ return "### ๐ŸŒฒ Forest Clearing\nClick **Search Clearing** โ€” watch Myco run toward the mushroom!"
503
+ s = state or {}
504
+ poison = mushroom.name in POISONOUS_MUSHROOM_NAMES
505
+ warning = "\n> โš ๏ธ **Myco senses danger โ€” do NOT pick this without studying first!**" if poison else ""
506
+ return "\n".join((
507
+ f"### ๐Ÿ„โ€๐ŸŸซ {mushroom.name}",
508
+ f"**{mushroom.rarity} discovery** ยท found near **{mushroom.habitat}**",
509
+ f"> {mushroom.lore}",
510
+ warning, "",
511
+ f"* **Edible:** {mushroom.edible}",
512
+ f"* **Magic:** {mushroom.magic}",
513
+ f"* **Danger:** {mushroom.danger}",
514
+ f"* **Value:** {_mushroom_value_label(mushroom.rarity)}",
515
+ f"* **Poison risk:** {_poison_risk_label(mushroom.name)}",
516
+ f"* **Event:** {s.get('event_emoji','โœจ')} {s.get('event_title','Strange Omen')}",
517
+ f"* **Mystery:** {s.get('mystery_title','The Wrong Memory')}",
518
+ f"* **Clue:** {clue or 'Study with Myco to reveal the clue.'}",
519
+ f"* **Secret:** {secret or 'Collect it to see how the MycoDex reacts.'}",
520
+ f"* **Status:** {'โš ๏ธ POISONOUS' if poison else 'โœ… Appears safe'}",
521
+ ))
522
+
523
+ def _mushroom_value_label(rarity):
524
+ return {"Legendary": "100 spores", "Rare": "35 spores"}.get(rarity, "10 spores")
525
+
526
+ def _poison_risk_label(name):
527
+ return "โš ๏ธ POISONOUS โ€” Game Over if picked!" if name in POISONOUS_MUSHROOM_NAMES else "No obvious poison"
528
+
529
+
530
+ # ---------------------------------------------------------------------------
531
+ # World map / Dex / Progress
532
+ # ---------------------------------------------------------------------------
533
+
534
+ def world_map_markdown(collection: "CollectionState | None") -> str:
535
+ count = len(_safe_collection(collection))
536
+ cards = []
537
+ for area in AREA_UNLOCKS:
538
+ unlocked = count >= area.required_discoveries
539
+ state = "unlocked" if unlocked else "locked"
540
+ badge = "โœ… Unlocked" if unlocked else f"๐Ÿ”’ {area.required_discoveries - count} away"
541
+ cards.append("\n".join((
542
+ f'<div class="map-card {state}">',
543
+ ' <div class="map-card-top">',
544
+ f' <strong>{escape(area.name)}</strong><span>{badge}</span>',
545
+ ' </div>',
546
+ f' <p>{escape(area.description)}</p>',
547
+ '</div>',
548
+ )))
549
+ secrets = tuple(_secret_badge(t.name, count >= t.required_discoveries) for t in revealed_mysteries(count))
550
+ if not secrets:
551
+ secrets = (_secret_badge("First Spore", False),)
552
+ return "\n".join((
553
+ '<div class="world-map-panel">',
554
+ ' <div class="world-map-header"><p class="eyebrow">World Map</p>',
555
+ ' <h2>Forest Atlas</h2>',
556
+ f' <p>{count} discoveries logged.</p></div>',
557
+ f' <div class="achievement-row">{"".join(secrets)}</div>',
558
+ f' <div class="map-grid">{"".join(cards)}</div>',
559
+ '</div>',
560
+ ))
561
+
562
+ def _secret_badge(label, unlocked):
563
+ state = "earned" if unlocked else "pending"
564
+ icon = "๐Ÿ”Ž" if unlocked else "โ—‡"
565
+ return f'<span class="achievement {state}">{icon} {escape(label)}</span>'
566
+
567
+ def dex_markdown(collection: "CollectionState | None") -> str:
568
+ current_collection = _safe_collection(collection)
569
+ if not current_collection:
570
+ return EMPTY_DEX
571
+ rows = ["### ๐Ÿ“– MycoDex", ""]
572
+ for entry in current_collection:
573
+ # Entries can arrive as JSON strings if Gradio serialized the state
574
+ if isinstance(entry, str):
575
+ try:
576
+ import json as _json
577
+ entry = _json.loads(entry)
578
+ except Exception:
579
+ continue
580
+ if not isinstance(entry, dict):
581
+ continue
582
+ poison_flag = " โ˜ ๏ธ" if entry.get("poison") == "Yes" else ""
583
+ rows.append(
584
+ f"* ๐Ÿ„ **{entry.get('name','Unknown')}**{poison_flag} โ€” "
585
+ f"{entry.get('rarity','Unknown')} โ€” "
586
+ f"{entry.get('habitat','Unknown habitat')} โ€” clue: {entry.get('clue','not studied yet')}"
587
+ )
588
+ return "\n".join(rows)
589
+
590
+ def progress_markdown(collection: "CollectionState | None") -> str:
591
+ count = len(_safe_collection(collection))
592
+ active_area = current_area(count)
593
+ upcoming_area = next_area(count)
594
+ unlocked_names = ", ".join(a.name for a in unlocked_areas(count))
595
+ rows = [
596
+ "### โœจ Forest Progress",
597
+ f"**MycoDex discoveries:** {count}",
598
+ f"**Current area:** {active_area.name} โ€” {active_area.description}",
599
+ f"**Unlocked:** {unlocked_names}",
600
+ ]
601
+ upcoming_mystery = next_mystery(count)
602
+ if upcoming_area:
603
+ rows.append(f"**Next area:** {upcoming_area.required_discoveries - count} more to unlock **{upcoming_area.name}**.")
604
+ else:
605
+ rows.append(f"**All areas visible.** You reached **{AREA_UNLOCKS[-1].name}**.")
606
+ if upcoming_mystery:
607
+ rows.append(f"**Next secret:** {upcoming_mystery.required_discoveries - count} more to reveal **{upcoming_mystery.name}**.")
608
+ else:
609
+ rows.append("**All current secrets found.**")
610
+ return "\n\n".join(rows)
611
+
612
+ def _mystery_goal_line(active_mystery, count):
613
+ if active_mystery is None:
614
+ return "**Mystery:** Every known clue is awake. Keep exploring for rare surprises."
615
+ remaining = active_mystery.required_discoveries - count
616
+ return f"**Mystery:** {remaining} clue discoveries until **{active_mystery.name}** โ€” {active_mystery.clue}"
617
+
618
+ def _mystery_bloom_meter(count):
619
+ filled = max(0, min(5, count))
620
+ petals = "".join("๐ŸŒ•" if i < filled else "๐ŸŒ‘" for i in range(5))
621
+ if filled >= 5:
622
+ return f"{petals} Impossible Bloom visible"
623
+ return f"{petals} {5 - filled} clue-whispers remain"
624
+