byte-vortex commited on
Commit
e4b7bb9
·
verified ·
1 Parent(s): fd6b28c

Delete game/old--engine.py

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