Spaces:
Sleeping
Sleeping
Deploy Myco from CI
Browse files- game/engine.py +253 -185
game/engine.py
CHANGED
|
@@ -3,17 +3,20 @@
|
|
| 3 |
import os
|
| 4 |
import random
|
| 5 |
|
| 6 |
-
from huggingface_hub import InferenceClient
|
| 7 |
-
|
| 8 |
from game.catalog import load_mushrooms
|
| 9 |
from game.state import collection_contains, mushroom_from_state, welcome_history
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
RARITY_WEIGHTS = {"Common": 64, "Rare": 24, "Legendary": 8}
|
| 14 |
RARITY_SCORE_VALUES = {"Common": 10, "Rare": 35, "Legendary": 100}
|
| 15 |
PLAYER_STARTING_HEALTH = 3
|
| 16 |
POISON_SCORE_PENALTY = -25
|
|
|
|
| 17 |
MYCO_CHARACTER_SPEC = """
|
| 18 |
# Myco Character Specification
|
| 19 |
|
|
@@ -48,12 +51,15 @@ Myco notices impossible details but does not explain them immediately. Myco beco
|
|
| 48 |
Design goal:
|
| 49 |
Players should think, "I want to see what happens next" and "I wonder what Myco thinks about this."
|
| 50 |
""".strip()
|
|
|
|
| 51 |
RARITY_CLUES = {
|
| 52 |
"Common": "The cap leans toward the path, like it wants to be remembered.",
|
| 53 |
"Rare": "Silver spores circle it in a pattern Myco has seen only in old forest stories.",
|
| 54 |
"Legendary": "The whole clearing goes quiet; this mushroom is hiding part of the Elder Map.",
|
| 55 |
}
|
|
|
|
| 56 |
POISONOUS_MUSHROOMS = {"Ghost Gill", "Pepper Pixie", "Ruby Knuckle", "Clockwork Chanterelle"}
|
|
|
|
| 57 |
FOREST_EVENTS = (
|
| 58 |
{
|
| 59 |
"title": "Silver Rain",
|
|
@@ -84,14 +90,17 @@ FOREST_EVENTS = (
|
|
| 84 |
"consequence": "The forest answers only if you stop rushing.",
|
| 85 |
},
|
| 86 |
)
|
|
|
|
| 87 |
RARE_ENCOUNTERS = (
|
| 88 |
"A lost traveler asks why Myco knows their childhood song.",
|
| 89 |
"A mushroom guardian blocks the trail and counts your clues.",
|
| 90 |
"A tiny forest spirit swaps your shadow with a spore-shadow.",
|
| 91 |
"Something under the roots whispers: Myco has been here before.",
|
| 92 |
)
|
|
|
|
| 93 |
IMPOSSIBLE_OBJECTIVE = "Find the Impossible Mushroom and learn why Myco remembers a forest that vanished."
|
| 94 |
MYSTERY_QUESTION = "Why does Myco remember places that disappeared before Myco was born?"
|
|
|
|
| 95 |
MYSTERY_CHAPTERS = (
|
| 96 |
{
|
| 97 |
"threshold": 0,
|
|
@@ -125,6 +134,62 @@ MYSTERY_CHAPTERS = (
|
|
| 125 |
},
|
| 126 |
)
|
| 127 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 128 |
|
| 129 |
def choose_mushroom(catalog=None):
|
| 130 |
"""Choose a mushroom discovery from the catalog."""
|
|
@@ -155,6 +220,11 @@ def discover_mushroom(collection=None, catalog=None):
|
|
| 155 |
return mushroom, current, history
|
| 156 |
|
| 157 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 158 |
def myco_reply(message=None, history=None, current=None, collection=None, position=None):
|
| 159 |
"""Generate Myco's companion reply from the player's current journey context."""
|
| 160 |
current_history = _safe_history(history)
|
|
@@ -169,14 +239,47 @@ def myco_reply(message=None, history=None, current=None, collection=None, positi
|
|
| 169 |
return "", [*next_history, _assistant_message(answer)]
|
| 170 |
|
| 171 |
|
|
|
|
|
|
|
|
|
|
| 172 |
def _companion_answer(message, current, context):
|
| 173 |
-
"""Return the
|
| 174 |
-
answer =
|
| 175 |
if answer is None:
|
| 176 |
-
return
|
| 177 |
return answer
|
| 178 |
|
| 179 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
def _discovery_reaction(current, collection):
|
| 181 |
"""Return Myco's first reaction to a new discovery."""
|
| 182 |
mushroom = mushroom_from_state(current)
|
|
@@ -189,7 +292,7 @@ def _discovery_reaction(current, collection):
|
|
| 189 |
f"Mystery: {current.get('mystery_title', 'The Wrong Memory')}. "
|
| 190 |
"React as Myco with emotion, make the moment memorable, and invite a meaningful choice."
|
| 191 |
)
|
| 192 |
-
answer =
|
| 193 |
if answer:
|
| 194 |
return answer
|
| 195 |
|
|
@@ -204,7 +307,7 @@ def _discovery_reaction(current, collection):
|
|
| 204 |
)
|
| 205 |
|
| 206 |
|
| 207 |
-
def
|
| 208 |
"""Return the deterministic fallback companion answer using game context."""
|
| 209 |
if current:
|
| 210 |
mushroom = mushroom_from_state(current)
|
|
@@ -223,148 +326,8 @@ def _local_companion_answer(current, context):
|
|
| 223 |
)
|
| 224 |
|
| 225 |
|
| 226 |
-
def
|
| 227 |
-
"""
|
| 228 |
-
token = _hf_token()
|
| 229 |
-
if not token:
|
| 230 |
-
return None
|
| 231 |
-
|
| 232 |
-
model = hf_model_id()
|
| 233 |
-
messages = _hf_messages(message, current, context)
|
| 234 |
-
try:
|
| 235 |
-
response = InferenceClient(token=token).chat_completion(
|
| 236 |
-
messages=messages,
|
| 237 |
-
model=model,
|
| 238 |
-
max_tokens=90,
|
| 239 |
-
temperature=0.8,
|
| 240 |
-
)
|
| 241 |
-
content = response.choices[0].message.content or ""
|
| 242 |
-
answer = content.strip()
|
| 243 |
-
except (AttributeError, IndexError, TypeError, ValueError):
|
| 244 |
-
return None
|
| 245 |
-
except Exception:
|
| 246 |
-
return None
|
| 247 |
-
|
| 248 |
-
return answer or None
|
| 249 |
-
|
| 250 |
-
|
| 251 |
-
def hf_model_id():
|
| 252 |
-
"""Return the configured Hugging Face model id for Myco."""
|
| 253 |
-
return os.getenv("MYCO_HF_MODEL_ID") or DEFAULT_HF_MODEL_ID
|
| 254 |
-
|
| 255 |
-
|
| 256 |
-
def hf_companion_status():
|
| 257 |
-
"""Return a player-safe status line for the companion model."""
|
| 258 |
-
model = hf_model_id()
|
| 259 |
-
if _hf_token():
|
| 260 |
-
return f"🧠 Myco AI: connected to Hugging Face model `{model}`."
|
| 261 |
-
return f"🧠 Myco AI: waiting for `HF_TOKEN`; fallback voice is active with `{model}` ready."
|
| 262 |
-
|
| 263 |
-
|
| 264 |
-
def _hf_token():
|
| 265 |
-
"""Return the first configured Hugging Face token without exposing it."""
|
| 266 |
-
for env_name in HF_TOKEN_ENV_VARS:
|
| 267 |
-
token = os.getenv(env_name, "").strip()
|
| 268 |
-
if token:
|
| 269 |
-
return token
|
| 270 |
-
return ""
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
def _companion_context(current, collection, history, position):
|
| 274 |
-
"""Summarize the current journey so Myco replies like a present companion."""
|
| 275 |
-
current_collection = _safe_collection(collection)
|
| 276 |
-
count = len(current_collection)
|
| 277 |
-
rare_names = [
|
| 278 |
-
entry.get("name", "Unknown")
|
| 279 |
-
for entry in current_collection
|
| 280 |
-
if entry.get("rarity") != "Common"
|
| 281 |
-
]
|
| 282 |
-
location = _location_label(position)
|
| 283 |
-
quest = MYSTERY_QUESTION
|
| 284 |
-
if current:
|
| 285 |
-
progress = (
|
| 286 |
-
f"{current.get('mystery_title', 'The Wrong Memory')} — "
|
| 287 |
-
f"{current.get('mystery_next', 'keep exploring')}"
|
| 288 |
-
)
|
| 289 |
-
notable_event = (
|
| 290 |
-
f"{current.get('event_emoji', '✨')} {current.get('event_title', 'Strange Omen')}: "
|
| 291 |
-
f"{current.get('encounter', 'the forest is watching')}"
|
| 292 |
-
)
|
| 293 |
-
emotion = current.get("myco_mood", "curious")
|
| 294 |
-
memory = current.get("memory_fragment") or current.get(
|
| 295 |
-
"mystery_reveal",
|
| 296 |
-
"Myco feels the forest tugging at an old memory.",
|
| 297 |
-
)
|
| 298 |
-
pattern = _pattern_notice(current, current_collection)
|
| 299 |
-
else:
|
| 300 |
-
progress = "No active discovery yet; search a clearing to start the mystery."
|
| 301 |
-
notable_event = "Myco is listening before the first omen."
|
| 302 |
-
emotion = "curious"
|
| 303 |
-
memory = "Myco remembers a path that is not on the map yet."
|
| 304 |
-
pattern = "No pattern yet, but the trees are leaning inward."
|
| 305 |
-
|
| 306 |
-
return {
|
| 307 |
-
"location": location,
|
| 308 |
-
"quest": quest,
|
| 309 |
-
"progress": progress,
|
| 310 |
-
"rare_finds": ", ".join(rare_names) if rare_names else "none yet",
|
| 311 |
-
"weather": notable_event,
|
| 312 |
-
"notable_event": notable_event,
|
| 313 |
-
"emotion": emotion,
|
| 314 |
-
"memory": memory,
|
| 315 |
-
"pattern": pattern,
|
| 316 |
-
"conversation": _recent_conversation(history),
|
| 317 |
-
"collection_count": str(count),
|
| 318 |
-
}
|
| 319 |
-
|
| 320 |
-
|
| 321 |
-
def _location_label(position):
|
| 322 |
-
"""Return a small in-world label for the grid position."""
|
| 323 |
-
if position is None:
|
| 324 |
-
return "center clearing"
|
| 325 |
-
x, y = position
|
| 326 |
-
names = {
|
| 327 |
-
(0, 0): "northwest root arch",
|
| 328 |
-
(1, 0): "northern fern gate",
|
| 329 |
-
(2, 0): "northeast moon stump",
|
| 330 |
-
(0, 1): "western moss path",
|
| 331 |
-
(1, 1): "center clearing",
|
| 332 |
-
(2, 1): "eastern glow log",
|
| 333 |
-
(0, 2): "southwest rain hollow",
|
| 334 |
-
(1, 2): "southern spore bridge",
|
| 335 |
-
(2, 2): "southeast elder shade",
|
| 336 |
-
}
|
| 337 |
-
return names.get((int(x), int(y)), "unknown clearing")
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
def _pattern_notice(current, collection):
|
| 341 |
-
"""Return one pattern Myco can comment on from the journey so far."""
|
| 342 |
-
if current.get("game_over") == "Yes":
|
| 343 |
-
return "The same poison warning appeared before Myco could say it aloud."
|
| 344 |
-
if current.get("rarity") == "Legendary":
|
| 345 |
-
return "Legendary spores bend toward the MycoDex instead of the moon."
|
| 346 |
-
if current.get("poison") == "Yes":
|
| 347 |
-
return "Poison omens arrive with black-winged moths and sudden silence."
|
| 348 |
-
if len(collection) >= 3:
|
| 349 |
-
return "Every third clue makes the MycoDex feel warmer, like it is alive."
|
| 350 |
-
if current.get("event_title") == "Moonlit Sporefall":
|
| 351 |
-
return "Moonlit spores keep behaving like memories instead of seeds."
|
| 352 |
-
return "The clues are not random; they keep pointing back to Myco's forgotten path."
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
def _recent_conversation(history):
|
| 356 |
-
"""Return a compact summary of recent player/Myco conversation turns."""
|
| 357 |
-
turns = []
|
| 358 |
-
for entry in _safe_history(history)[-6:]:
|
| 359 |
-
role = entry.get("role", "assistant")
|
| 360 |
-
content = entry.get("content", "").replace("\n", " ").strip()
|
| 361 |
-
if content:
|
| 362 |
-
turns.append(f"{role}: {content[:120]}")
|
| 363 |
-
return " | ".join(turns) if turns else "No conversation yet."
|
| 364 |
-
|
| 365 |
-
|
| 366 |
-
def _hf_messages(message, current, context):
|
| 367 |
-
"""Build a compact chat-completion prompt for Myco as an in-game companion."""
|
| 368 |
mushroom_context = "No mushroom is currently discovered."
|
| 369 |
if current:
|
| 370 |
mushroom = mushroom_from_state(current)
|
|
@@ -413,7 +376,9 @@ def _hf_messages(message, current, context):
|
|
| 413 |
]
|
| 414 |
|
| 415 |
|
| 416 |
-
|
|
|
|
|
|
|
| 417 |
|
| 418 |
|
| 419 |
def collect_current(current=None, collection=None, history=None):
|
|
@@ -477,7 +442,11 @@ def pick_current(current=None, collection=None, history=None):
|
|
| 477 |
)
|
| 478 |
|
| 479 |
score_delta = _score_value(current)
|
| 480 |
-
picked = _with_reward_state(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 481 |
if collection_contains(current_collection, picked["name"]):
|
| 482 |
return current_collection, picked, _append_assistant(
|
| 483 |
current_history,
|
|
@@ -571,37 +540,110 @@ def eat_current(current=None, history=None):
|
|
| 571 |
return _append_assistant(current_history, message)
|
| 572 |
|
| 573 |
|
| 574 |
-
|
| 575 |
-
|
| 576 |
-
|
| 577 |
|
| 578 |
|
| 579 |
-
def
|
| 580 |
-
"""
|
| 581 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 582 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 583 |
|
| 584 |
-
|
| 585 |
-
|
| 586 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 587 |
|
| 588 |
|
| 589 |
-
def
|
| 590 |
-
"""Return
|
| 591 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 592 |
|
| 593 |
|
| 594 |
-
def
|
| 595 |
-
"""Return a
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
|
| 599 |
-
|
| 600 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 601 |
|
| 602 |
|
| 603 |
def _mystery_clue(current, collection_count):
|
| 604 |
-
"""Return a clue that turns each discovery into a small mystery beat."""
|
| 605 |
rarity = current.get("rarity", "Common")
|
| 606 |
name = current.get("name", "this mushroom")
|
| 607 |
clue = RARITY_CLUES.get(rarity, RARITY_CLUES["Common"])
|
|
@@ -615,7 +657,6 @@ def _mystery_clue(current, collection_count):
|
|
| 615 |
|
| 616 |
|
| 617 |
def _mystery_thread(collection_count):
|
| 618 |
-
"""Return the single unfolding mystery state for the current progress."""
|
| 619 |
chapter = MYSTERY_CHAPTERS[0]
|
| 620 |
next_chapter = None
|
| 621 |
for candidate in MYSTERY_CHAPTERS:
|
|
@@ -640,7 +681,6 @@ def _mystery_thread(collection_count):
|
|
| 640 |
|
| 641 |
|
| 642 |
def _story_moment(current, collection_count):
|
| 643 |
-
"""Return the event, encounter, mood, and objective for this discovery."""
|
| 644 |
event = FOREST_EVENTS[collection_count % len(FOREST_EVENTS)]
|
| 645 |
encounter = _encounter_for(current, collection_count)
|
| 646 |
return {
|
|
@@ -655,7 +695,6 @@ def _story_moment(current, collection_count):
|
|
| 655 |
|
| 656 |
|
| 657 |
def _encounter_for(current, collection_count):
|
| 658 |
-
"""Return a rare encounter line tied to rarity, poison, and progress."""
|
| 659 |
if current.get("rarity") == "Legendary":
|
| 660 |
return "A mushroom guardian bows and calls Myco by an old royal name."
|
| 661 |
if _is_poisonous(current):
|
|
@@ -666,7 +705,6 @@ def _encounter_for(current, collection_count):
|
|
| 666 |
|
| 667 |
|
| 668 |
def _memory_fragment(current, collection_count, mystery):
|
| 669 |
-
"""Return the emotional reward for following a story whisper."""
|
| 670 |
name = current.get("name", "this mushroom")
|
| 671 |
reveal = mystery.get("mystery_reveal", "The forest remembers Myco.")
|
| 672 |
if mystery.get("mystery_title") == "The Impossible Bloom":
|
|
@@ -681,7 +719,6 @@ def _memory_fragment(current, collection_count, mystery):
|
|
| 681 |
|
| 682 |
|
| 683 |
def _secret_signal(current, collection_count):
|
| 684 |
-
"""Return a memorable secret/reward hint for the MycoDex."""
|
| 685 |
rarity = current.get("rarity", "Common")
|
| 686 |
if rarity == "Legendary":
|
| 687 |
return "The MycoDex page blooms with a star-shaped seal."
|
|
@@ -692,13 +729,16 @@ def _secret_signal(current, collection_count):
|
|
| 692 |
return "The page smells faintly of rain and moss."
|
| 693 |
|
| 694 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 695 |
def _score_value(current):
|
| 696 |
-
"""Return the score value for a mushroom by rarity."""
|
| 697 |
return RARITY_SCORE_VALUES.get(current.get("rarity", "Common"), 10)
|
| 698 |
|
| 699 |
|
| 700 |
def _score_collection(collection):
|
| 701 |
-
"""Return total spores from collected mushrooms."""
|
| 702 |
total = 0
|
| 703 |
for entry in _safe_collection(collection):
|
| 704 |
if entry.get("game_over") == "Yes":
|
|
@@ -708,15 +748,15 @@ def _score_collection(collection):
|
|
| 708 |
|
| 709 |
|
| 710 |
def _health_for_state(current, collection):
|
| 711 |
-
"""Return current health; poison discoveries are dangerous until avoided or studied."""
|
| 712 |
if current.get("game_over") == "Yes":
|
| 713 |
return 0
|
| 714 |
-
poison_penalties = sum(
|
|
|
|
|
|
|
| 715 |
return max(0, PLAYER_STARTING_HEALTH - poison_penalties)
|
| 716 |
|
| 717 |
|
| 718 |
def _with_reward_state(current, collection, score_delta):
|
| 719 |
-
"""Attach score, health, and feedback fields to the current mushroom state."""
|
| 720 |
score_total = _score_collection(collection) + score_delta
|
| 721 |
return {
|
| 722 |
**current,
|
|
@@ -728,7 +768,6 @@ def _with_reward_state(current, collection, score_delta):
|
|
| 728 |
|
| 729 |
|
| 730 |
def _reward_text(current, score_delta):
|
| 731 |
-
"""Return video-game-style feedback for the latest mushroom reward."""
|
| 732 |
if score_delta < 0:
|
| 733 |
return f"Poison penalty {score_delta} spores"
|
| 734 |
rarity = current.get("rarity", "Common")
|
|
@@ -741,6 +780,35 @@ def _reward_text(current, score_delta):
|
|
| 741 |
return "No spores scored yet"
|
| 742 |
|
| 743 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 744 |
def _is_poisonous(current):
|
| 745 |
-
"""Return whether the mushroom should trigger a game-over pick."""
|
| 746 |
return current.get("name", "") in POISONOUS_MUSHROOMS or current.get("danger") == "Poisonous"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
import os
|
| 4 |
import random
|
| 5 |
|
|
|
|
|
|
|
| 6 |
from game.catalog import load_mushrooms
|
| 7 |
from game.state import collection_contains, mushroom_from_state, welcome_history
|
| 8 |
|
| 9 |
+
# ---------------------------------------------------------------------------
|
| 10 |
+
# Model configuration
|
| 11 |
+
# ---------------------------------------------------------------------------
|
| 12 |
+
|
| 13 |
+
DEFAULT_MODEL_ID = "openai/gpt-oss-20b"
|
| 14 |
+
|
| 15 |
RARITY_WEIGHTS = {"Common": 64, "Rare": 24, "Legendary": 8}
|
| 16 |
RARITY_SCORE_VALUES = {"Common": 10, "Rare": 35, "Legendary": 100}
|
| 17 |
PLAYER_STARTING_HEALTH = 3
|
| 18 |
POISON_SCORE_PENALTY = -25
|
| 19 |
+
|
| 20 |
MYCO_CHARACTER_SPEC = """
|
| 21 |
# Myco Character Specification
|
| 22 |
|
|
|
|
| 51 |
Design goal:
|
| 52 |
Players should think, "I want to see what happens next" and "I wonder what Myco thinks about this."
|
| 53 |
""".strip()
|
| 54 |
+
|
| 55 |
RARITY_CLUES = {
|
| 56 |
"Common": "The cap leans toward the path, like it wants to be remembered.",
|
| 57 |
"Rare": "Silver spores circle it in a pattern Myco has seen only in old forest stories.",
|
| 58 |
"Legendary": "The whole clearing goes quiet; this mushroom is hiding part of the Elder Map.",
|
| 59 |
}
|
| 60 |
+
|
| 61 |
POISONOUS_MUSHROOMS = {"Ghost Gill", "Pepper Pixie", "Ruby Knuckle", "Clockwork Chanterelle"}
|
| 62 |
+
|
| 63 |
FOREST_EVENTS = (
|
| 64 |
{
|
| 65 |
"title": "Silver Rain",
|
|
|
|
| 90 |
"consequence": "The forest answers only if you stop rushing.",
|
| 91 |
},
|
| 92 |
)
|
| 93 |
+
|
| 94 |
RARE_ENCOUNTERS = (
|
| 95 |
"A lost traveler asks why Myco knows their childhood song.",
|
| 96 |
"A mushroom guardian blocks the trail and counts your clues.",
|
| 97 |
"A tiny forest spirit swaps your shadow with a spore-shadow.",
|
| 98 |
"Something under the roots whispers: Myco has been here before.",
|
| 99 |
)
|
| 100 |
+
|
| 101 |
IMPOSSIBLE_OBJECTIVE = "Find the Impossible Mushroom and learn why Myco remembers a forest that vanished."
|
| 102 |
MYSTERY_QUESTION = "Why does Myco remember places that disappeared before Myco was born?"
|
| 103 |
+
|
| 104 |
MYSTERY_CHAPTERS = (
|
| 105 |
{
|
| 106 |
"threshold": 0,
|
|
|
|
| 134 |
},
|
| 135 |
)
|
| 136 |
|
| 137 |
+
# ---------------------------------------------------------------------------
|
| 138 |
+
# Local pipeline — loaded once, reused for every reply
|
| 139 |
+
# ---------------------------------------------------------------------------
|
| 140 |
+
|
| 141 |
+
_pipeline = None # lazy-loaded on first use
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _get_pipeline():
|
| 145 |
+
"""Load the local transformers pipeline once and cache it."""
|
| 146 |
+
global _pipeline
|
| 147 |
+
if _pipeline is not None:
|
| 148 |
+
return _pipeline
|
| 149 |
+
|
| 150 |
+
try:
|
| 151 |
+
import torch
|
| 152 |
+
from transformers import pipeline
|
| 153 |
+
|
| 154 |
+
model_id = os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)
|
| 155 |
+
_pipeline = pipeline(
|
| 156 |
+
"text-generation",
|
| 157 |
+
model=model_id,
|
| 158 |
+
torch_dtype="auto",
|
| 159 |
+
device_map="auto",
|
| 160 |
+
)
|
| 161 |
+
return _pipeline
|
| 162 |
+
except Exception as exc:
|
| 163 |
+
# If the model cannot be loaded (e.g. not enough VRAM on this machine),
|
| 164 |
+
# log once and keep _pipeline as None so the fallback voice is used.
|
| 165 |
+
print(f"[Myco] Could not load local pipeline: {exc}")
|
| 166 |
+
_pipeline = False # sentinel: we already tried and failed
|
| 167 |
+
return None
|
| 168 |
+
|
| 169 |
+
|
| 170 |
+
def companion_model_id():
|
| 171 |
+
"""Return the model id that will be (or is) loaded."""
|
| 172 |
+
return os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)
|
| 173 |
+
|
| 174 |
+
|
| 175 |
+
def companion_status():
|
| 176 |
+
"""Return a player-safe status line for the companion model."""
|
| 177 |
+
model = companion_model_id()
|
| 178 |
+
pipe = _get_pipeline()
|
| 179 |
+
if pipe:
|
| 180 |
+
return f"🧠 Myco AI: running locally with `{model}`."
|
| 181 |
+
return f"🧠 Myco AI: fallback voice active (could not load `{model}`)."
|
| 182 |
+
|
| 183 |
+
|
| 184 |
+
# Keep the old name so any code that calls hf_companion_status() still works.
|
| 185 |
+
def hf_companion_status():
|
| 186 |
+
return companion_status()
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
# ---------------------------------------------------------------------------
|
| 190 |
+
# Core mushroom-selection helpers
|
| 191 |
+
# ---------------------------------------------------------------------------
|
| 192 |
+
|
| 193 |
|
| 194 |
def choose_mushroom(catalog=None):
|
| 195 |
"""Choose a mushroom discovery from the catalog."""
|
|
|
|
| 220 |
return mushroom, current, history
|
| 221 |
|
| 222 |
|
| 223 |
+
# ---------------------------------------------------------------------------
|
| 224 |
+
# Companion reply
|
| 225 |
+
# ---------------------------------------------------------------------------
|
| 226 |
+
|
| 227 |
+
|
| 228 |
def myco_reply(message=None, history=None, current=None, collection=None, position=None):
|
| 229 |
"""Generate Myco's companion reply from the player's current journey context."""
|
| 230 |
current_history = _safe_history(history)
|
|
|
|
| 239 |
return "", [*next_history, _assistant_message(answer)]
|
| 240 |
|
| 241 |
|
| 242 |
+
companion_reply = myco_reply
|
| 243 |
+
|
| 244 |
+
|
| 245 |
def _companion_answer(message, current, context):
|
| 246 |
+
"""Return the local-model reply, falling back to Myco's deterministic voice."""
|
| 247 |
+
answer = _local_pipeline_answer(message, current, context)
|
| 248 |
if answer is None:
|
| 249 |
+
return _fallback_companion_answer(current, context)
|
| 250 |
return answer
|
| 251 |
|
| 252 |
|
| 253 |
+
def _local_pipeline_answer(message, current, context):
|
| 254 |
+
"""
|
| 255 |
+
Ask the locally loaded transformers pipeline for Myco's reply.
|
| 256 |
+
Returns None if the pipeline is unavailable so the caller can fall back.
|
| 257 |
+
"""
|
| 258 |
+
pipe = _get_pipeline()
|
| 259 |
+
if not pipe:
|
| 260 |
+
return None
|
| 261 |
+
|
| 262 |
+
messages = _build_messages(message, current, context)
|
| 263 |
+
try:
|
| 264 |
+
outputs = pipe(
|
| 265 |
+
messages,
|
| 266 |
+
max_new_tokens=90,
|
| 267 |
+
temperature=0.8,
|
| 268 |
+
do_sample=True,
|
| 269 |
+
)
|
| 270 |
+
# The pipeline returns the full generated_text list; the last entry is
|
| 271 |
+
# the new assistant turn added by the model.
|
| 272 |
+
last = outputs[0]["generated_text"][-1]
|
| 273 |
+
# last is either a dict {"role": "assistant", "content": "..."}
|
| 274 |
+
# or a plain string depending on the transformers version.
|
| 275 |
+
if isinstance(last, dict):
|
| 276 |
+
return (last.get("content") or "").strip() or None
|
| 277 |
+
return str(last).strip() or None
|
| 278 |
+
except Exception as exc:
|
| 279 |
+
print(f"[Myco] Pipeline inference error: {exc}")
|
| 280 |
+
return None
|
| 281 |
+
|
| 282 |
+
|
| 283 |
def _discovery_reaction(current, collection):
|
| 284 |
"""Return Myco's first reaction to a new discovery."""
|
| 285 |
mushroom = mushroom_from_state(current)
|
|
|
|
| 292 |
f"Mystery: {current.get('mystery_title', 'The Wrong Memory')}. "
|
| 293 |
"React as Myco with emotion, make the moment memorable, and invite a meaningful choice."
|
| 294 |
)
|
| 295 |
+
answer = _local_pipeline_answer(prompt, current, context)
|
| 296 |
if answer:
|
| 297 |
return answer
|
| 298 |
|
|
|
|
| 307 |
)
|
| 308 |
|
| 309 |
|
| 310 |
+
def _fallback_companion_answer(current, context):
|
| 311 |
"""Return the deterministic fallback companion answer using game context."""
|
| 312 |
if current:
|
| 313 |
mushroom = mushroom_from_state(current)
|
|
|
|
| 326 |
)
|
| 327 |
|
| 328 |
|
| 329 |
+
def _build_messages(message, current, context):
|
| 330 |
+
"""Build the chat messages list for the local pipeline."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 331 |
mushroom_context = "No mushroom is currently discovered."
|
| 332 |
if current:
|
| 333 |
mushroom = mushroom_from_state(current)
|
|
|
|
| 376 |
]
|
| 377 |
|
| 378 |
|
| 379 |
+
# ---------------------------------------------------------------------------
|
| 380 |
+
# Game actions
|
| 381 |
+
# ---------------------------------------------------------------------------
|
| 382 |
|
| 383 |
|
| 384 |
def collect_current(current=None, collection=None, history=None):
|
|
|
|
| 442 |
)
|
| 443 |
|
| 444 |
score_delta = _score_value(current)
|
| 445 |
+
picked = _with_reward_state(
|
| 446 |
+
{**current, "picked": "Yes", "danger": "No obvious poison"},
|
| 447 |
+
current_collection,
|
| 448 |
+
score_delta,
|
| 449 |
+
)
|
| 450 |
if collection_contains(current_collection, picked["name"]):
|
| 451 |
return current_collection, picked, _append_assistant(
|
| 452 |
current_history,
|
|
|
|
| 540 |
return _append_assistant(current_history, message)
|
| 541 |
|
| 542 |
|
| 543 |
+
# ---------------------------------------------------------------------------
|
| 544 |
+
# Context helpers
|
| 545 |
+
# ---------------------------------------------------------------------------
|
| 546 |
|
| 547 |
|
| 548 |
+
def _companion_context(current, collection, history, position):
|
| 549 |
+
"""Summarize the current journey so Myco replies like a present companion."""
|
| 550 |
+
current_collection = _safe_collection(collection)
|
| 551 |
+
count = len(current_collection)
|
| 552 |
+
rare_names = [
|
| 553 |
+
entry.get("name", "Unknown")
|
| 554 |
+
for entry in current_collection
|
| 555 |
+
if entry.get("rarity") != "Common"
|
| 556 |
+
]
|
| 557 |
+
location = _location_label(position)
|
| 558 |
+
quest = MYSTERY_QUESTION
|
| 559 |
+
if current:
|
| 560 |
+
progress = (
|
| 561 |
+
f"{current.get('mystery_title', 'The Wrong Memory')} — "
|
| 562 |
+
f"{current.get('mystery_next', 'keep exploring')}"
|
| 563 |
+
)
|
| 564 |
+
notable_event = (
|
| 565 |
+
f"{current.get('event_emoji', '✨')} {current.get('event_title', 'Strange Omen')}: "
|
| 566 |
+
f"{current.get('encounter', 'the forest is watching')}"
|
| 567 |
+
)
|
| 568 |
+
emotion = current.get("myco_mood", "curious")
|
| 569 |
+
memory = current.get("memory_fragment") or current.get(
|
| 570 |
+
"mystery_reveal",
|
| 571 |
+
"Myco feels the forest tugging at an old memory.",
|
| 572 |
+
)
|
| 573 |
+
pattern = _pattern_notice(current, current_collection)
|
| 574 |
+
else:
|
| 575 |
+
progress = "No active discovery yet; search a clearing to start the mystery."
|
| 576 |
+
notable_event = "Myco is listening before the first omen."
|
| 577 |
+
emotion = "curious"
|
| 578 |
+
memory = "Myco remembers a path that is not on the map yet."
|
| 579 |
+
pattern = "No pattern yet, but the trees are leaning inward."
|
| 580 |
|
| 581 |
+
return {
|
| 582 |
+
"location": location,
|
| 583 |
+
"quest": quest,
|
| 584 |
+
"progress": progress,
|
| 585 |
+
"rare_finds": ", ".join(rare_names) if rare_names else "none yet",
|
| 586 |
+
"weather": notable_event,
|
| 587 |
+
"notable_event": notable_event,
|
| 588 |
+
"emotion": emotion,
|
| 589 |
+
"memory": memory,
|
| 590 |
+
"pattern": pattern,
|
| 591 |
+
"conversation": _recent_conversation(history),
|
| 592 |
+
"collection_count": str(count),
|
| 593 |
+
}
|
| 594 |
|
| 595 |
+
|
| 596 |
+
def _location_label(position):
|
| 597 |
+
"""Return a small in-world label for the grid position."""
|
| 598 |
+
if position is None:
|
| 599 |
+
return "center clearing"
|
| 600 |
+
x, y = position
|
| 601 |
+
names = {
|
| 602 |
+
(0, 0): "northwest root arch",
|
| 603 |
+
(1, 0): "northern fern gate",
|
| 604 |
+
(2, 0): "northeast moon stump",
|
| 605 |
+
(0, 1): "western moss path",
|
| 606 |
+
(1, 1): "center clearing",
|
| 607 |
+
(2, 1): "eastern glow log",
|
| 608 |
+
(0, 2): "southwest rain hollow",
|
| 609 |
+
(1, 2): "southern spore bridge",
|
| 610 |
+
(2, 2): "southeast elder shade",
|
| 611 |
+
}
|
| 612 |
+
return names.get((int(x), int(y)), "unknown clearing")
|
| 613 |
|
| 614 |
|
| 615 |
+
def _pattern_notice(current, collection):
|
| 616 |
+
"""Return one pattern Myco can comment on from the journey so far."""
|
| 617 |
+
if current.get("game_over") == "Yes":
|
| 618 |
+
return "The same poison warning appeared before Myco could say it aloud."
|
| 619 |
+
if current.get("rarity") == "Legendary":
|
| 620 |
+
return "Legendary spores bend toward the MycoDex instead of the moon."
|
| 621 |
+
if current.get("poison") == "Yes":
|
| 622 |
+
return "Poison omens arrive with black-winged moths and sudden silence."
|
| 623 |
+
if len(collection) >= 3:
|
| 624 |
+
return "Every third clue makes the MycoDex feel warmer, like it is alive."
|
| 625 |
+
if current.get("event_title") == "Moonlit Sporefall":
|
| 626 |
+
return "Moonlit spores keep behaving like memories instead of seeds."
|
| 627 |
+
return "The clues are not random; they keep pointing back to Myco's forgotten path."
|
| 628 |
|
| 629 |
|
| 630 |
+
def _recent_conversation(history):
|
| 631 |
+
"""Return a compact summary of recent player/Myco conversation turns."""
|
| 632 |
+
turns = []
|
| 633 |
+
for entry in _safe_history(history)[-6:]:
|
| 634 |
+
role = entry.get("role", "assistant")
|
| 635 |
+
content = entry.get("content", "").replace("\n", " ").strip()
|
| 636 |
+
if content:
|
| 637 |
+
turns.append(f"{role}: {content[:120]}")
|
| 638 |
+
return " | ".join(turns) if turns else "No conversation yet."
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
# ---------------------------------------------------------------------------
|
| 642 |
+
# Story / mystery helpers
|
| 643 |
+
# ---------------------------------------------------------------------------
|
| 644 |
|
| 645 |
|
| 646 |
def _mystery_clue(current, collection_count):
|
|
|
|
| 647 |
rarity = current.get("rarity", "Common")
|
| 648 |
name = current.get("name", "this mushroom")
|
| 649 |
clue = RARITY_CLUES.get(rarity, RARITY_CLUES["Common"])
|
|
|
|
| 657 |
|
| 658 |
|
| 659 |
def _mystery_thread(collection_count):
|
|
|
|
| 660 |
chapter = MYSTERY_CHAPTERS[0]
|
| 661 |
next_chapter = None
|
| 662 |
for candidate in MYSTERY_CHAPTERS:
|
|
|
|
| 681 |
|
| 682 |
|
| 683 |
def _story_moment(current, collection_count):
|
|
|
|
| 684 |
event = FOREST_EVENTS[collection_count % len(FOREST_EVENTS)]
|
| 685 |
encounter = _encounter_for(current, collection_count)
|
| 686 |
return {
|
|
|
|
| 695 |
|
| 696 |
|
| 697 |
def _encounter_for(current, collection_count):
|
|
|
|
| 698 |
if current.get("rarity") == "Legendary":
|
| 699 |
return "A mushroom guardian bows and calls Myco by an old royal name."
|
| 700 |
if _is_poisonous(current):
|
|
|
|
| 705 |
|
| 706 |
|
| 707 |
def _memory_fragment(current, collection_count, mystery):
|
|
|
|
| 708 |
name = current.get("name", "this mushroom")
|
| 709 |
reveal = mystery.get("mystery_reveal", "The forest remembers Myco.")
|
| 710 |
if mystery.get("mystery_title") == "The Impossible Bloom":
|
|
|
|
| 719 |
|
| 720 |
|
| 721 |
def _secret_signal(current, collection_count):
|
|
|
|
| 722 |
rarity = current.get("rarity", "Common")
|
| 723 |
if rarity == "Legendary":
|
| 724 |
return "The MycoDex page blooms with a star-shaped seal."
|
|
|
|
| 729 |
return "The page smells faintly of rain and moss."
|
| 730 |
|
| 731 |
|
| 732 |
+
# ---------------------------------------------------------------------------
|
| 733 |
+
# Scoring helpers
|
| 734 |
+
# ---------------------------------------------------------------------------
|
| 735 |
+
|
| 736 |
+
|
| 737 |
def _score_value(current):
|
|
|
|
| 738 |
return RARITY_SCORE_VALUES.get(current.get("rarity", "Common"), 10)
|
| 739 |
|
| 740 |
|
| 741 |
def _score_collection(collection):
|
|
|
|
| 742 |
total = 0
|
| 743 |
for entry in _safe_collection(collection):
|
| 744 |
if entry.get("game_over") == "Yes":
|
|
|
|
| 748 |
|
| 749 |
|
| 750 |
def _health_for_state(current, collection):
|
|
|
|
| 751 |
if current.get("game_over") == "Yes":
|
| 752 |
return 0
|
| 753 |
+
poison_penalties = sum(
|
| 754 |
+
1 for entry in _safe_collection(collection) if entry.get("game_over") == "Yes"
|
| 755 |
+
)
|
| 756 |
return max(0, PLAYER_STARTING_HEALTH - poison_penalties)
|
| 757 |
|
| 758 |
|
| 759 |
def _with_reward_state(current, collection, score_delta):
|
|
|
|
| 760 |
score_total = _score_collection(collection) + score_delta
|
| 761 |
return {
|
| 762 |
**current,
|
|
|
|
| 768 |
|
| 769 |
|
| 770 |
def _reward_text(current, score_delta):
|
|
|
|
| 771 |
if score_delta < 0:
|
| 772 |
return f"Poison penalty {score_delta} spores"
|
| 773 |
rarity = current.get("rarity", "Common")
|
|
|
|
| 780 |
return "No spores scored yet"
|
| 781 |
|
| 782 |
|
| 783 |
+
# ---------------------------------------------------------------------------
|
| 784 |
+
# Safety / utility helpers
|
| 785 |
+
# ---------------------------------------------------------------------------
|
| 786 |
+
|
| 787 |
+
|
| 788 |
def _is_poisonous(current):
|
|
|
|
| 789 |
return current.get("name", "") in POISONOUS_MUSHROOMS or current.get("danger") == "Poisonous"
|
| 790 |
+
|
| 791 |
+
|
| 792 |
+
def _study_hint(rarity):
|
| 793 |
+
if rarity == "Legendary":
|
| 794 |
+
return "Strong, mysterious aura"
|
| 795 |
+
if rarity == "Rare":
|
| 796 |
+
return "Faint magical trace"
|
| 797 |
+
return "Tiny spore shimmer"
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
def _assistant_message(content):
|
| 801 |
+
return {"role": "assistant", "content": content}
|
| 802 |
+
|
| 803 |
+
|
| 804 |
+
def _append_assistant(history, content):
|
| 805 |
+
return [*_safe_history(history), _assistant_message(content)]
|
| 806 |
+
|
| 807 |
+
|
| 808 |
+
def _safe_collection(collection):
|
| 809 |
+
return list(collection or [])
|
| 810 |
+
|
| 811 |
+
|
| 812 |
+
def _safe_history(history):
|
| 813 |
+
return list(history or welcome_history())
|
| 814 |
+
|