byte-vortex commited on
Commit
b20eab1
·
verified ·
1 Parent(s): da8a529

Delete ui/9-renderers.py

Browse files
Files changed (1) hide show
  1. ui/9-renderers.py +0 -525
ui/9-renderers.py DELETED
@@ -1,525 +0,0 @@
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
- return f'''
177
- <div class="forest-scene rarity-{escape(rarity)} {pos_cls} {state_cls}" data-key="{anim_key}">
178
- <div class="scene-hud">
179
- <span>🧭 {escape(area.name)}</span>
180
- <span>🎮 ({pos_x+1},{pos_y+1})</span>
181
- <span>📖 {count} found</span>
182
- <span>⭐ {escape(str(score_total))}</span>
183
- <span>❤️ {escape(str(health))}/3</span>
184
- <span>{escape(event_label)}</span>
185
- <span>🧩 {escape(mystery_label)}</span>
186
- </div>
187
-
188
- <div class="scene-stage" aria-label="Magical forest scene">
189
- <span class="tree tree-left">🌲</span>
190
- <span class="tree tree-right">🌲</span>
191
- <span class="grass grass-one">🌿</span>
192
- <span class="grass grass-two">🍃</span>
193
- <span class="myco-player" title="Myco" style="left:{["14%","41%","67%"][pos_x]};bottom:{["62%","36%","13%"][pos_y]};">🍄</span>
194
- <span class="mushroom-sprite" title="{escape(mushroom_name)}">{escape(sprite)}</span>
195
- {active_sprites}
196
- <span class="sparkle sparkle-one">✨</span>
197
- <span class="sparkle sparkle-two">✦</span>
198
- </div>
199
-
200
- <div class="forest-map" aria-label="Forest grid">
201
- {_movement_tiles(pos_x, pos_y, active_mushrooms)}
202
- </div>
203
-
204
- <div class="scene-caption">
205
- <strong>{escape(str(status))}</strong>
206
- <span>{escape(str(omen))}</span>
207
- </div>
208
- <div class="score-burst" aria-live="polite">{escape(str(reward_text))}</div>
209
- <div class="story-moment">
210
- <strong>{escape(str(event_label))}</strong>
211
- <span>{escape(str(encounter))}</span>
212
- </div>
213
- </div>'''
214
-
215
-
216
- # ---------------------------------------------------------------------------
217
- # Active mushroom sprites builder
218
- # ---------------------------------------------------------------------------
219
-
220
- def _build_active_sprites(active_mushrooms: list) -> str:
221
- """Render roaming mushrooms with inline styles so position works inside Gradio components."""
222
- # Grid positions: x=0->10%, x=1->37%, x=2->63% / y=0->58%, y=1->32%, y=2->9%
223
- LEFT = ["10%", "37%", "63%"]
224
- BOTTOM= ["58%", "32%", "9%"]
225
- sprites = []
226
- for m in active_mushrooms:
227
- if not isinstance(m, dict):
228
- continue
229
- if m.get("picked") == "Yes":
230
- continue
231
- mx = max(0, min(2, int(m.get("mush_x", 1))))
232
- my = max(0, min(2, int(m.get("mush_y", 1))))
233
- is_poison = m.get("poison") == "Yes"
234
- rarity = m.get("rarity", "Common")
235
- if is_poison:
236
- icon = "☠️"
237
- color = "rgba(255,62,91,1)"
238
- extra = "animation:roam-bob 2s ease-in-out infinite,poison-pulse 1.2s ease-in-out infinite;"
239
- elif rarity == "Legendary":
240
- icon = "🍄‍🟫"
241
- color = "rgba(255,215,0,1)"
242
- extra = "animation:roam-bob 2s ease-in-out infinite,legendary-pulse 1s ease-in-out infinite;"
243
- elif rarity == "Rare":
244
- icon = "🍄"
245
- color = "rgba(138,220,255,1)"
246
- extra = "animation:roam-bob 2s ease-in-out infinite;"
247
- else:
248
- icon = "🍄"
249
- color = "rgba(255,255,255,0.3)"
250
- extra = "animation:roam-bob 2s ease-in-out infinite;"
251
- name = escape(str(m.get("name", "?")))
252
- style = (
253
- f"position:absolute;font-size:2.4rem;z-index:2;line-height:1;"
254
- f"left:{LEFT[mx]};bottom:{BOTTOM[my]};"
255
- f"filter:drop-shadow(0 0 8px {color});"
256
- f"transition:left .3s,bottom .3s;{extra}"
257
- )
258
- sprites.append(f'<span style="{style}" title="{name}">{icon}</span>')
259
- return "\n ".join(sprites)
260
-
261
-
262
- # ---------------------------------------------------------------------------
263
- # Helpers
264
- # ---------------------------------------------------------------------------
265
-
266
- def _safe_position(position):
267
- if position is None:
268
- return (1, 1)
269
- try:
270
- x, y = position
271
- return (max(0, min(2, int(x))), max(0, min(2, int(y))))
272
- except Exception:
273
- return (1, 1)
274
-
275
-
276
- def _movement_tiles(active_x, active_y, active_mushrooms=None):
277
- """Grid map tiles — marks player, mushrooms, and poison cells."""
278
- mush_coords = {}
279
- for m in (active_mushrooms or []):
280
- if not isinstance(m, dict):
281
- continue
282
- if m.get("picked") == "Yes":
283
- continue
284
- mx, my = int(m.get("mush_x", -1)), int(m.get("mush_y", -1))
285
- if 0 <= mx <= 2 and 0 <= my <= 2:
286
- mush_coords[(mx, my)] = m
287
-
288
- tiles = []
289
- for y in range(3):
290
- for x in range(3):
291
- is_player = (x, y) == (int(active_x), int(active_y))
292
- mush = mush_coords.get((x, y))
293
- if is_player:
294
- css = "map-tile active"
295
- icon = "🍄"
296
- elif mush:
297
- is_p = mush.get("poison") == "Yes"
298
- css = "map-tile has-poison" if is_p else "map-tile has-mush"
299
- icon = "☠️" if is_p else "✨"
300
- else:
301
- css = "map-tile"
302
- icon = "·"
303
- tiles.append(f'<span class="{css}">{icon}</span>')
304
- return "".join(tiles)
305
-
306
-
307
- def _scene_state_class(current):
308
- if not current:
309
- return "state-waiting"
310
- if current.get("game_over") == "Yes":
311
- return "state-game-over"
312
- if current.get("picked") == "Yes":
313
- return "state-picked"
314
- if current.get("poison") == "Yes":
315
- return "state-danger"
316
- return "state-discovered"
317
-
318
-
319
- def _safe_collection(collection):
320
- """Return a list of dicts, parsing any string entries that Gradio may have serialized."""
321
- import json as _json
322
- result = []
323
- for entry in list(collection or []):
324
- if isinstance(entry, str):
325
- try:
326
- entry = _json.loads(entry)
327
- except Exception:
328
- continue
329
- if isinstance(entry, dict):
330
- result.append(entry)
331
- return result
332
-
333
-
334
- # ---------------------------------------------------------------------------
335
- # Game status panel
336
- # ---------------------------------------------------------------------------
337
-
338
- def game_status_markdown(
339
- current: "MushroomState | None",
340
- collection: "CollectionState | None",
341
- position: "tuple[int,int] | None" = None,
342
- ) -> str:
343
- count = len(_safe_collection(collection))
344
- pos_x, pos_y = _safe_position(position)
345
- active_mystery = next_mystery(count)
346
- mystery_line = _mystery_goal_line(active_mystery, count)
347
-
348
- if current is None:
349
- objective = "Goal: solve **one mystery** — why does Myco remember a vanished forest?"
350
- discovery = "No active discovery yet. Move Myco, then Search Clearing."
351
- ai_job = "Myco AI is roaming — watch it search, study, and collect automatically."
352
- event = "**Event:** waiting for the first omen"
353
- clue_line = mystery_line
354
- thread_line = "**Mystery thread:** The Wrong Memory — search the first clearing."
355
- bloom_line = f"**Impossible bloom:** {_mystery_bloom_meter(count)}"
356
- score_line = "**Score:** 0 spores · **Health:** 3/3"
357
- else:
358
- name = current.get("name", "Mystery mushroom")
359
- studied = current.get("studied") == "Yes"
360
- game_over = current.get("game_over") == "Yes"
361
- picked = current.get("picked") == "Yes"
362
- if game_over:
363
- objective = "**💀 GAME OVER** — press **Search Clearing** to start a new run."
364
- elif picked:
365
- objective = "Current objective: **move to the next clearing and search again**."
366
- else:
367
- next_step = "Collect it to preserve the clue" if studied else "Study it, then Collect or Pick"
368
- objective = f"Current objective: **{next_step}**."
369
- bloom_line = f"**Impossible bloom:** {_mystery_bloom_meter(count)}"
370
- score_line = (
371
- f"**Score:** {current.get('score_total','0')} spores · "
372
- f"**Health:** {current.get('health','3')}/3 · "
373
- f"**Last:** {current.get('reward_text','—')}"
374
- )
375
- discovery = f"Active discovery: **{name}** · Rarity: **{current.get('rarity','Unknown')}**"
376
- event = f"**Event:** {current.get('event_emoji','✨')} {current.get('event_title','Strange Omen')}"
377
- clue_line = f"**Clue:** {current.get('clue','Myco is still listening.')}"
378
- thread_line = (
379
- f"**Mystery thread:** {current.get('mystery_title','The Wrong Memory')} — "
380
- f"Next: {current.get('mystery_next','follow the whisper.')}"
381
- )
382
- ai_job = "Myco AI is watching — it will study and collect automatically while you explore."
383
-
384
- return "\n".join((
385
- "### 🎮 Quest Log",
386
- f"**MycoDex:** {count} discoveries · **Map:** ({pos_x+1},{pos_y+1})",
387
- discovery, objective, score_line, bloom_line,
388
- event, clue_line, thread_line, mystery_line, ai_job,
389
- ))
390
-
391
-
392
- # ---------------------------------------------------------------------------
393
- # Mushroom card
394
- # ---------------------------------------------------------------------------
395
-
396
- def mushroom_card(
397
- mushroom: "Mushroom | None",
398
- clue: "str | None" = None,
399
- secret: "str | None" = None,
400
- state: "MushroomState | None" = None,
401
- ) -> str:
402
- if mushroom is None:
403
- return "### 🌲 Forest Clearing\nClick **Search Clearing** — watch Myco run toward the mushroom!"
404
- s = state or {}
405
- poison = mushroom.name in POISONOUS_MUSHROOM_NAMES
406
- warning = "\n> ⚠️ **Myco senses danger — do NOT pick this without studying first!**" if poison else ""
407
- return "\n".join((
408
- f"### 🍄‍🟫 {mushroom.name}",
409
- f"**{mushroom.rarity} discovery** · found near **{mushroom.habitat}**",
410
- f"> {mushroom.lore}",
411
- warning, "",
412
- f"* **Edible:** {mushroom.edible}",
413
- f"* **Magic:** {mushroom.magic}",
414
- f"* **Danger:** {mushroom.danger}",
415
- f"* **Value:** {_mushroom_value_label(mushroom.rarity)}",
416
- f"* **Poison risk:** {_poison_risk_label(mushroom.name)}",
417
- f"* **Event:** {s.get('event_emoji','✨')} {s.get('event_title','Strange Omen')}",
418
- f"* **Mystery:** {s.get('mystery_title','The Wrong Memory')}",
419
- f"* **Clue:** {clue or 'Study with Myco to reveal the clue.'}",
420
- f"* **Secret:** {secret or 'Collect it to see how the MycoDex reacts.'}",
421
- f"* **Status:** {'⚠️ POISONOUS' if poison else '✅ Appears safe'}",
422
- ))
423
-
424
- def _mushroom_value_label(rarity):
425
- return {"Legendary": "100 spores", "Rare": "35 spores"}.get(rarity, "10 spores")
426
-
427
- def _poison_risk_label(name):
428
- return "⚠️ POISONOUS — Game Over if picked!" if name in POISONOUS_MUSHROOM_NAMES else "No obvious poison"
429
-
430
-
431
- # ---------------------------------------------------------------------------
432
- # World map / Dex / Progress
433
- # ---------------------------------------------------------------------------
434
-
435
- def world_map_markdown(collection: "CollectionState | None") -> str:
436
- count = len(_safe_collection(collection))
437
- cards = []
438
- for area in AREA_UNLOCKS:
439
- unlocked = count >= area.required_discoveries
440
- state = "unlocked" if unlocked else "locked"
441
- badge = "✅ Unlocked" if unlocked else f"🔒 {area.required_discoveries - count} away"
442
- cards.append("\n".join((
443
- f'<div class="map-card {state}">',
444
- ' <div class="map-card-top">',
445
- f' <strong>{escape(area.name)}</strong><span>{badge}</span>',
446
- ' </div>',
447
- f' <p>{escape(area.description)}</p>',
448
- '</div>',
449
- )))
450
- secrets = tuple(_secret_badge(t.name, count >= t.required_discoveries) for t in revealed_mysteries(count))
451
- if not secrets:
452
- secrets = (_secret_badge("First Spore", False),)
453
- return "\n".join((
454
- '<div class="world-map-panel">',
455
- ' <div class="world-map-header"><p class="eyebrow">World Map</p>',
456
- ' <h2>Forest Atlas</h2>',
457
- f' <p>{count} discoveries logged.</p></div>',
458
- f' <div class="achievement-row">{"".join(secrets)}</div>',
459
- f' <div class="map-grid">{"".join(cards)}</div>',
460
- '</div>',
461
- ))
462
-
463
- def _secret_badge(label, unlocked):
464
- state = "earned" if unlocked else "pending"
465
- icon = "🔎" if unlocked else "◇"
466
- return f'<span class="achievement {state}">{icon} {escape(label)}</span>'
467
-
468
- def dex_markdown(collection: "CollectionState | None") -> str:
469
- current_collection = _safe_collection(collection)
470
- if not current_collection:
471
- return EMPTY_DEX
472
- rows = ["### 📖 MycoDex", ""]
473
- for entry in current_collection:
474
- # Entries can arrive as JSON strings if Gradio serialized the state
475
- if isinstance(entry, str):
476
- try:
477
- import json as _json
478
- entry = _json.loads(entry)
479
- except Exception:
480
- continue
481
- if not isinstance(entry, dict):
482
- continue
483
- poison_flag = " ☠️" if entry.get("poison") == "Yes" else ""
484
- rows.append(
485
- f"* 🍄 **{entry.get('name','Unknown')}**{poison_flag} — "
486
- f"{entry.get('rarity','Unknown')} — "
487
- f"{entry.get('habitat','Unknown habitat')} — clue: {entry.get('clue','not studied yet')}"
488
- )
489
- return "\n".join(rows)
490
-
491
- def progress_markdown(collection: "CollectionState | None") -> str:
492
- count = len(_safe_collection(collection))
493
- active_area = current_area(count)
494
- upcoming_area = next_area(count)
495
- unlocked_names = ", ".join(a.name for a in unlocked_areas(count))
496
- rows = [
497
- "### ✨ Forest Progress",
498
- f"**MycoDex discoveries:** {count}",
499
- f"**Current area:** {active_area.name} — {active_area.description}",
500
- f"**Unlocked:** {unlocked_names}",
501
- ]
502
- upcoming_mystery = next_mystery(count)
503
- if upcoming_area:
504
- rows.append(f"**Next area:** {upcoming_area.required_discoveries - count} more to unlock **{upcoming_area.name}**.")
505
- else:
506
- rows.append(f"**All areas visible.** You reached **{AREA_UNLOCKS[-1].name}**.")
507
- if upcoming_mystery:
508
- rows.append(f"**Next secret:** {upcoming_mystery.required_discoveries - count} more to reveal **{upcoming_mystery.name}**.")
509
- else:
510
- rows.append("**All current secrets found.**")
511
- return "\n\n".join(rows)
512
-
513
- def _mystery_goal_line(active_mystery, count):
514
- if active_mystery is None:
515
- return "**Mystery:** Every known clue is awake. Keep exploring for rare surprises."
516
- remaining = active_mystery.required_discoveries - count
517
- return f"**Mystery:** {remaining} clue discoveries until **{active_mystery.name}** — {active_mystery.clue}"
518
-
519
- def _mystery_bloom_meter(count):
520
- filled = max(0, min(5, count))
521
- petals = "".join("🌕" if i < filled else "🌑" for i in range(5))
522
- if filled >= 5:
523
- return f"{petals} Impossible Bloom visible"
524
- return f"{petals} {5 - filled} clue-whispers remain"
525
-