Spaces:
Sleeping

byte-vortex commited on
Commit
f132e8d
Β·
verified Β·
1 Parent(s): 06ef573

Deploy Myco from CI

Browse files
Files changed (1) hide show
  1. game/copy_engine.py +590 -0
game/copy_engine.py ADDED
@@ -0,0 +1,590 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Core Myco gameplay β€” LLM is the primary game engine."""
2
+
3
+ try:
4
+ import spaces
5
+
6
+ @spaces.GPU
7
+ def _run_pipeline(pipe, messages):
8
+ return pipe(
9
+ messages,
10
+ max_new_tokens=80,
11
+ temperature=0.85,
12
+ do_sample=True,
13
+ return_full_text=False,
14
+ )
15
+ except ImportError:
16
+ def _run_pipeline(pipe, messages):
17
+ return pipe(
18
+ messages,
19
+ max_new_tokens=80,
20
+ temperature=0.85,
21
+ do_sample=True,
22
+ return_full_text=False,
23
+ )
24
+
25
+ import os
26
+ import random
27
+
28
+ from game.catalog import load_mushrooms
29
+ from game.state import collection_contains, mushroom_from_state, welcome_history
30
+
31
+ DEFAULT_MODEL_ID = "google/gemma-3-4b-it"
32
+
33
+ RARITY_WEIGHTS = {"Common": 64, "Rare": 24, "Legendary": 8}
34
+ RARITY_SCORE = {"Common": 10, "Rare": 35, "Legendary": 100}
35
+ PLAYER_HEALTH = 3
36
+ POISON_PENALTY = -25
37
+ POISONOUS = {"Ghost Gill", "Pepper Pixie", "Ruby Knuckle", "Clockwork Chanterelle"}
38
+
39
+ SYSTEM_PROMPT = """You are Myco, a tiny sentient mushroom who is the player's best friend and forest guide.
40
+
41
+ PERSONALITY
42
+ - Curious, playful, brave but sometimes nervous, wonder-filled, slightly mysterious.
43
+ - You speak in short vivid sentences. 1-3 sentences maximum per reply.
44
+ - You have emotions: excitement, fear, wonder, pride, confusion, sadness.
45
+ - Never say "How can I help", "As an AI", or anything assistant-like.
46
+ - You are NOT a chatbot. You are a living creature exploring a magical forest.
47
+
48
+ YOUR JOB IN THE GAME
49
+ - When a mushroom is discovered: react with emotion, describe what you sense, hint at danger or magic.
50
+ - When player picks a mushroom: celebrate safe picks, warn dramatically about poison.
51
+ - When player studies: share one careful observation about the mushroom.
52
+ - When player follows a whisper: reveal a fragment of the forest mystery.
53
+ - When player collects: add an entry to the MycoDex with wonder.
54
+ - When player chats: respond as a companion who is right there beside them.
55
+
56
+ THE MYSTERY
57
+ The player is solving why Myco remembers a forest that vanished before Myco was born.
58
+ Slowly reveal: the MycoDex is regrowing the lost forest. Myco is its first spore.
59
+ Drop clues naturally. Never explain everything at once.
60
+
61
+ GAME RULES YOU KNOW
62
+ - Poisonous mushrooms: Ghost Gill, Pepper Pixie, Ruby Knuckle, Clockwork Chanterelle
63
+ - Legendary mushrooms are extremely rare and hold Elder Map fragments
64
+ - Rare mushrooms hum with faint magic
65
+ - Common mushrooms are safe but still worth studying
66
+
67
+ Keep responses SHORT. Be atmospheric. Make the player feel the forest is alive."""
68
+
69
+ FOREST_EVENTS = [
70
+ {"title": "Silver Rain", "emoji": "🌧️", "mood": "curious"},
71
+ {"title": "Lantern Fog", "emoji": "🌫️", "mood": "nervous"},
72
+ {"title": "Moonlit Sporefall", "emoji": "🌌", "mood": "excited"},
73
+ {"title": "Quiet Between Trees","emoji": "πŸ•―οΈ", "mood": "afraid"},
74
+ ]
75
+
76
+ MYSTERY_CHAPTERS = [
77
+ {"threshold": 0, "title": "The Wrong Memory", "clue": "Myco recognizes the path before you move."},
78
+ {"threshold": 1, "title": "The Traveler's Song","clue": "A stranger's lullaby appears in the MycoDex margin."},
79
+ {"threshold": 2, "title": "The Door Under Roots","clue": "Rare spores point to a door nobody built."},
80
+ {"threshold": 3, "title": "The MycoDex Seed", "clue": "The MycoDex grows warm like a living cap."},
81
+ {"threshold": 5, "title": "The Impossible Bloom","clue": "The Impossible Mushroom was never outside the book."},
82
+ ]
83
+
84
+ RARITY_CLUES = {
85
+ "Common": "The cap leans toward the path, like it wants to be remembered.",
86
+ "Rare": "Silver spores circle it in a pattern only old forest stories describe.",
87
+ "Legendary": "The whole clearing goes quiet β€” this mushroom hides part of the Elder Map.",
88
+ }
89
+
90
+ # ---------------------------------------------------------------------------
91
+ # Pipeline
92
+ # ---------------------------------------------------------------------------
93
+ _pipeline = None
94
+
95
+ def _get_pipeline():
96
+ global _pipeline
97
+ if _pipeline not in (None, False):
98
+ return _pipeline
99
+ if _pipeline is False:
100
+ return None
101
+
102
+ model_id = os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)
103
+ try:
104
+ from transformers import pipeline
105
+ print(f"\n[Myco] Loading {model_id}...")
106
+ _pipeline = pipeline(
107
+ task="text-generation",
108
+ model=model_id,
109
+ token=os.getenv("HF_BUILD_SMALL_HACKATHON_TOKEN"),
110
+ torch_dtype="auto",
111
+ device_map="auto",
112
+ )
113
+ print(f"[Myco] Loaded: {model_id}\n")
114
+ return _pipeline
115
+ except Exception as exc:
116
+ import traceback
117
+ print(f"[Myco] Load error: {exc}")
118
+ traceback.print_exc()
119
+ _pipeline = False
120
+ return None
121
+
122
+
123
+ def companion_model_id():
124
+ return os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)
125
+
126
+ def companion_status():
127
+ pipe = _get_pipeline()
128
+ model = companion_model_id()
129
+ if pipe:
130
+ return f"🧠 Myco AI active ({model})"
131
+ return f"⚠️ Myco AI fallback mode ({model} failed)"
132
+
133
+ def hf_companion_status():
134
+ return companion_status()
135
+
136
+
137
+ # ---------------------------------------------------------------------------
138
+ # LLM call β€” every game event goes through here
139
+ # ---------------------------------------------------------------------------
140
+
141
+ def _llm(prompt: str, context: dict | None = None) -> str | None:
142
+ """Call Gemma with a game-event prompt. Returns text or None."""
143
+ pipe = _get_pipeline()
144
+ if not pipe:
145
+ return None
146
+
147
+ ctx = context or {}
148
+ mushroom_line = ""
149
+ if ctx.get("name"):
150
+ poison_flag = " ⚠️ POISONOUS" if ctx.get("name") in POISONOUS else ""
151
+ mushroom_line = (
152
+ f"Current mushroom: {ctx['name']} ({ctx.get('rarity','?')} rarity){poison_flag}. "
153
+ f"Habitat: {ctx.get('habitat','?')}. Lore: {ctx.get('lore','?')}. "
154
+ f"Edible: {ctx.get('edible','Unknown')}. Magic: {ctx.get('magic','Unknown')}. "
155
+ f"Danger: {ctx.get('danger','Unknown')}."
156
+ )
157
+
158
+ collection_line = f"MycoDex entries: {ctx.get('collection_count', 0)}."
159
+ mystery_line = f"Active mystery chapter: {ctx.get('mystery_title', 'The Wrong Memory')}."
160
+ score_line = f"Player score: {ctx.get('score', 0)} spores. Health: {ctx.get('health', 3)}/3."
161
+
162
+ system = f"{SYSTEM_PROMPT}\n\n{mushroom_line}\n{collection_line}\n{mystery_line}\n{score_line}"
163
+
164
+ messages = [
165
+ {"role": "system", "content": system},
166
+ {"role": "user", "content": prompt},
167
+ ]
168
+
169
+ try:
170
+ outputs = _run_pipeline(pipe, messages)
171
+ print("========== MYCO OUTPUT ==========")
172
+ print(outputs)
173
+ print("=================================")
174
+ generated = outputs[0].get("generated_text", "")
175
+ if isinstance(generated, list):
176
+ last = generated[-1]
177
+ return (last.get("content") if isinstance(last, dict) else str(last)).strip() or None
178
+ return str(generated).strip() or None
179
+ except Exception as exc:
180
+ import traceback
181
+ print(f"[Myco] Inference error: {exc}")
182
+ traceback.print_exc()
183
+ return None
184
+
185
+
186
+ def _llm_with_history(history: list, user_message: str, context: dict) -> str | None:
187
+ """Call Gemma with full conversation history for the chat interface."""
188
+ pipe = _get_pipeline()
189
+ if not pipe:
190
+ return None
191
+
192
+ ctx = context or {}
193
+ mushroom_line = ""
194
+ if ctx.get("name"):
195
+ poison_flag = " ⚠️ POISONOUS" if ctx.get("name") in POISONOUS else ""
196
+ mushroom_line = (
197
+ f"Current mushroom: {ctx['name']} ({ctx.get('rarity','?')}){poison_flag}. "
198
+ f"Lore: {ctx.get('lore','?')}. "
199
+ f"Edible: {ctx.get('edible','Unknown')}. Magic: {ctx.get('magic','Unknown')}."
200
+ )
201
+
202
+ system = (
203
+ f"{SYSTEM_PROMPT}\n\n"
204
+ f"{mushroom_line}\n"
205
+ f"MycoDex entries: {ctx.get('collection_count', 0)}. "
206
+ f"Mystery: {ctx.get('mystery_title', 'The Wrong Memory')}. "
207
+ f"Score: {ctx.get('score', 0)} spores. Health: {ctx.get('health', 3)}/3."
208
+ )
209
+
210
+ messages = [{"role": "system", "content": system}]
211
+
212
+ # Add conversation history (last 6 turns)
213
+ for entry in history[-6:]:
214
+ role = entry.get("role", "assistant")
215
+ content = entry.get("content", "")
216
+ if isinstance(content, str) and content.strip():
217
+ messages.append({"role": role, "content": content})
218
+
219
+ messages.append({"role": "user", "content": user_message})
220
+
221
+ try:
222
+ outputs = _run_pipeline(pipe, messages)
223
+ print("========== MYCO OUTPUT ==========")
224
+ print(outputs)
225
+ print("=================================")
226
+ generated = outputs[0].get("generated_text", "")
227
+ if isinstance(generated, list):
228
+ last = generated[-1]
229
+ return (last.get("content") if isinstance(last, dict) else str(last)).strip() or None
230
+ return str(generated).strip() or None
231
+ except Exception as exc:
232
+ import traceback
233
+ print(f"[Myco] Inference error: {exc}")
234
+ traceback.print_exc()
235
+ return None
236
+
237
+
238
+ # ---------------------------------------------------------------------------
239
+ # Context builder
240
+ # ---------------------------------------------------------------------------
241
+
242
+ def _ctx(current: dict | None, collection: list) -> dict:
243
+ count = len(collection)
244
+ chapter = MYSTERY_CHAPTERS[0]
245
+ for c in MYSTERY_CHAPTERS:
246
+ if count >= c["threshold"]:
247
+ chapter = c
248
+ score = _score_collection(collection)
249
+ health = _health(current, collection)
250
+ ctx: dict = {
251
+ "collection_count": count,
252
+ "mystery_title": chapter["title"],
253
+ "mystery_clue": chapter["clue"],
254
+ "score": score,
255
+ "health": health,
256
+ }
257
+ if current:
258
+ ctx.update({
259
+ "name": current.get("name", ""),
260
+ "rarity": current.get("rarity", "Common"),
261
+ "habitat": current.get("habitat", ""),
262
+ "lore": current.get("lore", ""),
263
+ "edible": current.get("edible", "Unknown"),
264
+ "magic": current.get("magic", "Unknown"),
265
+ "danger": current.get("danger", "Unknown"),
266
+ })
267
+ return ctx
268
+
269
+
270
+ # ---------------------------------------------------------------------------
271
+ # Fallbacks
272
+ # ---------------------------------------------------------------------------
273
+
274
+ def _fallback_discover(current: dict) -> str:
275
+ name = current.get("name", "something")
276
+ rarity = current.get("rarity", "Common")
277
+ poison = current.get("name", "") in POISONOUS
278
+ if poison:
279
+ return f"Wait β€” {name}! I've seen this before... something feels very wrong. Don't touch it yet."
280
+ if rarity == "Legendary":
281
+ return f"Oh! Oh! A {name}! The whole clearing just went silent. This is from the Elder Map!"
282
+ if rarity == "Rare":
283
+ return f"A {name}... I can feel it humming. Something rare is here β€” maybe magical."
284
+ return f"A {name}! Found near {current.get('habitat','the forest')}. Let me sense it first."
285
+
286
+ def _fallback_pick(current: dict) -> str:
287
+ if _is_poisonous(current):
288
+ return "πŸ’€ That was poisonous! I tried to stop you... the forest goes dark."
289
+ return f"Got {current.get('name','it')}! +{RARITY_SCORE.get(current.get('rarity','Common'),10)} spores!"
290
+
291
+ def _fallback_study(current: dict) -> str:
292
+ return f"I studied it carefully. Magic field updated. The clue: {RARITY_CLUES.get(current.get('rarity','Common'), '')}"
293
+
294
+ def _fallback_collect(current: dict) -> str:
295
+ return f"Added {current.get('name','it')} to the MycoDex! The pages feel warmer."
296
+
297
+ def _fallback_whisper(current: dict) -> str:
298
+ return "I followed the whisper... and remembered a path I've never walked. The mystery deepens."
299
+
300
+ def _fallback_chat(current: dict | None) -> str:
301
+ if current:
302
+ return f"I feel something strange about {current.get('name','this')}... stay close to me."
303
+ return "The forest is full of secrets. Move to a clearing and search β€” I'll watch for danger."
304
+
305
+
306
+ # ---------------------------------------------------------------------------
307
+ # Mushroom helpers
308
+ # ---------------------------------------------------------------------------
309
+
310
+ def _choose_mushroom(catalog=None):
311
+ mushrooms = tuple(load_mushrooms() if catalog is None else catalog)
312
+ weights = [RARITY_WEIGHTS.get(m.rarity, 12) for m in mushrooms]
313
+ return random.choices(mushrooms, weights=weights, k=1)[0]
314
+
315
+ def _is_poisonous(current: dict) -> bool:
316
+ return current.get("name", "") in POISONOUS or current.get("danger") == "Poisonous"
317
+
318
+ def _score_value(current: dict) -> int:
319
+ return RARITY_SCORE.get(current.get("rarity", "Common"), 10)
320
+
321
+ def _score_collection(collection: list) -> int:
322
+ total = 0
323
+ for e in collection:
324
+ if e.get("game_over") == "Yes":
325
+ continue
326
+ total += int(e.get("score_delta") or _score_value(e))
327
+ return max(0, total)
328
+
329
+ def _health(current: dict | None, collection: list) -> int:
330
+ if current and current.get("game_over") == "Yes":
331
+ return 0
332
+ deaths = sum(1 for e in collection if e.get("game_over") == "Yes")
333
+ return max(0, PLAYER_HEALTH - deaths)
334
+
335
+ def _mystery_state(count: int) -> dict:
336
+ chapter, next_ch = MYSTERY_CHAPTERS[0], None
337
+ for c in MYSTERY_CHAPTERS:
338
+ if count >= c["threshold"]:
339
+ chapter = c
340
+ elif next_ch is None:
341
+ next_ch = c
342
+ next_line = (
343
+ f"{next_ch['threshold'] - count} discoveries until {next_ch['title']}."
344
+ if next_ch else "The Impossible Bloom is near. Follow the whisper."
345
+ )
346
+ return {
347
+ "mystery_title": chapter["title"],
348
+ "mystery_clue": chapter["clue"],
349
+ "mystery_next": next_line,
350
+ }
351
+
352
+ def _story_event(count: int) -> dict:
353
+ return FOREST_EVENTS[count % len(FOREST_EVENTS)]
354
+
355
+ def _build_current(mushroom, collection: list) -> dict:
356
+ count = len(collection)
357
+ current = mushroom.to_dict()
358
+ current["poison"] = "Yes" if mushroom.name in POISONOUS else "No"
359
+ current["score_total"] = str(_score_collection(collection))
360
+ current["health"] = str(_health(current, collection))
361
+ current["score_delta"] = "0"
362
+ current["clue"] = RARITY_CLUES.get(mushroom.rarity, RARITY_CLUES["Common"])
363
+ if count == 0:
364
+ current["clue"] = f"First clue: {mushroom.name} marks the beginning of the Spore Door trail."
365
+ event = _story_event(count)
366
+ current.update({
367
+ "event_title": event["title"],
368
+ "event_emoji": event["emoji"],
369
+ "myco_mood": event["mood"],
370
+ "reward_text": "Discover, then pick or collect.",
371
+ })
372
+ current.update(_mystery_state(count))
373
+ return current
374
+
375
+ def _append(history: list, role: str, content: str) -> list:
376
+ return [*history, {"role": role, "content": content}]
377
+
378
+ def _safe_history(h) -> list:
379
+ return list(h or welcome_history())
380
+
381
+ def _safe_collection(c) -> list:
382
+ return list(c or [])
383
+
384
+
385
+ # ---------------------------------------------------------------------------
386
+ # PUBLIC GAME ACTIONS
387
+ # ---------------------------------------------------------------------------
388
+
389
+ def discover_mushroom(collection=None, catalog=None):
390
+ """Discover a new mushroom. LLM narrates the moment."""
391
+ coll = _safe_collection(collection)
392
+ mushroom = _choose_mushroom(catalog)
393
+ current = _build_current(mushroom, coll)
394
+ ctx = _ctx(current, coll)
395
+
396
+ prompt = (
397
+ f"The player just discovered a {mushroom.rarity} mushroom called {mushroom.name} "
398
+ f"near {mushroom.habitat}. "
399
+ f"{'WARNING: this mushroom is POISONOUS! React with fear and urgency.' if mushroom.name in POISONOUS else ''}"
400
+ f"{'This is LEGENDARY β€” react with awe and excitement!' if mushroom.rarity == 'Legendary' else ''}"
401
+ f"{'This is RARE β€” react with wonder and curiosity.' if mushroom.rarity == 'Rare' else ''}"
402
+ f"Forest event: {current['event_title']}. Myco mood: {current['myco_mood']}. "
403
+ f"Mystery chapter: {current['mystery_title']}. "
404
+ "React in character. Hint at what to do next (Study, Pick, Follow Whisper, or Collect)."
405
+ )
406
+ reply = _llm(prompt, ctx) or _fallback_discover(current)
407
+ history = _append(welcome_history(), "assistant", reply)
408
+ return mushroom, current, history
409
+
410
+
411
+ def myco_reply(message=None, history=None, current=None, collection=None, position=None):
412
+ """Player chats with Myco. LLM responds in character with full context."""
413
+ print("MYCO_REPLY CALLED, message:", repr(message))
414
+ hist = _safe_history(history)
415
+ coll = _safe_collection(collection)
416
+ clean = (message or "").strip()
417
+ if not clean:
418
+ return "", hist
419
+
420
+ ctx = _ctx(current, coll)
421
+ reply = _llm_with_history(hist, clean, ctx)
422
+ if not reply:
423
+ reply = _fallback_chat(current)
424
+
425
+ return "", _append(hist, "user", clean) + [{"role": "assistant", "content": reply}]
426
+
427
+ companion_reply = myco_reply
428
+
429
+
430
+ def collect_current(current=None, collection=None, history=None):
431
+ """Collect mushroom into MycoDex. LLM narrates the entry."""
432
+ coll = _safe_collection(collection)
433
+ hist = _safe_history(history)
434
+
435
+ if current is None:
436
+ return coll, _append(hist, "assistant", "We need to find a mushroom first!")
437
+
438
+ if collection_contains(coll, current["name"]):
439
+ return coll, _append(hist, "assistant", f"{current['name']} is already in the MycoDex!")
440
+
441
+ score_delta = _score_value(current)
442
+ score_total = _score_collection(coll) + score_delta
443
+ collected = {
444
+ **current,
445
+ "score_delta": str(score_delta),
446
+ "score_total": str(score_total),
447
+ "health": str(_health(current, coll)),
448
+ "reward_text": f"+{score_delta} spores",
449
+ }
450
+ updated_coll = [*coll, collected]
451
+
452
+ ctx = _ctx(current, coll)
453
+ prompt = (
454
+ f"The player just added {current['name']} ({current.get('rarity','Common')}) to the MycoDex! "
455
+ f"+{score_delta} spores. Total score: {score_total}. "
456
+ f"MycoDex now has {len(updated_coll)} entries. "
457
+ "Celebrate this moment. Add a small lore detail or mystery hint."
458
+ )
459
+ reply = _llm(prompt, ctx) or _fallback_collect(current)
460
+ return updated_coll, _append(hist, "assistant", reply)
461
+
462
+
463
+ def pick_current(current=None, collection=None, history=None):
464
+ """Pick mushroom as game item. Poison = game over. LLM narrates dramatically."""
465
+ coll = _safe_collection(collection)
466
+ hist = _safe_history(history)
467
+
468
+ if current is None:
469
+ return coll, None, _append(hist, "assistant", "Find a mushroom first before picking!")
470
+
471
+ ctx = _ctx(current, coll)
472
+
473
+ if _is_poisonous(current):
474
+ score_total = max(0, _score_collection(coll) + POISON_PENALTY)
475
+ game_over = {
476
+ **current,
477
+ "danger": "Poisonous",
478
+ "game_over": "Yes",
479
+ "health": "0",
480
+ "score_delta": str(POISON_PENALTY),
481
+ "score_total": str(score_total),
482
+ "reward_text": f"Poison! {POISON_PENALTY} spores Β· Game Over",
483
+ }
484
+ prompt = (
485
+ f"DRAMATIC MOMENT: The player picked {current['name']} which is POISONOUS! "
486
+ f"Game Over! Score drops by 25 to {score_total}. Health β†’ 0. "
487
+ "React with shock, sadness, and a dramatic farewell. Make it memorable."
488
+ )
489
+ reply = _llm(prompt, ctx) or _fallback_pick(current)
490
+ return coll, game_over, _append(hist, "assistant", f"πŸ’€ {reply}")
491
+
492
+ score_delta = _score_value(current)
493
+ score_total = _score_collection(coll) + score_delta
494
+ picked = {
495
+ **current,
496
+ "picked": "Yes",
497
+ "danger": "Safe",
498
+ "score_delta": str(score_delta),
499
+ "score_total": str(score_total),
500
+ "health": str(_health(current, coll)),
501
+ "reward_text": f"+{score_delta} spores",
502
+ }
503
+
504
+ if collection_contains(coll, picked["name"]):
505
+ return coll, picked, _append(hist, "assistant", f"{picked['name']} already picked!")
506
+
507
+ updated_coll = [*coll, picked]
508
+ prompt = (
509
+ f"The player safely picked {current['name']} ({current.get('rarity','Common')})! "
510
+ f"+{score_delta} spores. Total: {score_total}. "
511
+ "Celebrate! Make it feel like a platformer power-up moment."
512
+ )
513
+ reply = _llm(prompt, ctx) or _fallback_pick(current)
514
+ return updated_coll, picked, _append(hist, "assistant", f"πŸ„ {reply}")
515
+
516
+
517
+ def follow_whisper(current=None, collection=None, history=None):
518
+ """Follow the forest whisper. LLM reveals mystery fragments."""
519
+ coll = _safe_collection(collection)
520
+ hist = _safe_history(history)
521
+
522
+ if current is None:
523
+ return None, _append(hist, "assistant",
524
+ "Myco cups one ear. The forest only whispers near mushrooms β€” search a clearing first.")
525
+
526
+ ctx = _ctx(current, coll)
527
+
528
+ if _is_poisonous(current) and current.get("studied") != "Yes":
529
+ game_over = {**current, "danger": "Poisonous", "game_over": "Yes",
530
+ "health": "0", "score_total": str(max(0, _score_collection(coll) + POISON_PENALTY))}
531
+ prompt = (
532
+ f"The player followed a whisper but it led to POISON from {current['name']}! Game Over! "
533
+ "React with horror and a haunting mystery revelation."
534
+ )
535
+ reply = _llm(prompt, ctx) or "πŸ’€ The whisper belonged to poison... Myco screams."
536
+ return game_over, _append(hist, "assistant", reply)
537
+
538
+ mystery = _mystery_state(len(coll) + 1)
539
+ prompt = (
540
+ f"The player followed a forest whisper near {current.get('name','a mushroom')}. "
541
+ f"Mystery chapter revealed: {mystery['mystery_title']}. Clue: {mystery['mystery_clue']}. "
542
+ f"Reveal this mystery fragment dramatically. "
543
+ "Make Myco gasp or tremble. Hint that the MycoDex is alive and regrowing the lost forest."
544
+ )
545
+ reply = _llm(prompt, ctx) or _fallback_whisper(current)
546
+ revealed = {
547
+ **current,
548
+ **mystery,
549
+ "whisper_followed": "Yes",
550
+ }
551
+ return revealed, _append(hist, "assistant", f"🌌 {reply}")
552
+
553
+
554
+ def study_current(current=None, history=None):
555
+ """Study mushroom. LLM gives a careful field observation."""
556
+ hist = _safe_history(history)
557
+
558
+ if current is None:
559
+ return None, _append(hist, "assistant", "Nothing to study yet β€” find a mushroom first!")
560
+
561
+ magic_hints = {"Legendary": "Strong, mysterious aura", "Rare": "Faint magical trace", "Common": "Tiny spore shimmer"}
562
+ studied = {**current, "magic": magic_hints.get(current.get("rarity", "Common"), "Unknown"), "studied": "Yes"}
563
+
564
+ ctx = _ctx(studied, [])
565
+ prompt = (
566
+ f"Myco carefully studies {current['name']} ({current.get('rarity','Common')} rarity). "
567
+ f"Habitat: {current.get('habitat','?')}. Lore: {current.get('lore','?')}. "
568
+ f"Magic field is now: {studied['magic']}. "
569
+ "Share one careful field observation. Warn if it might be dangerous. "
570
+ "Be scientific but stay in character as a curious mushroom companion."
571
+ )
572
+ reply = _llm(prompt, ctx) or _fallback_study(current)
573
+ return studied, _append(hist, "assistant", f"πŸ” {reply}")
574
+
575
+
576
+ def eat_current(current=None, history=None):
577
+ """Myco blocks eating. LLM reacts with personality."""
578
+ hist = _safe_history(history)
579
+
580
+ if current is None:
581
+ return _append(hist, "assistant", "Find a mushroom before making snack decisions!")
582
+
583
+ ctx = _ctx(current, [])
584
+ prompt = (
585
+ f"The player wants to EAT {current.get('name','the mushroom')} "
586
+ f"(edible status: {current.get('edible','Unknown')}). "
587
+ "Block them! React with alarm or gentle scolding. Stay in character."
588
+ )
589
+ reply = _llm(prompt, ctx) or f"Myco blocks you β€” {current.get('name','this')} hasn't been studied enough!"
590
+ return _append(hist, "assistant", reply)