byte-vortex commited on
Commit
421cbe8
·
verified ·
1 Parent(s): fd0179d

Delete game/spare_engine.py

Browse files
Files changed (1) hide show
  1. game/spare_engine.py +0 -649
game/spare_engine.py DELETED
@@ -1,649 +0,0 @@
1
- """
2
- Core Myco gameplay — LLM is the primary game engine.
3
- """
4
-
5
- import os
6
- import random
7
- import threading
8
- import re
9
- import json
10
- import traceback
11
-
12
- from game.catalog import load_mushrooms
13
- from game.state import collection_contains, mushroom_from_state, welcome_history
14
-
15
-
16
- import os
17
- import torch
18
- import spaces
19
- from transformers import AutoModelForCausalLM, AutoTokenizer
20
-
21
- DEFAULT_MODEL_ID = "google/gemma-3-1b-it"
22
-
23
- # Global singletons
24
- _model = None
25
- _tokenizer = None
26
- _lock = threading.Lock() # Ensure this matches your existing lock variable name
27
-
28
- def _get_model_and_tokenizer():
29
- global _model, _tokenizer
30
- if _model is not None and _tokenizer is not None:
31
- return _model, _tokenizer
32
-
33
- with _lock:
34
- if _model is not None and _tokenizer is not None:
35
- return _model, _tokenizer
36
-
37
- model_id = os.getenv("MYCO_MODEL_ID", "google/gemma-3-1b-it")
38
- token = os.getenv("HF_BUILD_SMALL_HACKATHON_TOKEN")
39
-
40
- try:
41
- print(f"\n[Myco] Loading model and tokenizer for {model_id}...")
42
-
43
- # Load tokenizer
44
- _tokenizer = AutoTokenizer.from_pretrained(model_id, token=token)
45
-
46
- # Load model strictly on CPU with bfloat16 precision
47
- _model = AutoModelForCausalLM.from_pretrained(
48
- model_id,
49
- token=token,
50
- torch_dtype=torch.bfloat16,
51
- device_map=None, # CRITICAL: Must be None so ZeroGPU can hook it safely
52
- trust_remote_code=True
53
- )
54
- print(f"[Myco] Successfully loaded: {model_id}")
55
- return _model, _tokenizer
56
- except Exception as exc:
57
- print(f"[Myco] Load error: {exc}")
58
- return None, None
59
-
60
- # ---------------------------------------------------------------------------
61
- # Pipeline loader
62
- # ---------------------------------------------------------------------------
63
- def _get_pipeline():
64
- """ Legacy compatibility wrapper so companion_status() and other
65
- startup hooks don't throw a NameError.
66
- """
67
- model, tokenizer = _get_model_and_tokenizer()
68
- if model is not None and tokenizer is not None:
69
- # Return the model instance so 'if pipe is not None' checks pass successfully
70
- return model
71
- return None
72
-
73
- # ---------------------------------------------------------------------------
74
- # GPU runner — ONLY this function gets the @spaces.GPU decorator.
75
- # ---------------------------------------------------------------------------
76
- @spaces.GPU
77
- def _run_pipeline(pipe_ignored, messages):
78
- # 1. Fetch our raw model and tokenizer singletons
79
- model, tokenizer = _get_model_and_tokenizer()
80
- if model is None or tokenizer is None:
81
- return "The forest is silent. (Model loading failed)"
82
-
83
- # CRITICAL: Do NOT call model.to("cuda") manually here.
84
- # ZeroGPU's @spaces.GPU decorator handles the weight migration automatically.
85
-
86
- # 2. Build the chat template structure natively
87
- formatted_prompt = tokenizer.apply_chat_template(
88
- messages,
89
- tokenize=False,
90
- add_generation_prompt=True
91
- )
92
-
93
- # 3. Tokenize and dynamically map inputs to the exact device the model is currently using
94
- inputs = tokenizer(formatted_prompt, return_tensors="pt").to(model.device)
95
-
96
- # 4. Generate clean text without any configuration conflicts
97
- with torch.no_grad():
98
- outputs = model.generate(
99
- **inputs,
100
- max_new_tokens=256,
101
- do_sample=True,
102
- temperature=0.7,
103
- pad_token_id=tokenizer.eos_token_id
104
- )
105
-
106
- # 5. Extract only the newly generated text tokens
107
- input_length = inputs.input_ids.shape[1]
108
- generated_tokens = outputs[0][input_length:]
109
-
110
- return tokenizer.decode(generated_tokens, skip_special_tokens=True)
111
-
112
-
113
- JSON_PROMPT_SUFFIX = (
114
- "\n\nRespond with a single JSON object only. No prose before or after it. "
115
- 'Example: {"action":"pick","target":"Ruby Knuckle","thought":"It seems safe."}'
116
- )
117
-
118
- RARITY_WEIGHTS = {"Common": 64, "Rare": 24, "Legendary": 8}
119
- RARITY_SCORE = {"Common": 10, "Rare": 35, "Legendary": 100}
120
- PLAYER_HEALTH = 3
121
- POISON_PENALTY = -25
122
- POISONOUS = {"Ghost Gill", "Pepper Pixie", "Ruby Knuckle", "Clockwork Chanterelle"}
123
-
124
- SYSTEM_PROMPT = """You are Myco, a tiny sentient mushroom companion and forest guide.
125
- You are curious, warm, slightly anxious about poisonous mushrooms, and deeply connected
126
- to the forest mystery. You speak in short, vivid sentences. You never break character.
127
- You react emotionally to discoveries — with awe for Legendary mushrooms, caution for
128
- poisonous ones, and gentle wonder for Common ones. You hint at the deeper mystery of
129
- the vanished forest and the MycoDex that seems to remember things it shouldn't."""
130
-
131
- FOREST_EVENTS = [
132
- {"title": "A Quiet Clearing", "emoji": "🌿", "mood": "calm"},
133
- {"title": "Wind Between Trees", "emoji": "🕯️", "mood": "afraid"},
134
- ]
135
-
136
- MYSTERY_CHAPTERS = [
137
- {"threshold": 0, "title": "The Wrong Memory", "clue": "Myco recognises the path before you move."},
138
- {"threshold": 1, "title": "The Traveler's Song", "clue": "A stranger's lullaby appears in the MycoDex margin."},
139
- {"threshold": 2, "title": "The Door Under Roots","clue": "Rare spores point to a door nobody built."},
140
- {"threshold": 3, "title": "The MycoDex Seed", "clue": "The MycoDex grows warm like a living cap."},
141
- {"threshold": 5, "title": "The Impossible Bloom","clue": "The Impossible Mushroom was never outside the book."},
142
- ]
143
-
144
- RARITY_CLUES = {
145
- "Common": "The cap leans toward the path, like it wants to be remembered.",
146
- "Rare": "Silver spores circle it in a pattern only old forest stories describe.",
147
- "Legendary": "The whole clearing goes quiet — this mushroom hides part of the Elder Map.",
148
- }
149
-
150
-
151
- # ---------------------------------------------------------------------------
152
- # Utility: extract JSON or return text
153
- # ---------------------------------------------------------------------------
154
- def _extract_json_or_text(generated_text: str) -> str | None:
155
- if not generated_text:
156
- return None
157
- text = str(generated_text).strip()
158
-
159
- simple_matches = re.findall(r"\{.*?\}|\[.*?\]", text, flags=re.DOTALL)
160
- if simple_matches:
161
- for candidate in reversed(simple_matches):
162
- try:
163
- parsed = json.loads(candidate)
164
- return json.dumps(parsed, separators=(",", ":"), ensure_ascii=False)
165
- except Exception:
166
- continue
167
-
168
- return text or None
169
-
170
-
171
- # ---------------------------------------------------------------------------
172
- # Status
173
- # ---------------------------------------------------------------------------
174
- def companion_model_id():
175
- return os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)
176
-
177
-
178
- def companion_status():
179
- pipe = _get_pipeline()
180
- model = companion_model_id()
181
- if pipe:
182
- return f"🧠 Myco AI active ({model})"
183
- return f"⚠️ Myco AI fallback mode ({model} failed)"
184
-
185
-
186
- def hf_companion_status():
187
- return companion_status()
188
-
189
-
190
- # ---------------------------------------------------------------------------
191
- # LLM call — single-turn
192
- # ---------------------------------------------------------------------------
193
- def _llm(prompt: str, context: dict | None = None) -> str | None:
194
- pipe = _get_pipeline()
195
- if not pipe:
196
- return None
197
-
198
- ctx = context or {}
199
- mushroom_line = ""
200
- if ctx.get("name"):
201
- poison_flag = " ⚠️ POISONOUS" if ctx.get("name") in POISONOUS else ""
202
- mushroom_line = (
203
- f"Current mushroom: {ctx['name']} ({ctx.get('rarity','?')} rarity){poison_flag}. "
204
- f"Habitat: {ctx.get('habitat','?')}. Lore: {ctx.get('lore','?')}. "
205
- f"Edible: {ctx.get('edible','Unknown')}. Magic: {ctx.get('magic','Unknown')}. "
206
- f"Danger: {ctx.get('danger','Unknown')}."
207
- )
208
-
209
- collection_line = f"MycoDex entries: {ctx.get('collection_count', 0)}."
210
- mystery_line = f"Active mystery chapter: {ctx.get('mystery_title', 'The Wrong Memory')}."
211
- score_line = f"Player score: {ctx.get('score', 0)} spores. Health: {ctx.get('health', 3)}/3."
212
-
213
- system = f"{SYSTEM_PROMPT}\n\n{mushroom_line}\n{collection_line}\n{mystery_line}\n{score_line}"
214
-
215
- messages = [
216
- {"role": "system", "content": system},
217
- {"role": "user", "content": prompt + JSON_PROMPT_SUFFIX},
218
- ]
219
-
220
- try:
221
- outputs = _run_pipeline(pipe, messages)
222
- print("========== MYCO OUTPUT ==========")
223
- print(outputs)
224
- print("=================================")
225
-
226
- if isinstance(outputs, list) and outputs:
227
- first = outputs[0]
228
- generated = first.get("generated_text", "") if isinstance(first, dict) else str(first)
229
- else:
230
- generated = str(outputs)
231
-
232
- if isinstance(generated, list):
233
- last = generated[-1]
234
- text = last.get("content") if isinstance(last, dict) else str(last)
235
- else:
236
- text = str(generated)
237
-
238
- return _extract_json_or_text(text)
239
- except Exception as exc:
240
- print(f"[Myco] Inference error: {exc}")
241
- traceback.print_exc()
242
- return None
243
-
244
-
245
- # ---------------------------------------------------------------------------
246
- # LLM call — multi-turn chat
247
- # ---------------------------------------------------------------------------
248
- def _llm_with_history(history: list, user_message: str, context: dict) -> str | None:
249
- pipe = _get_pipeline()
250
- if not pipe:
251
- return None
252
-
253
- ctx = context or {}
254
- mushroom_line = ""
255
- if ctx.get("name"):
256
- poison_flag = " ⚠️ POISONOUS" if ctx.get("name") in POISONOUS else ""
257
- mushroom_line = (
258
- f"Current mushroom: {ctx['name']} ({ctx.get('rarity','?')}){poison_flag}. "
259
- f"Lore: {ctx.get('lore','?')}. "
260
- f"Edible: {ctx.get('edible','Unknown')}. Magic: {ctx.get('magic','Unknown')}."
261
- )
262
-
263
- system = (
264
- f"{SYSTEM_PROMPT}\n\n"
265
- f"{mushroom_line}\n"
266
- f"MycoDex entries: {ctx.get('collection_count', 0)}. "
267
- f"Mystery: {ctx.get('mystery_title', 'The Wrong Memory')}. "
268
- f"Score: {ctx.get('score', 0)} spores. Health: {ctx.get('health', 3)}/3."
269
- )
270
-
271
- messages = [{"role": "system", "content": system}]
272
- for entry in history[-6:]:
273
- role = entry.get("role", "assistant")
274
- content = entry.get("content", "")
275
- if isinstance(content, str) and content.strip():
276
- messages.append({"role": role, "content": content})
277
- # Chat replies: no JSON forcing — Myco speaks naturally here.
278
- messages.append({"role": "user", "content": user_message})
279
-
280
- try:
281
- reply = _run_pipeline(pipe, messages)
282
-
283
- print("========== MYCO OUTPUT ==========")
284
- print(reply)
285
- print("=================================")
286
-
287
- return reply
288
-
289
- except Exception as exc:
290
- print(f"[Myco] Inference error: {exc}")
291
- traceback.print_exc()
292
- return None
293
-
294
-
295
- # ---------------------------------------------------------------------------
296
- # Context builder
297
- # ---------------------------------------------------------------------------
298
- def _ctx(current: dict | None, collection: list) -> dict:
299
- count = len(collection)
300
- chapter = MYSTERY_CHAPTERS[0]
301
- for c in MYSTERY_CHAPTERS:
302
- if count >= c["threshold"]:
303
- chapter = c
304
- score = _score_collection(collection)
305
- health = _health(current, collection)
306
- ctx: dict = {
307
- "collection_count": count,
308
- "mystery_title": chapter["title"],
309
- "mystery_clue": chapter["clue"],
310
- "score": score,
311
- "health": health,
312
- }
313
- if current:
314
- ctx.update({
315
- "name": current.get("name", ""),
316
- "rarity": current.get("rarity", "Common"),
317
- "habitat": current.get("habitat", ""),
318
- "lore": current.get("lore", ""),
319
- "edible": current.get("edible", "Unknown"),
320
- "magic": current.get("magic", "Unknown"),
321
- "danger": current.get("danger", "Unknown"),
322
- })
323
- return ctx
324
-
325
-
326
- # ---------------------------------------------------------------------------
327
- # Fallbacks
328
- # ---------------------------------------------------------------------------
329
- def _fallback_discover(current: dict) -> str:
330
- name = current.get("name", "something")
331
- rarity = current.get("rarity", "Common")
332
- poison = current.get("name", "") in POISONOUS
333
- if poison:
334
- return f"Wait — {name}! I've seen this before... something feels very wrong. Don't touch it yet."
335
- if rarity == "Legendary":
336
- return f"Oh! Oh! A {name}! The whole clearing just went silent. This is from the Elder Map!"
337
- if rarity == "Rare":
338
- return f"A {name}... I can feel it humming. Something rare is here — maybe magical."
339
- return f"A {name}! Found near {current.get('habitat','the forest')}. Let me sense it first."
340
-
341
-
342
- def _fallback_pick(current: dict) -> str:
343
- if _is_poisonous(current):
344
- return "💀 That was poisonous! I tried to stop you... the forest goes dark."
345
- return f"Got {current.get('name','it')}! +{RARITY_SCORE.get(current.get('rarity','Common'),10)} spores!"
346
-
347
-
348
- def _fallback_study(current: dict) -> str:
349
- return f"I studied it carefully. Magic field updated. The clue: {RARITY_CLUES.get(current.get('rarity','Common'), '')}"
350
-
351
-
352
- def _fallback_collect(current: dict) -> str:
353
- return f"Added {current.get('name','it')} to the MycoDex! The pages feel warmer."
354
-
355
-
356
- def _fallback_whisper(current: dict) -> str:
357
- return "I followed the whisper... and remembered a path I've never walked. The mystery deepens."
358
-
359
-
360
- def _fallback_chat(current: dict | None) -> str:
361
- if current:
362
- return f"I feel something strange about {current.get('name','this')}... stay close to me."
363
- return "The forest is full of secrets. Move to a clearing and search — I'll watch for danger."
364
-
365
-
366
- # ---------------------------------------------------------------------------
367
- # Mushroom helpers
368
- # ---------------------------------------------------------------------------
369
- def _choose_mushroom(catalog=None):
370
- mushrooms = tuple(load_mushrooms() if catalog is None else catalog)
371
- weights = [RARITY_WEIGHTS.get(m.rarity, 12) for m in mushrooms]
372
- return random.choices(mushrooms, weights=weights, k=1)[0]
373
-
374
-
375
- def _is_poisonous(current: dict) -> bool:
376
- return current.get("name", "") in POISONOUS or current.get("danger") == "Poisonous"
377
-
378
-
379
- def _score_value(current: dict) -> int:
380
- return RARITY_SCORE.get(current.get("rarity", "Common"), 10)
381
-
382
-
383
- def _score_collection(collection: list) -> int:
384
- total = 0
385
- for e in collection:
386
- if e.get("game_over") == "Yes":
387
- continue
388
- total += int(e.get("score_delta") or _score_value(e))
389
- return max(0, total)
390
-
391
-
392
- def _health(current: dict | None, collection: list) -> int:
393
- if current and current.get("game_over") == "Yes":
394
- return 0
395
- deaths = sum(1 for e in collection if e.get("game_over") == "Yes")
396
- return max(0, PLAYER_HEALTH - deaths)
397
-
398
-
399
- def _mystery_state(count: int) -> dict:
400
- chapter, next_ch = MYSTERY_CHAPTERS[0], None
401
- for c in MYSTERY_CHAPTERS:
402
- if count >= c["threshold"]:
403
- chapter = c
404
- elif next_ch is None:
405
- next_ch = c
406
- next_line = (
407
- f"{next_ch['threshold'] - count} discoveries until {next_ch['title']}."
408
- if next_ch else "The Impossible Bloom is near. Follow the whisper."
409
- )
410
- return {
411
- "mystery_title": chapter["title"],
412
- "mystery_clue": chapter["clue"],
413
- "mystery_next": next_line,
414
- }
415
-
416
-
417
- def _story_event(count: int) -> dict:
418
- return FOREST_EVENTS[count % len(FOREST_EVENTS)]
419
-
420
-
421
- def _build_current(mushroom, collection: list) -> dict:
422
- count = len(collection)
423
- current = mushroom.to_dict()
424
- current["poison"] = "Yes" if mushroom.name in POISONOUS else "No"
425
- current["score_total"] = str(_score_collection(collection))
426
- current["health"] = str(_health(current, collection))
427
- current["score_delta"] = "0"
428
- current["clue"] = RARITY_CLUES.get(mushroom.rarity, RARITY_CLUES["Common"])
429
- if count == 0:
430
- current["clue"] = f"First clue: {mushroom.name} marks the beginning of the Spore Door trail."
431
- event = _story_event(count)
432
- current.update({
433
- "event_title": event["title"],
434
- "event_emoji": event["emoji"],
435
- "myco_mood": event["mood"],
436
- "reward_text": "Discover, then pick or collect.",
437
- })
438
- current.update(_mystery_state(count))
439
- return current
440
-
441
-
442
- def _append(history: list, role: str, content: str) -> list:
443
- return [*history, {"role": role, "content": content}]
444
-
445
-
446
- def _safe_history(h) -> list:
447
- return list(h or welcome_history())
448
-
449
-
450
- def _safe_collection(c) -> list:
451
- return list(c or [])
452
-
453
-
454
- # ---------------------------------------------------------------------------
455
- # Public game actions
456
- # ---------------------------------------------------------------------------
457
- def discover_mushroom(collection=None, catalog=None):
458
- """Discover a new mushroom. LLM narrates the moment."""
459
- coll = _safe_collection(collection)
460
- mushroom = _choose_mushroom(catalog)
461
- current = _build_current(mushroom, coll)
462
- ctx = _ctx(current, coll)
463
-
464
- prompt = (
465
- f"The player just discovered a {mushroom.rarity} mushroom called {mushroom.name} "
466
- f"near {mushroom.habitat}. "
467
- f"{'WARNING: this mushroom is POISONOUS! React with fear and urgency.' if mushroom.name in POISONOUS else ''}"
468
- f"{'This is LEGENDARY — react with awe and excitement!' if mushroom.rarity == 'Legendary' else ''}"
469
- f"{'This is RARE — react with wonder and curiosity.' if mushroom.rarity == 'Rare' else ''}"
470
- f"Forest event: {current['event_title']}. Myco mood: {current['myco_mood']}. "
471
- f"Mystery chapter: {current['mystery_title']}. "
472
- "React in character. Hint at what to do next (Study, Pick, Follow Whisper, or Collect)."
473
- )
474
- reply = _llm(prompt, ctx) or _fallback_discover(current)
475
- history = _append(welcome_history(), "assistant", reply)
476
- return mushroom, current, history
477
-
478
-
479
- def myco_reply(message=None, history=None, current=None, collection=None, position=None):
480
- """Player chats with Myco. LLM responds in character with full context."""
481
- print("MYCO_REPLY CALLED, message:", repr(message))
482
- hist = _safe_history(history)
483
- coll = _safe_collection(collection)
484
- clean = (message or "").strip()
485
- if not clean:
486
- return "", hist
487
-
488
- ctx = _ctx(current, coll)
489
- reply = _llm_with_history(hist, clean, ctx)
490
- if not reply:
491
- reply = _fallback_chat(current)
492
-
493
- return "", _append(hist, "user", clean) + [{"role": "assistant", "content": reply}]
494
-
495
-
496
- companion_reply = myco_reply
497
-
498
-
499
- def collect_current(current=None, collection=None, history=None):
500
- """Collect mushroom into MycoDex. LLM narrates the entry."""
501
- coll = _safe_collection(collection)
502
- hist = _safe_history(history)
503
-
504
- if current is None:
505
- return coll, _append(hist, "assistant", "We need to find a mushroom first!")
506
-
507
- if collection_contains(coll, current["name"]):
508
- return coll, _append(hist, "assistant", f"{current['name']} is already in the MycoDex!")
509
-
510
- score_delta = _score_value(current)
511
- score_total = _score_collection(coll) + score_delta
512
- collected = {
513
- **current,
514
- "score_delta": str(score_delta),
515
- "score_total": str(score_total),
516
- "health": str(_health(current, coll)),
517
- "reward_text": f"+{score_delta} spores",
518
- }
519
- updated_coll = [*coll, collected]
520
- ctx = _ctx(current, coll)
521
-
522
- prompt = (
523
- f"The player just added {current['name']} ({current.get('rarity','Common')}) to the MycoDex! "
524
- f"+{score_delta} spores. Total score: {score_total}. "
525
- f"MycoDex now has {len(updated_coll)} entries. "
526
- "Celebrate this moment. Add a small lore detail or mystery hint."
527
- )
528
- reply = _llm(prompt, ctx) or _fallback_collect(current)
529
- return updated_coll, _append(hist, "assistant", reply)
530
-
531
-
532
- def pick_current(current=None, collection=None, history=None):
533
- """Pick mushroom as game item. Poison = game over. LLM narrates dramatically."""
534
- coll = _safe_collection(collection)
535
- hist = _safe_history(history)
536
-
537
- if current is None:
538
- return coll, None, _append(hist, "assistant", "Find a mushroom first before picking!")
539
-
540
- ctx = _ctx(current, coll)
541
-
542
- if _is_poisonous(current):
543
- score_total = max(0, _score_collection(coll) + POISON_PENALTY)
544
- game_over = {
545
- **current,
546
- "danger": "Poisonous",
547
- "game_over": "Yes",
548
- "health": "0",
549
- "score_delta": str(POISON_PENALTY),
550
- "score_total": str(score_total),
551
- "reward_text": f"Poison! {POISON_PENALTY} spores · Game Over",
552
- }
553
- prompt = (
554
- f"DRAMATIC MOMENT: The player picked {current['name']} which is POISONOUS! "
555
- f"Game Over! Score drops by 25 to {score_total}. Health → 0. "
556
- "React with shock, sadness, and a dramatic farewell. Make it memorable."
557
- )
558
- reply = _llm(prompt, ctx) or _fallback_pick(current)
559
- return coll, game_over, _append(hist, "assistant", f"💀 {reply}")
560
-
561
- score_delta = _score_value(current)
562
- score_total = _score_collection(coll) + score_delta
563
- picked = {
564
- **current,
565
- "picked": "Yes",
566
- "danger": "Safe",
567
- "score_delta": str(score_delta),
568
- "score_total": str(score_total),
569
- "health": str(_health(current, coll)),
570
- "reward_text": f"+{score_delta} spores",
571
- }
572
-
573
- if collection_contains(coll, picked["name"]):
574
- return coll, picked, _append(hist, "assistant", f"{picked['name']} already picked!")
575
-
576
- updated_coll = [*coll, picked]
577
- prompt = (
578
- f"The player safely picked {current['name']} ({current.get('rarity','Common')})! "
579
- f"+{score_delta} spores. Total: {score_total}. "
580
- "Celebrate! Make it feel like a platformer power-up moment."
581
- )
582
- reply = _llm(prompt, ctx) or _fallback_pick(current)
583
- return updated_coll, picked, _append(hist, "assistant", f"🍄 {reply}")
584
-
585
-
586
- def follow_whisper(current=None, collection=None, history=None):
587
- """Follow the forest whisper. LLM reveals mystery fragments."""
588
- coll = _safe_collection(collection)
589
- hist = _safe_history(history)
590
-
591
- if current is None:
592
- return None, _append(hist, "assistant",
593
- "Myco cups one ear. The forest only whispers near mushrooms — search a clearing first.")
594
-
595
- ctx = _ctx(current, coll)
596
-
597
- if _is_poisonous(current) and current.get("studied") != "Yes":
598
- game_over = {
599
- **current,
600
- "danger": "Poisonous",
601
- "game_over": "Yes",
602
- "health": "0",
603
- "score_total": str(max(0, _score_collection(coll) + POISON_PENALTY)),
604
- }
605
- prompt = (
606
- f"The player followed a whisper but it led to POISON from {current['name']}! Game Over! "
607
- "React with horror and a haunting mystery revelation."
608
- )
609
- reply = _llm(prompt, ctx) or "💀 The whisper belonged to poison... Myco screams."
610
- return game_over, _append(hist, "assistant", reply)
611
-
612
- mystery = _mystery_state(len(coll) + 1)
613
- prompt = (
614
- f"The player followed a forest whisper near {current.get('name','a mushroom')}. "
615
- f"Mystery chapter revealed: {mystery['mystery_title']}. Clue: {mystery['mystery_clue']}. "
616
- "Reveal this mystery fragment dramatically. "
617
- "Make Myco gasp or tremble. Hint that the MycoDex is alive and regrowing the lost forest."
618
- )
619
- reply = _llm(prompt, ctx) or _fallback_whisper(current)
620
- revealed = {**current, **mystery, "whisper_followed": "Yes"}
621
- return revealed, _append(hist, "assistant", f"🌌 {reply}")
622
-
623
-
624
- def study_current(current=None, history=None):
625
- """Study mushroom. LLM gives a careful field observation."""
626
- hist = _safe_history(history)
627
-
628
- if current is None:
629
- return None, _append(hist, "assistant", "Nothing to study yet — find a mushroom first!")
630
-
631
- prompt = (
632
- f"Study the mushroom {current.get('name','unknown')} carefully. "
633
- "Provide a concise field observation and one hint about its magic or danger."
634
- )
635
- reply = _llm(prompt, _ctx(current, [])) or _fallback_study(current)
636
- return reply, _append(hist, "assistant", reply)
637
-
638
-
639
- def eat_current(current=None, collection=None, history=None):
640
- """Eating mushrooms raw is always blocked."""
641
- hist = _safe_history(history)
642
- if current is None:
643
- return collection, _append(hist, "assistant", "There's nothing here to eat!")
644
- reply = (
645
- f"No no no! {current.get('name','That')} could be dangerous raw! "
646
- "I'll never let you eat an unidentified mushroom. Study it first!"
647
- )
648
- return collection, _append(hist, "assistant", reply)
649
-