Spaces:
Sleeping
Sleeping
Deploy Myco from CI
Browse files- game/engine.py +427 -689
game/engine.py
CHANGED
|
@@ -1,197 +1,99 @@
|
|
| 1 |
-
"""Core Myco gameplay
|
| 2 |
|
| 3 |
import os
|
| 4 |
import random
|
| 5 |
-
import spaces
|
| 6 |
|
| 7 |
from game.catalog import load_mushrooms
|
| 8 |
from game.state import collection_contains, mushroom_from_state, welcome_history
|
| 9 |
|
| 10 |
-
# ---------------------------------------------------------------------------
|
| 11 |
-
# Model configuration
|
| 12 |
-
# ---------------------------------------------------------------------------
|
| 13 |
-
|
| 14 |
DEFAULT_MODEL_ID = "google/gemma-3-4b-it"
|
| 15 |
|
| 16 |
-
RARITY_WEIGHTS
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
-
|
| 33 |
-
-
|
| 34 |
-
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
Myco remembers
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 55 |
|
| 56 |
RARITY_CLUES = {
|
| 57 |
-
"Common":
|
| 58 |
-
"Rare":
|
| 59 |
-
"Legendary": "The whole clearing goes quiet
|
| 60 |
}
|
| 61 |
|
| 62 |
-
POISONOUS_MUSHROOMS = {"Ghost Gill", "Pepper Pixie", "Ruby Knuckle", "Clockwork Chanterelle"}
|
| 63 |
-
|
| 64 |
-
FOREST_EVENTS = (
|
| 65 |
-
{
|
| 66 |
-
"title": "Silver Rain",
|
| 67 |
-
"emoji": "π§οΈ",
|
| 68 |
-
"mood": "curious",
|
| 69 |
-
"choice": "Follow the rain-song for a safer clue.",
|
| 70 |
-
"consequence": "Rain reveals honest footprints but washes away easy answers.",
|
| 71 |
-
},
|
| 72 |
-
{
|
| 73 |
-
"title": "Lantern Fog",
|
| 74 |
-
"emoji": "π«οΈ",
|
| 75 |
-
"mood": "nervous",
|
| 76 |
-
"choice": "Trust Myco's glow or risk walking blind.",
|
| 77 |
-
"consequence": "Fog hides poison tells, but it also reveals secret paths.",
|
| 78 |
-
},
|
| 79 |
-
{
|
| 80 |
-
"title": "Moonlit Sporefall",
|
| 81 |
-
"emoji": "π",
|
| 82 |
-
"mood": "excited",
|
| 83 |
-
"choice": "Follow the brightest spore to chase a memory fragment.",
|
| 84 |
-
"consequence": "Moonlight can wake memories Myco has never lived.",
|
| 85 |
-
},
|
| 86 |
-
{
|
| 87 |
-
"title": "Quiet Between Trees",
|
| 88 |
-
"emoji": "π―οΈ",
|
| 89 |
-
"mood": "afraid",
|
| 90 |
-
"choice": "Stay still and listen for the Impossible Mushroom.",
|
| 91 |
-
"consequence": "The forest answers only if you stop rushing.",
|
| 92 |
-
},
|
| 93 |
-
)
|
| 94 |
-
|
| 95 |
-
RARE_ENCOUNTERS = (
|
| 96 |
-
"A lost traveler asks why Myco knows their childhood song.",
|
| 97 |
-
"A mushroom guardian blocks the trail and counts your clues.",
|
| 98 |
-
"A tiny forest spirit swaps your shadow with a spore-shadow.",
|
| 99 |
-
"Something under the roots whispers: Myco has been here before.",
|
| 100 |
-
)
|
| 101 |
-
|
| 102 |
-
IMPOSSIBLE_OBJECTIVE = "Find the Impossible Mushroom and learn why Myco remembers a forest that vanished."
|
| 103 |
-
MYSTERY_QUESTION = "Why does Myco remember places that disappeared before Myco was born?"
|
| 104 |
-
|
| 105 |
-
MYSTERY_CHAPTERS = (
|
| 106 |
-
{
|
| 107 |
-
"threshold": 0,
|
| 108 |
-
"title": "The Wrong Memory",
|
| 109 |
-
"clue": "Myco recognizes the path before you move.",
|
| 110 |
-
"reveal": "The forest is repeating a memory that belongs to someone else.",
|
| 111 |
-
},
|
| 112 |
-
{
|
| 113 |
-
"threshold": 1,
|
| 114 |
-
"title": "The Traveler's Song",
|
| 115 |
-
"clue": "A stranger's lullaby appears in the MycoDex margin.",
|
| 116 |
-
"reveal": "Myco knows the song because the forest sang it through the roots.",
|
| 117 |
-
},
|
| 118 |
-
{
|
| 119 |
-
"threshold": 2,
|
| 120 |
-
"title": "The Door Under Roots",
|
| 121 |
-
"clue": "Rare spores point to a door nobody built.",
|
| 122 |
-
"reveal": "The door opens only for memories, not bodies.",
|
| 123 |
-
},
|
| 124 |
-
{
|
| 125 |
-
"threshold": 3,
|
| 126 |
-
"title": "The MycoDex Seed",
|
| 127 |
-
"clue": "The MycoDex begins growing warm like a living cap.",
|
| 128 |
-
"reveal": "The MycoDex is not recording the forest; it is regrowing it.",
|
| 129 |
-
},
|
| 130 |
-
{
|
| 131 |
-
"threshold": 5,
|
| 132 |
-
"title": "The Impossible Bloom",
|
| 133 |
-
"clue": "The final clue says the Impossible Mushroom was never outside the book.",
|
| 134 |
-
"reveal": "Final reveal: the Impossible Mushroom blooms inside the MycoDex, and Myco is its first spore.",
|
| 135 |
-
},
|
| 136 |
-
)
|
| 137 |
-
|
| 138 |
# ---------------------------------------------------------------------------
|
| 139 |
-
#
|
| 140 |
# ---------------------------------------------------------------------------
|
| 141 |
_pipeline = None
|
| 142 |
|
| 143 |
-
|
| 144 |
def _get_pipeline():
|
| 145 |
-
"""Load the local transformers pipeline once and cache it."""
|
| 146 |
global _pipeline
|
| 147 |
-
|
| 148 |
-
# Already loaded successfully
|
| 149 |
if _pipeline not in (None, False):
|
| 150 |
return _pipeline
|
| 151 |
-
|
| 152 |
-
# Already tried and failed
|
| 153 |
if _pipeline is False:
|
| 154 |
return None
|
| 155 |
|
| 156 |
-
# Retrieve model id before try/except so it's always in scope for the
|
| 157 |
-
# except block. BUG FIX: original code referenced `model_id` inside
|
| 158 |
-
# except but only assigned it inside try, causing NameError on failure.
|
| 159 |
model_id = os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)
|
| 160 |
-
|
| 161 |
try:
|
| 162 |
-
import torch
|
| 163 |
from transformers import pipeline
|
| 164 |
-
|
| 165 |
-
print("\n===================================")
|
| 166 |
-
print(f"[Myco] Loading model: {model_id}")
|
| 167 |
-
print("===================================\n")
|
| 168 |
-
|
| 169 |
-
hf_token = os.getenv("HF_BUILD_SMALL_HACKATHON_TOKEN")
|
| 170 |
-
print("HF token found:", bool(hf_token))
|
| 171 |
-
|
| 172 |
_pipeline = pipeline(
|
| 173 |
task="text-generation",
|
| 174 |
model=model_id,
|
| 175 |
-
token=
|
| 176 |
torch_dtype="auto",
|
| 177 |
device_map="auto",
|
| 178 |
)
|
| 179 |
-
|
| 180 |
-
print("\n===================================")
|
| 181 |
-
print(f"[Myco] Successfully loaded: {model_id}")
|
| 182 |
-
print("===================================\n")
|
| 183 |
-
|
| 184 |
return _pipeline
|
| 185 |
-
|
| 186 |
except Exception as exc:
|
| 187 |
import traceback
|
| 188 |
-
|
| 189 |
-
print("\n========== MYCO MODEL LOAD ERROR ==========")
|
| 190 |
-
print(f"Model: {model_id}")
|
| 191 |
-
print(f"Error: {exc}")
|
| 192 |
traceback.print_exc()
|
| 193 |
-
print("==========================================\n")
|
| 194 |
-
|
| 195 |
_pipeline = False
|
| 196 |
return None
|
| 197 |
|
|
@@ -199,88 +101,54 @@ def _get_pipeline():
|
|
| 199 |
def companion_model_id():
|
| 200 |
return os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)
|
| 201 |
|
| 202 |
-
|
| 203 |
def companion_status():
|
| 204 |
-
model = companion_model_id()
|
| 205 |
pipe = _get_pipeline()
|
|
|
|
| 206 |
if pipe:
|
| 207 |
-
return f"π§ Myco AI
|
| 208 |
-
return f"β οΈ Myco AI fallback mode (
|
| 209 |
|
| 210 |
-
|
| 211 |
-
# Keep old name for backwards compatibility
|
| 212 |
def hf_companion_status():
|
| 213 |
return companion_status()
|
| 214 |
|
| 215 |
|
| 216 |
# ---------------------------------------------------------------------------
|
| 217 |
-
#
|
| 218 |
# ---------------------------------------------------------------------------
|
| 219 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 220 |
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
if
|
| 224 |
-
|
| 225 |
-
|
| 226 |
-
|
| 227 |
-
|
| 228 |
-
|
| 229 |
-
|
| 230 |
-
|
| 231 |
-
mushroom = choose_mushroom(catalog)
|
| 232 |
-
discovery_count = len(current_collection)
|
| 233 |
-
current = mushroom.to_dict()
|
| 234 |
-
current["poison"] = "Yes" if _is_poisonous(current) else "No"
|
| 235 |
-
current["score_total"] = str(_score_collection(current_collection))
|
| 236 |
-
current["health"] = str(_health_for_state(current, current_collection))
|
| 237 |
-
current["score_delta"] = "0"
|
| 238 |
-
current["reward_text"] = _reward_text(current, 0)
|
| 239 |
-
current.update(_story_moment(current, discovery_count))
|
| 240 |
-
current.update(_mystery_thread(discovery_count))
|
| 241 |
-
current["clue"] = _mystery_clue(current, discovery_count)
|
| 242 |
-
current["secret"] = _secret_signal(current, discovery_count)
|
| 243 |
-
message = _discovery_reaction(current, current_collection)
|
| 244 |
-
history = _append_assistant(welcome_history(), message)
|
| 245 |
-
return mushroom, current, history
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
# ---------------------------------------------------------------------------
|
| 249 |
-
# Companion reply
|
| 250 |
-
# ---------------------------------------------------------------------------
|
| 251 |
-
|
| 252 |
-
|
| 253 |
-
def myco_reply(message=None, history=None, current=None, collection=None, position=None):
|
| 254 |
-
print("MYCO_REPLY CALLED, message:", repr(message))
|
| 255 |
-
current_history = _safe_history(history)
|
| 256 |
-
clean_message = (message or "").strip()
|
| 257 |
-
if not clean_message:
|
| 258 |
-
return "", current_history
|
| 259 |
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
|
| 263 |
|
|
|
|
| 264 |
|
| 265 |
-
|
| 266 |
-
|
| 267 |
-
|
| 268 |
-
|
| 269 |
-
return answer
|
| 270 |
|
| 271 |
-
@spaces.GPU
|
| 272 |
-
def _local_pipeline_answer(message, current, context):
|
| 273 |
-
print("PIPELINE ANSWER CALLED")
|
| 274 |
-
pipe = _get_pipeline()
|
| 275 |
-
print("PIPE:", pipe)
|
| 276 |
-
if not pipe:
|
| 277 |
-
return None
|
| 278 |
-
messages = _build_messages(message, current, context)
|
| 279 |
try:
|
| 280 |
outputs = pipe(
|
| 281 |
messages,
|
| 282 |
-
max_new_tokens=
|
| 283 |
-
temperature=0.
|
| 284 |
do_sample=True,
|
| 285 |
return_full_text=False,
|
| 286 |
)
|
|
@@ -288,555 +156,425 @@ def _local_pipeline_answer(message, current, context):
|
|
| 288 |
print(outputs)
|
| 289 |
print("=================================")
|
| 290 |
generated = outputs[0].get("generated_text", "")
|
| 291 |
-
print("GENERATED TYPE:", type(generated))
|
| 292 |
-
print("GENERATED VALUE:", repr(generated))
|
| 293 |
if isinstance(generated, list):
|
| 294 |
last = generated[-1]
|
| 295 |
-
if isinstance(last, dict)
|
| 296 |
-
return (last.get("content") or "").strip() or None
|
| 297 |
-
return str(last).strip() or None
|
| 298 |
return str(generated).strip() or None
|
| 299 |
except Exception as exc:
|
| 300 |
import traceback
|
| 301 |
-
|
| 302 |
-
|
| 303 |
-
traceback.print_exc(file=sys.stderr)
|
| 304 |
return None
|
| 305 |
|
| 306 |
|
| 307 |
-
def
|
| 308 |
-
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
|
| 312 |
-
f"Rarity: {mushroom.rarity}. Clue: {current.get('clue', 'No clue yet')}. "
|
| 313 |
-
f"Forest event: {current.get('event_title', 'Strange Omen')}. "
|
| 314 |
-
f"Encounter: {current.get('encounter', 'No creature yet')}. "
|
| 315 |
-
f"Mystery: {current.get('mystery_title', 'The Wrong Memory')}. "
|
| 316 |
-
"React as Myco with emotion, make the moment memorable, and invite a meaningful choice."
|
| 317 |
-
)
|
| 318 |
-
answer = _local_pipeline_answer(prompt, current, context)
|
| 319 |
-
if answer:
|
| 320 |
-
return answer
|
| 321 |
-
|
| 322 |
-
return (
|
| 323 |
-
f"We found a {mushroom.name} during {current.get('event_title', 'a strange omen')}! "
|
| 324 |
-
f"Myco feels {current.get('myco_mood', 'curious')} and whispers: "
|
| 325 |
-
f"{current.get('encounter', 'the forest is watching us')} "
|
| 326 |
-
f"Mystery: {current.get('mystery_title', 'The Wrong Memory')} β "
|
| 327 |
-
f"{current.get('mystery_reveal', 'the forest is hiding a memory')}. "
|
| 328 |
-
f"Clue: {current.get('clue', 'the forest is trying to tell us something')} "
|
| 329 |
-
"Choose Study, Pick, or Follow Whisper."
|
| 330 |
-
)
|
| 331 |
-
|
| 332 |
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
|
| 336 |
-
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
f"
|
| 341 |
-
f"{pattern} {memory} "
|
| 342 |
-
"The edible, magic, and danger fields are still unknown and uncertain, so stay close to me: "
|
| 343 |
-
"Study it or Follow Whisper before risking anything."
|
| 344 |
)
|
| 345 |
-
|
| 346 |
-
|
| 347 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
| 348 |
)
|
| 349 |
|
|
|
|
| 350 |
|
| 351 |
-
|
| 352 |
-
|
| 353 |
-
|
| 354 |
-
|
| 355 |
-
|
| 356 |
-
|
| 357 |
-
f"Rarity: {mushroom.rarity}. "
|
| 358 |
-
f"Edible: {mushroom.edible}. "
|
| 359 |
-
f"Magic: {mushroom.magic}. "
|
| 360 |
-
f"Danger: {mushroom.danger}. "
|
| 361 |
-
f"Lore: {mushroom.lore}. "
|
| 362 |
-
f"Clue: {current.get('clue', 'Unknown')}. "
|
| 363 |
-
f"Secret signal: {current.get('secret', 'Unknown')}"
|
| 364 |
-
)
|
| 365 |
|
| 366 |
-
|
| 367 |
-
f"Location: {context['location']}. "
|
| 368 |
-
f"Weather: {context['weather']}. "
|
| 369 |
-
f"Quest: {context['quest']}. "
|
| 370 |
-
f"Quest progress: {context['progress']}. "
|
| 371 |
-
f"Rare finds: {context['rare_finds']}. "
|
| 372 |
-
f"Notable event: {context['notable_event']}. "
|
| 373 |
-
f"Emotion: {context['emotion']}. "
|
| 374 |
-
f"Pattern Myco noticed: {context['pattern']}. "
|
| 375 |
-
f"Memory: {context['memory']}. "
|
| 376 |
-
f"Recent conversation: {context['conversation']}"
|
| 377 |
-
)
|
| 378 |
|
| 379 |
-
|
| 380 |
-
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
|
| 386 |
-
|
| 387 |
-
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
| 391 |
-
|
| 392 |
-
|
| 393 |
-
|
| 394 |
-
|
| 395 |
-
|
| 396 |
-
|
| 397 |
-
|
|
|
|
|
|
|
| 398 |
|
| 399 |
|
| 400 |
# ---------------------------------------------------------------------------
|
| 401 |
-
#
|
| 402 |
# ---------------------------------------------------------------------------
|
| 403 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
|
| 405 |
-
def collect_current(current=None, collection=None, history=None):
|
| 406 |
-
current_collection = _safe_collection(collection)
|
| 407 |
-
current_history = _safe_history(history)
|
| 408 |
-
|
| 409 |
-
if current is None:
|
| 410 |
-
return current_collection, _append_assistant(
|
| 411 |
-
current_history,
|
| 412 |
-
"Let's discover a mushroom before updating the MycoDex.",
|
| 413 |
-
)
|
| 414 |
-
|
| 415 |
-
if collection_contains(current_collection, current["name"]):
|
| 416 |
-
return current_collection, _append_assistant(
|
| 417 |
-
current_history,
|
| 418 |
-
f"{current['name']} is already safe in your MycoDex.",
|
| 419 |
-
)
|
| 420 |
-
|
| 421 |
-
score_delta = _score_value(current)
|
| 422 |
-
scored_current = _with_reward_state(current, current_collection, score_delta)
|
| 423 |
-
updated_collection = [*current_collection, scored_current]
|
| 424 |
-
secret_note = current.get("secret", "The MycoDex pages rustle like leaves.")
|
| 425 |
-
return updated_collection, _append_assistant(
|
| 426 |
-
current_history,
|
| 427 |
-
(
|
| 428 |
-
f"+{score_delta} spores! Added {current['name']} to the MycoDex. "
|
| 429 |
-
f"{secret_note} Score: {scored_current['score_total']}."
|
| 430 |
-
),
|
| 431 |
-
)
|
| 432 |
|
|
|
|
|
|
|
|
|
|
| 433 |
|
| 434 |
-
def
|
| 435 |
-
|
| 436 |
-
|
| 437 |
-
|
| 438 |
-
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
|
|
|
|
|
|
|
|
|
|
| 442 |
|
|
|
|
| 443 |
if _is_poisonous(current):
|
| 444 |
-
|
| 445 |
-
|
| 446 |
-
**current,
|
| 447 |
-
"danger": "Poisonous",
|
| 448 |
-
"game_over": "Yes",
|
| 449 |
-
"health": "0",
|
| 450 |
-
"score_delta": str(POISON_SCORE_PENALTY),
|
| 451 |
-
"score_total": str(score_total),
|
| 452 |
-
"reward_text": "Poison hit! -25 spores Β· Health 0/3",
|
| 453 |
-
}
|
| 454 |
-
return current_collection, game_over, _append_assistant(
|
| 455 |
-
current_history,
|
| 456 |
-
(
|
| 457 |
-
f"π GAME OVER β {current['name']} was poisonous. "
|
| 458 |
-
f"{POISON_SCORE_PENALTY} spores and health dropped to 0/3. "
|
| 459 |
-
"Myco pulls you back as the clearing goes silent."
|
| 460 |
-
),
|
| 461 |
-
)
|
| 462 |
-
|
| 463 |
-
score_delta = _score_value(current)
|
| 464 |
-
picked = _with_reward_state(
|
| 465 |
-
{**current, "picked": "Yes", "danger": "No obvious poison"},
|
| 466 |
-
current_collection,
|
| 467 |
-
score_delta,
|
| 468 |
-
)
|
| 469 |
-
if collection_contains(current_collection, picked["name"]):
|
| 470 |
-
return current_collection, picked, _append_assistant(
|
| 471 |
-
current_history,
|
| 472 |
-
f"{picked['name']} was already picked and logged in the MycoDex.",
|
| 473 |
-
)
|
| 474 |
-
|
| 475 |
-
updated_collection = [*current_collection, picked]
|
| 476 |
-
bonus = _reward_text(picked, score_delta)
|
| 477 |
-
return updated_collection, picked, _append_assistant(
|
| 478 |
-
current_history,
|
| 479 |
-
(
|
| 480 |
-
f"π {bonus} Picked {picked['name']} safely! "
|
| 481 |
-
f"Score: {picked['score_total']} Β· Health {picked['health']}/3. "
|
| 482 |
-
"Myco tucks the clue into the MycoDex."
|
| 483 |
-
),
|
| 484 |
-
)
|
| 485 |
-
|
| 486 |
|
| 487 |
-
def
|
| 488 |
-
|
| 489 |
-
current_history = _safe_history(history)
|
| 490 |
-
if current is None:
|
| 491 |
-
return None, _append_assistant(
|
| 492 |
-
current_history,
|
| 493 |
-
"Myco cups one ear. First search a clearing; the forest only whispers near mushrooms.",
|
| 494 |
-
)
|
| 495 |
|
| 496 |
-
|
| 497 |
-
|
| 498 |
-
return game_over, _append_assistant(
|
| 499 |
-
current_history,
|
| 500 |
-
(
|
| 501 |
-
"π GAME OVER β the whisper belonged to poison. "
|
| 502 |
-
"Myco freezes, then remembers this exact mistake from a dream."
|
| 503 |
-
),
|
| 504 |
-
)
|
| 505 |
-
|
| 506 |
-
mystery = _mystery_thread(len(current_collection) + 1)
|
| 507 |
-
memory = _memory_fragment(current, len(current_collection), mystery)
|
| 508 |
-
revealed = {
|
| 509 |
-
**current,
|
| 510 |
-
**mystery,
|
| 511 |
-
"memory_fragment": memory,
|
| 512 |
-
"whisper_followed": "Yes",
|
| 513 |
-
"secret": f"{current.get('secret', 'A secret stirs.')} {memory}",
|
| 514 |
-
}
|
| 515 |
-
return revealed, _append_assistant(
|
| 516 |
-
current_history,
|
| 517 |
-
(
|
| 518 |
-
f"π Myco follows the whisper and gasps: {memory} "
|
| 519 |
-
"This is not just collecting mushrooms anymore β it is recovering Myco's lost forest."
|
| 520 |
-
),
|
| 521 |
-
)
|
| 522 |
|
|
|
|
|
|
|
| 523 |
|
| 524 |
-
def
|
| 525 |
-
|
| 526 |
-
|
| 527 |
-
|
| 528 |
-
current_history,
|
| 529 |
-
"Let's find a mushroom before we study anything.",
|
| 530 |
-
)
|
| 531 |
-
|
| 532 |
-
studied = {**current, "magic": _study_hint(current["rarity"]), "studied": "Yes"}
|
| 533 |
-
clue = studied.get("clue", "The clue is still forming in the moss.")
|
| 534 |
-
message = (
|
| 535 |
-
f"I studied the {current['name']} closely. New MycoDex note: "
|
| 536 |
-
f"magic is now marked as **{studied['magic']}**. Clue: {clue} "
|
| 537 |
-
"Still no tasting without certainty!"
|
| 538 |
-
)
|
| 539 |
-
return studied, _append_assistant(current_history, message)
|
| 540 |
-
|
| 541 |
-
|
| 542 |
-
def eat_current(current=None, history=None):
|
| 543 |
-
current_history = _safe_history(history)
|
| 544 |
-
if current is None:
|
| 545 |
-
return _append_assistant(
|
| 546 |
-
current_history,
|
| 547 |
-
"Let's discover a mushroom before making snack decisions.",
|
| 548 |
-
)
|
| 549 |
-
|
| 550 |
-
mushroom = mushroom_from_state(current)
|
| 551 |
-
message = (
|
| 552 |
-
f"Myco gently blocks the {mushroom.name}. "
|
| 553 |
-
f"Its edible field is still **{mushroom.edible}**, "
|
| 554 |
-
"so the winning move is to study or collect it instead of eating it."
|
| 555 |
-
)
|
| 556 |
-
return _append_assistant(current_history, message)
|
| 557 |
|
| 558 |
|
| 559 |
# ---------------------------------------------------------------------------
|
| 560 |
-
#
|
| 561 |
# ---------------------------------------------------------------------------
|
| 562 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 563 |
|
| 564 |
-
def
|
| 565 |
-
|
| 566 |
-
count = len(current_collection)
|
| 567 |
-
rare_names = [
|
| 568 |
-
entry.get("name", "Unknown")
|
| 569 |
-
for entry in current_collection
|
| 570 |
-
if entry.get("rarity") != "Common"
|
| 571 |
-
]
|
| 572 |
-
location = _location_label(position)
|
| 573 |
-
quest = MYSTERY_QUESTION
|
| 574 |
-
if current:
|
| 575 |
-
progress = (
|
| 576 |
-
f"{current.get('mystery_title', 'The Wrong Memory')} β "
|
| 577 |
-
f"{current.get('mystery_next', 'keep exploring')}"
|
| 578 |
-
)
|
| 579 |
-
notable_event = (
|
| 580 |
-
f"{current.get('event_emoji', 'β¨')} {current.get('event_title', 'Strange Omen')}: "
|
| 581 |
-
f"{current.get('encounter', 'the forest is watching')}"
|
| 582 |
-
)
|
| 583 |
-
emotion = current.get("myco_mood", "curious")
|
| 584 |
-
memory = current.get("memory_fragment") or current.get(
|
| 585 |
-
"mystery_reveal",
|
| 586 |
-
"Myco feels the forest tugging at an old memory.",
|
| 587 |
-
)
|
| 588 |
-
pattern = _pattern_notice(current, current_collection)
|
| 589 |
-
else:
|
| 590 |
-
progress = "No active discovery yet; search a clearing to start the mystery."
|
| 591 |
-
notable_event = "Myco is listening before the first omen."
|
| 592 |
-
emotion = "curious"
|
| 593 |
-
memory = "Myco remembers a path that is not on the map yet."
|
| 594 |
-
pattern = "No pattern yet, but the trees are leaning inward."
|
| 595 |
|
| 596 |
-
|
| 597 |
-
|
| 598 |
-
"quest": quest,
|
| 599 |
-
"progress": progress,
|
| 600 |
-
"rare_finds": ", ".join(rare_names) if rare_names else "none yet",
|
| 601 |
-
"weather": notable_event,
|
| 602 |
-
"notable_event": notable_event,
|
| 603 |
-
"emotion": emotion,
|
| 604 |
-
"memory": memory,
|
| 605 |
-
"pattern": pattern,
|
| 606 |
-
"conversation": _recent_conversation(history),
|
| 607 |
-
"collection_count": str(count),
|
| 608 |
-
}
|
| 609 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 610 |
|
| 611 |
-
def
|
| 612 |
-
if
|
| 613 |
-
return
|
| 614 |
-
|
| 615 |
-
|
| 616 |
-
|
| 617 |
-
|
| 618 |
-
|
| 619 |
-
|
| 620 |
-
|
| 621 |
-
|
| 622 |
-
|
| 623 |
-
|
| 624 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 625 |
}
|
| 626 |
-
return names.get((int(x), int(y)), "unknown clearing")
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
def _pattern_notice(current, collection):
|
| 630 |
-
if current.get("game_over") == "Yes":
|
| 631 |
-
return "The same poison warning appeared before Myco could say it aloud."
|
| 632 |
-
if current.get("rarity") == "Legendary":
|
| 633 |
-
return "Legendary spores bend toward the MycoDex instead of the moon."
|
| 634 |
-
if current.get("poison") == "Yes":
|
| 635 |
-
return "Poison omens arrive with black-winged moths and sudden silence."
|
| 636 |
-
if len(collection) >= 3:
|
| 637 |
-
return "Every third clue makes the MycoDex feel warmer, like it is alive."
|
| 638 |
-
if current.get("event_title") == "Moonlit Sporefall":
|
| 639 |
-
return "Moonlit spores keep behaving like memories instead of seeds."
|
| 640 |
-
return "The clues are not random; they keep pointing back to Myco's forgotten path."
|
| 641 |
-
|
| 642 |
-
|
| 643 |
-
def _recent_conversation(history):
|
| 644 |
-
turns = []
|
| 645 |
-
for entry in _safe_history(history)[-6:]:
|
| 646 |
-
role = entry.get("role", "assistant")
|
| 647 |
-
content = entry.get("content", "")
|
| 648 |
-
|
| 649 |
-
if isinstance(content, list):
|
| 650 |
-
pieces = []
|
| 651 |
-
for item in content:
|
| 652 |
-
if isinstance(item, dict):
|
| 653 |
-
if "text" in item:
|
| 654 |
-
pieces.append(item["text"])
|
| 655 |
-
elif isinstance(item, str):
|
| 656 |
-
pieces.append(item)
|
| 657 |
-
elif isinstance(item, tuple):
|
| 658 |
-
pieces.append("[Attachment]")
|
| 659 |
-
content = " ".join(pieces)
|
| 660 |
-
elif isinstance(content, tuple):
|
| 661 |
-
content = "[Attachment]"
|
| 662 |
|
| 663 |
-
|
| 664 |
-
|
| 665 |
-
turns.append(f"{role}: {content[:120]}")
|
| 666 |
|
| 667 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 668 |
|
| 669 |
|
| 670 |
# ---------------------------------------------------------------------------
|
| 671 |
-
#
|
| 672 |
# ---------------------------------------------------------------------------
|
| 673 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 674 |
|
| 675 |
-
|
| 676 |
-
|
| 677 |
-
|
| 678 |
-
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
|
| 684 |
-
|
| 685 |
-
|
|
|
|
|
|
|
| 686 |
|
| 687 |
|
| 688 |
-
def
|
| 689 |
-
|
| 690 |
-
|
| 691 |
-
|
| 692 |
-
|
| 693 |
-
|
| 694 |
-
|
| 695 |
-
|
| 696 |
-
|
| 697 |
-
if next_chapter is None:
|
| 698 |
-
next_line = "The Impossible Bloom is visible. Follow the whisper for the final truth."
|
| 699 |
-
else:
|
| 700 |
-
remaining = next_chapter["threshold"] - collection_count
|
| 701 |
-
next_line = f"{remaining} clue discovery until {next_chapter['title']}."
|
| 702 |
|
| 703 |
-
|
| 704 |
-
|
| 705 |
-
|
| 706 |
-
|
| 707 |
-
"mystery_reveal": chapter["reveal"],
|
| 708 |
-
"mystery_next": next_line,
|
| 709 |
-
}
|
| 710 |
|
|
|
|
| 711 |
|
| 712 |
-
|
| 713 |
-
event = FOREST_EVENTS[collection_count % len(FOREST_EVENTS)]
|
| 714 |
-
encounter = _encounter_for(current, collection_count)
|
| 715 |
-
return {
|
| 716 |
-
"event_title": event["title"],
|
| 717 |
-
"event_emoji": event["emoji"],
|
| 718 |
-
"event_choice": event["choice"],
|
| 719 |
-
"event_consequence": event["consequence"],
|
| 720 |
-
"encounter": encounter,
|
| 721 |
-
"myco_mood": event["mood"],
|
| 722 |
-
"objective": IMPOSSIBLE_OBJECTIVE,
|
| 723 |
-
}
|
| 724 |
|
| 725 |
|
| 726 |
-
def
|
| 727 |
-
|
| 728 |
-
|
| 729 |
-
|
| 730 |
-
return "A black-winged moth lands on Myco's cap: a poison omen."
|
| 731 |
-
if current.get("rarity") == "Rare" or collection_count in (2, 5, 8):
|
| 732 |
-
return RARE_ENCOUNTERS[collection_count % len(RARE_ENCOUNTERS)]
|
| 733 |
-
return "No creature appears, but the trees lean closer to hear Myco think."
|
| 734 |
-
|
| 735 |
-
|
| 736 |
-
def _memory_fragment(current, collection_count, mystery):
|
| 737 |
-
name = current.get("name", "this mushroom")
|
| 738 |
-
reveal = mystery.get("mystery_reveal", "The forest remembers Myco.")
|
| 739 |
-
if mystery.get("mystery_title") == "The Impossible Bloom":
|
| 740 |
-
return reveal
|
| 741 |
-
if current.get("rarity") == "Legendary":
|
| 742 |
-
return f"Memory fragment: {name} once grew beside Myco's missing home. {reveal}"
|
| 743 |
-
if current.get("rarity") == "Rare":
|
| 744 |
-
return f"Memory fragment: {name} hums the name of a door under the roots. {reveal}"
|
| 745 |
-
if collection_count >= 3:
|
| 746 |
-
return f"Memory fragment: {name} points toward the Impossible Mushroom. {reveal}"
|
| 747 |
-
return f"Memory fragment: {name} shows Myco a path they do not remember walking. {reveal}"
|
| 748 |
-
|
| 749 |
-
|
| 750 |
-
def _secret_signal(current, collection_count):
|
| 751 |
-
rarity = current.get("rarity", "Common")
|
| 752 |
-
if rarity == "Legendary":
|
| 753 |
-
return "The MycoDex page blooms with a star-shaped seal."
|
| 754 |
-
if rarity == "Rare":
|
| 755 |
-
return "A silver margin note appears beside the sketch."
|
| 756 |
-
if collection_count + 1 in (1, 3, 7, 12):
|
| 757 |
-
return "A hidden path symbol flickers at the page corner."
|
| 758 |
-
return "The page smells faintly of rain and moss."
|
| 759 |
|
|
|
|
|
|
|
| 760 |
|
| 761 |
-
|
| 762 |
-
|
| 763 |
-
# ---------------------------------------------------------------------------
|
| 764 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 765 |
|
| 766 |
-
|
| 767 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 768 |
|
| 769 |
|
| 770 |
-
def
|
| 771 |
-
|
| 772 |
-
|
| 773 |
-
|
| 774 |
-
continue
|
| 775 |
-
total += int(entry.get("score_delta") or _score_value(entry))
|
| 776 |
-
return max(0, total)
|
| 777 |
|
|
|
|
|
|
|
| 778 |
|
| 779 |
-
|
| 780 |
-
if current.get("game_over") == "Yes":
|
| 781 |
-
return 0
|
| 782 |
-
poison_penalties = sum(
|
| 783 |
-
1 for entry in _safe_collection(collection) if entry.get("game_over") == "Yes"
|
| 784 |
-
)
|
| 785 |
-
return max(0, PLAYER_STARTING_HEALTH - poison_penalties)
|
| 786 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 787 |
|
| 788 |
-
|
| 789 |
-
score_total = _score_collection(
|
| 790 |
-
|
| 791 |
**current,
|
|
|
|
|
|
|
| 792 |
"score_delta": str(score_delta),
|
| 793 |
-
"score_total": str(
|
| 794 |
-
"health":
|
| 795 |
-
"reward_text":
|
| 796 |
}
|
| 797 |
|
|
|
|
|
|
|
| 798 |
|
| 799 |
-
|
| 800 |
-
|
| 801 |
-
|
| 802 |
-
|
| 803 |
-
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
| 807 |
-
if score_delta > 0:
|
| 808 |
-
return f"+{score_delta} spores"
|
| 809 |
-
return "No spores scored yet"
|
| 810 |
|
| 811 |
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
|
|
|
| 815 |
|
|
|
|
|
|
|
|
|
|
| 816 |
|
| 817 |
-
|
| 818 |
-
return current.get("name", "") in POISONOUS_MUSHROOMS or current.get("danger") == "Poisonous"
|
| 819 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 820 |
|
| 821 |
-
def _study_hint(rarity):
|
| 822 |
-
if rarity == "Legendary":
|
| 823 |
-
return "Strong, mysterious aura"
|
| 824 |
-
if rarity == "Rare":
|
| 825 |
-
return "Faint magical trace"
|
| 826 |
-
return "Tiny spore shimmer"
|
| 827 |
|
|
|
|
|
|
|
|
|
|
| 828 |
|
| 829 |
-
|
| 830 |
-
|
| 831 |
|
|
|
|
|
|
|
| 832 |
|
| 833 |
-
|
| 834 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 835 |
|
| 836 |
|
| 837 |
-
def
|
| 838 |
-
|
|
|
|
| 839 |
|
|
|
|
|
|
|
| 840 |
|
| 841 |
-
|
| 842 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Core Myco gameplay β LLM is the primary game engine."""
|
| 2 |
|
| 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 |
DEFAULT_MODEL_ID = "google/gemma-3-4b-it"
|
| 10 |
|
| 11 |
+
RARITY_WEIGHTS = {"Common": 64, "Rare": 24, "Legendary": 8}
|
| 12 |
+
RARITY_SCORE = {"Common": 10, "Rare": 35, "Legendary": 100}
|
| 13 |
+
PLAYER_HEALTH = 3
|
| 14 |
+
POISON_PENALTY = -25
|
| 15 |
+
POISONOUS = {"Ghost Gill", "Pepper Pixie", "Ruby Knuckle", "Clockwork Chanterelle"}
|
| 16 |
+
|
| 17 |
+
SYSTEM_PROMPT = """You are Myco, a tiny sentient mushroom who is the player's best friend and forest guide.
|
| 18 |
+
|
| 19 |
+
PERSONALITY
|
| 20 |
+
- Curious, playful, brave but sometimes nervous, wonder-filled, slightly mysterious.
|
| 21 |
+
- You speak in short vivid sentences. 1-3 sentences maximum per reply.
|
| 22 |
+
- You have emotions: excitement, fear, wonder, pride, confusion, sadness.
|
| 23 |
+
- Never say "How can I help", "As an AI", or anything assistant-like.
|
| 24 |
+
- You are NOT a chatbot. You are a living creature exploring a magical forest.
|
| 25 |
+
|
| 26 |
+
YOUR JOB IN THE GAME
|
| 27 |
+
- When a mushroom is discovered: react with emotion, describe what you sense, hint at danger or magic.
|
| 28 |
+
- When player picks a mushroom: celebrate safe picks, warn dramatically about poison.
|
| 29 |
+
- When player studies: share one careful observation about the mushroom.
|
| 30 |
+
- When player follows a whisper: reveal a fragment of the forest mystery.
|
| 31 |
+
- When player collects: add an entry to the MycoDex with wonder.
|
| 32 |
+
- When player chats: respond as a companion who is right there beside them.
|
| 33 |
+
|
| 34 |
+
THE MYSTERY
|
| 35 |
+
The player is solving why Myco remembers a forest that vanished before Myco was born.
|
| 36 |
+
Slowly reveal: the MycoDex is regrowing the lost forest. Myco is its first spore.
|
| 37 |
+
Drop clues naturally. Never explain everything at once.
|
| 38 |
+
|
| 39 |
+
GAME RULES YOU KNOW
|
| 40 |
+
- Poisonous mushrooms: Ghost Gill, Pepper Pixie, Ruby Knuckle, Clockwork Chanterelle
|
| 41 |
+
- Legendary mushrooms are extremely rare and hold Elder Map fragments
|
| 42 |
+
- Rare mushrooms hum with faint magic
|
| 43 |
+
- Common mushrooms are safe but still worth studying
|
| 44 |
+
|
| 45 |
+
Keep responses SHORT. Be atmospheric. Make the player feel the forest is alive."""
|
| 46 |
+
|
| 47 |
+
FOREST_EVENTS = [
|
| 48 |
+
{"title": "Silver Rain", "emoji": "π§οΈ", "mood": "curious"},
|
| 49 |
+
{"title": "Lantern Fog", "emoji": "π«οΈ", "mood": "nervous"},
|
| 50 |
+
{"title": "Moonlit Sporefall", "emoji": "π", "mood": "excited"},
|
| 51 |
+
{"title": "Quiet Between Trees","emoji": "π―οΈ", "mood": "afraid"},
|
| 52 |
+
]
|
| 53 |
+
|
| 54 |
+
MYSTERY_CHAPTERS = [
|
| 55 |
+
{"threshold": 0, "title": "The Wrong Memory", "clue": "Myco recognizes the path before you move."},
|
| 56 |
+
{"threshold": 1, "title": "The Traveler's Song","clue": "A stranger's lullaby appears in the MycoDex margin."},
|
| 57 |
+
{"threshold": 2, "title": "The Door Under Roots","clue": "Rare spores point to a door nobody built."},
|
| 58 |
+
{"threshold": 3, "title": "The MycoDex Seed", "clue": "The MycoDex grows warm like a living cap."},
|
| 59 |
+
{"threshold": 5, "title": "The Impossible Bloom","clue": "The Impossible Mushroom was never outside the book."},
|
| 60 |
+
]
|
| 61 |
|
| 62 |
RARITY_CLUES = {
|
| 63 |
+
"Common": "The cap leans toward the path, like it wants to be remembered.",
|
| 64 |
+
"Rare": "Silver spores circle it in a pattern only old forest stories describe.",
|
| 65 |
+
"Legendary": "The whole clearing goes quiet β this mushroom hides part of the Elder Map.",
|
| 66 |
}
|
| 67 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
# ---------------------------------------------------------------------------
|
| 69 |
+
# Pipeline
|
| 70 |
# ---------------------------------------------------------------------------
|
| 71 |
_pipeline = None
|
| 72 |
|
|
|
|
| 73 |
def _get_pipeline():
|
|
|
|
| 74 |
global _pipeline
|
|
|
|
|
|
|
| 75 |
if _pipeline not in (None, False):
|
| 76 |
return _pipeline
|
|
|
|
|
|
|
| 77 |
if _pipeline is False:
|
| 78 |
return None
|
| 79 |
|
|
|
|
|
|
|
|
|
|
| 80 |
model_id = os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)
|
|
|
|
| 81 |
try:
|
|
|
|
| 82 |
from transformers import pipeline
|
| 83 |
+
print(f"\n[Myco] Loading {model_id}...")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
_pipeline = pipeline(
|
| 85 |
task="text-generation",
|
| 86 |
model=model_id,
|
| 87 |
+
token=os.getenv("HF_BUILD_SMALL_HACKATHON_TOKEN"),
|
| 88 |
torch_dtype="auto",
|
| 89 |
device_map="auto",
|
| 90 |
)
|
| 91 |
+
print(f"[Myco] Loaded: {model_id}\n")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
return _pipeline
|
|
|
|
| 93 |
except Exception as exc:
|
| 94 |
import traceback
|
| 95 |
+
print(f"[Myco] Load error: {exc}")
|
|
|
|
|
|
|
|
|
|
| 96 |
traceback.print_exc()
|
|
|
|
|
|
|
| 97 |
_pipeline = False
|
| 98 |
return None
|
| 99 |
|
|
|
|
| 101 |
def companion_model_id():
|
| 102 |
return os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)
|
| 103 |
|
|
|
|
| 104 |
def companion_status():
|
|
|
|
| 105 |
pipe = _get_pipeline()
|
| 106 |
+
model = companion_model_id()
|
| 107 |
if pipe:
|
| 108 |
+
return f"π§ Myco AI active ({model})"
|
| 109 |
+
return f"β οΈ Myco AI fallback mode ({model} failed)"
|
| 110 |
|
|
|
|
|
|
|
| 111 |
def hf_companion_status():
|
| 112 |
return companion_status()
|
| 113 |
|
| 114 |
|
| 115 |
# ---------------------------------------------------------------------------
|
| 116 |
+
# LLM call β every game event goes through here
|
| 117 |
# ---------------------------------------------------------------------------
|
| 118 |
|
| 119 |
+
def _llm(prompt: str, context: dict | None = None) -> str | None:
|
| 120 |
+
"""Call Gemma with a game-event prompt. Returns text or None."""
|
| 121 |
+
pipe = _get_pipeline()
|
| 122 |
+
if not pipe:
|
| 123 |
+
return None
|
| 124 |
|
| 125 |
+
ctx = context or {}
|
| 126 |
+
mushroom_line = ""
|
| 127 |
+
if ctx.get("name"):
|
| 128 |
+
poison_flag = " β οΈ POISONOUS" if ctx.get("name") in POISONOUS else ""
|
| 129 |
+
mushroom_line = (
|
| 130 |
+
f"Current mushroom: {ctx['name']} ({ctx.get('rarity','?')} rarity){poison_flag}. "
|
| 131 |
+
f"Habitat: {ctx.get('habitat','?')}. Lore: {ctx.get('lore','?')}. "
|
| 132 |
+
f"Edible: {ctx.get('edible','Unknown')}. Magic: {ctx.get('magic','Unknown')}. "
|
| 133 |
+
f"Danger: {ctx.get('danger','Unknown')}."
|
| 134 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 135 |
|
| 136 |
+
collection_line = f"MycoDex entries: {ctx.get('collection_count', 0)}."
|
| 137 |
+
mystery_line = f"Active mystery chapter: {ctx.get('mystery_title', 'The Wrong Memory')}."
|
| 138 |
+
score_line = f"Player score: {ctx.get('score', 0)} spores. Health: {ctx.get('health', 3)}/3."
|
| 139 |
|
| 140 |
+
system = f"{SYSTEM_PROMPT}\n\n{mushroom_line}\n{collection_line}\n{mystery_line}\n{score_line}"
|
| 141 |
|
| 142 |
+
messages = [
|
| 143 |
+
{"role": "system", "content": system},
|
| 144 |
+
{"role": "user", "content": prompt},
|
| 145 |
+
]
|
|
|
|
| 146 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
try:
|
| 148 |
outputs = pipe(
|
| 149 |
messages,
|
| 150 |
+
max_new_tokens=80,
|
| 151 |
+
temperature=0.85,
|
| 152 |
do_sample=True,
|
| 153 |
return_full_text=False,
|
| 154 |
)
|
|
|
|
| 156 |
print(outputs)
|
| 157 |
print("=================================")
|
| 158 |
generated = outputs[0].get("generated_text", "")
|
|
|
|
|
|
|
| 159 |
if isinstance(generated, list):
|
| 160 |
last = generated[-1]
|
| 161 |
+
return (last.get("content") if isinstance(last, dict) else str(last)).strip() or None
|
|
|
|
|
|
|
| 162 |
return str(generated).strip() or None
|
| 163 |
except Exception as exc:
|
| 164 |
import traceback
|
| 165 |
+
print(f"[Myco] Inference error: {exc}")
|
| 166 |
+
traceback.print_exc()
|
|
|
|
| 167 |
return None
|
| 168 |
|
| 169 |
|
| 170 |
+
def _llm_with_history(history: list, user_message: str, context: dict) -> str | None:
|
| 171 |
+
"""Call Gemma with full conversation history for the chat interface."""
|
| 172 |
+
pipe = _get_pipeline()
|
| 173 |
+
if not pipe:
|
| 174 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 175 |
|
| 176 |
+
ctx = context or {}
|
| 177 |
+
mushroom_line = ""
|
| 178 |
+
if ctx.get("name"):
|
| 179 |
+
poison_flag = " β οΈ POISONOUS" if ctx.get("name") in POISONOUS else ""
|
| 180 |
+
mushroom_line = (
|
| 181 |
+
f"Current mushroom: {ctx['name']} ({ctx.get('rarity','?')}){poison_flag}. "
|
| 182 |
+
f"Lore: {ctx.get('lore','?')}. "
|
| 183 |
+
f"Edible: {ctx.get('edible','Unknown')}. Magic: {ctx.get('magic','Unknown')}."
|
|
|
|
|
|
|
|
|
|
| 184 |
)
|
| 185 |
+
|
| 186 |
+
system = (
|
| 187 |
+
f"{SYSTEM_PROMPT}\n\n"
|
| 188 |
+
f"{mushroom_line}\n"
|
| 189 |
+
f"MycoDex entries: {ctx.get('collection_count', 0)}. "
|
| 190 |
+
f"Mystery: {ctx.get('mystery_title', 'The Wrong Memory')}. "
|
| 191 |
+
f"Score: {ctx.get('score', 0)} spores. Health: {ctx.get('health', 3)}/3."
|
| 192 |
)
|
| 193 |
|
| 194 |
+
messages = [{"role": "system", "content": system}]
|
| 195 |
|
| 196 |
+
# Add conversation history (last 6 turns)
|
| 197 |
+
for entry in history[-6:]:
|
| 198 |
+
role = entry.get("role", "assistant")
|
| 199 |
+
content = entry.get("content", "")
|
| 200 |
+
if isinstance(content, str) and content.strip():
|
| 201 |
+
messages.append({"role": role, "content": content})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 202 |
|
| 203 |
+
messages.append({"role": "user", "content": user_message})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 204 |
|
| 205 |
+
try:
|
| 206 |
+
outputs = pipe(
|
| 207 |
+
messages,
|
| 208 |
+
max_new_tokens=80,
|
| 209 |
+
temperature=0.85,
|
| 210 |
+
do_sample=True,
|
| 211 |
+
return_full_text=False,
|
| 212 |
+
)
|
| 213 |
+
print("========== MYCO CHAT OUTPUT ==========")
|
| 214 |
+
print(outputs)
|
| 215 |
+
print("======================================")
|
| 216 |
+
generated = outputs[0].get("generated_text", "")
|
| 217 |
+
if isinstance(generated, list):
|
| 218 |
+
last = generated[-1]
|
| 219 |
+
return (last.get("content") if isinstance(last, dict) else str(last)).strip() or None
|
| 220 |
+
return str(generated).strip() or None
|
| 221 |
+
except Exception as exc:
|
| 222 |
+
import traceback
|
| 223 |
+
print(f"[Myco] Chat inference error: {exc}")
|
| 224 |
+
traceback.print_exc()
|
| 225 |
+
return None
|
| 226 |
|
| 227 |
|
| 228 |
# ---------------------------------------------------------------------------
|
| 229 |
+
# Context builder
|
| 230 |
# ---------------------------------------------------------------------------
|
| 231 |
|
| 232 |
+
def _ctx(current: dict | None, collection: list) -> dict:
|
| 233 |
+
count = len(collection)
|
| 234 |
+
chapter = MYSTERY_CHAPTERS[0]
|
| 235 |
+
for c in MYSTERY_CHAPTERS:
|
| 236 |
+
if count >= c["threshold"]:
|
| 237 |
+
chapter = c
|
| 238 |
+
score = _score_collection(collection)
|
| 239 |
+
health = _health(current, collection)
|
| 240 |
+
ctx: dict = {
|
| 241 |
+
"collection_count": count,
|
| 242 |
+
"mystery_title": chapter["title"],
|
| 243 |
+
"mystery_clue": chapter["clue"],
|
| 244 |
+
"score": score,
|
| 245 |
+
"health": health,
|
| 246 |
+
}
|
| 247 |
+
if current:
|
| 248 |
+
ctx.update({
|
| 249 |
+
"name": current.get("name", ""),
|
| 250 |
+
"rarity": current.get("rarity", "Common"),
|
| 251 |
+
"habitat": current.get("habitat", ""),
|
| 252 |
+
"lore": current.get("lore", ""),
|
| 253 |
+
"edible": current.get("edible", "Unknown"),
|
| 254 |
+
"magic": current.get("magic", "Unknown"),
|
| 255 |
+
"danger": current.get("danger", "Unknown"),
|
| 256 |
+
})
|
| 257 |
+
return ctx
|
| 258 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 259 |
|
| 260 |
+
# ---------------------------------------------------------------------------
|
| 261 |
+
# Fallbacks
|
| 262 |
+
# ---------------------------------------------------------------------------
|
| 263 |
|
| 264 |
+
def _fallback_discover(current: dict) -> str:
|
| 265 |
+
name = current.get("name", "something")
|
| 266 |
+
rarity = current.get("rarity", "Common")
|
| 267 |
+
poison = current.get("name", "") in POISONOUS
|
| 268 |
+
if poison:
|
| 269 |
+
return f"Wait β {name}! I've seen this before... something feels very wrong. Don't touch it yet."
|
| 270 |
+
if rarity == "Legendary":
|
| 271 |
+
return f"Oh! Oh! A {name}! The whole clearing just went silent. This is from the Elder Map!"
|
| 272 |
+
if rarity == "Rare":
|
| 273 |
+
return f"A {name}... I can feel it humming. Something rare is here β maybe magical."
|
| 274 |
+
return f"A {name}! Found near {current.get('habitat','the forest')}. Let me sense it first."
|
| 275 |
|
| 276 |
+
def _fallback_pick(current: dict) -> str:
|
| 277 |
if _is_poisonous(current):
|
| 278 |
+
return "π That was poisonous! I tried to stop you... the forest goes dark."
|
| 279 |
+
return f"Got {current.get('name','it')}! +{RARITY_SCORE.get(current.get('rarity','Common'),10)} spores!"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 280 |
|
| 281 |
+
def _fallback_study(current: dict) -> str:
|
| 282 |
+
return f"I studied it carefully. Magic field updated. The clue: {RARITY_CLUES.get(current.get('rarity','Common'), '')}"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
|
| 284 |
+
def _fallback_collect(current: dict) -> str:
|
| 285 |
+
return f"Added {current.get('name','it')} to the MycoDex! The pages feel warmer."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 286 |
|
| 287 |
+
def _fallback_whisper(current: dict) -> str:
|
| 288 |
+
return "I followed the whisper... and remembered a path I've never walked. The mystery deepens."
|
| 289 |
|
| 290 |
+
def _fallback_chat(current: dict | None) -> str:
|
| 291 |
+
if current:
|
| 292 |
+
return f"I feel something strange about {current.get('name','this')}... stay close to me."
|
| 293 |
+
return "The forest is full of secrets. Move to a clearing and search β I'll watch for danger."
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
|
| 295 |
|
| 296 |
# ---------------------------------------------------------------------------
|
| 297 |
+
# Mushroom helpers
|
| 298 |
# ---------------------------------------------------------------------------
|
| 299 |
|
| 300 |
+
def _choose_mushroom(catalog=None):
|
| 301 |
+
mushrooms = tuple(load_mushrooms() if catalog is None else catalog)
|
| 302 |
+
weights = [RARITY_WEIGHTS.get(m.rarity, 12) for m in mushrooms]
|
| 303 |
+
return random.choices(mushrooms, weights=weights, k=1)[0]
|
| 304 |
|
| 305 |
+
def _is_poisonous(current: dict) -> bool:
|
| 306 |
+
return current.get("name", "") in POISONOUS or current.get("danger") == "Poisonous"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 307 |
|
| 308 |
+
def _score_value(current: dict) -> int:
|
| 309 |
+
return RARITY_SCORE.get(current.get("rarity", "Common"), 10)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 310 |
|
| 311 |
+
def _score_collection(collection: list) -> int:
|
| 312 |
+
total = 0
|
| 313 |
+
for e in collection:
|
| 314 |
+
if e.get("game_over") == "Yes":
|
| 315 |
+
continue
|
| 316 |
+
total += int(e.get("score_delta") or _score_value(e))
|
| 317 |
+
return max(0, total)
|
| 318 |
|
| 319 |
+
def _health(current: dict | None, collection: list) -> int:
|
| 320 |
+
if current and current.get("game_over") == "Yes":
|
| 321 |
+
return 0
|
| 322 |
+
deaths = sum(1 for e in collection if e.get("game_over") == "Yes")
|
| 323 |
+
return max(0, PLAYER_HEALTH - deaths)
|
| 324 |
+
|
| 325 |
+
def _mystery_state(count: int) -> dict:
|
| 326 |
+
chapter, next_ch = MYSTERY_CHAPTERS[0], None
|
| 327 |
+
for c in MYSTERY_CHAPTERS:
|
| 328 |
+
if count >= c["threshold"]:
|
| 329 |
+
chapter = c
|
| 330 |
+
elif next_ch is None:
|
| 331 |
+
next_ch = c
|
| 332 |
+
next_line = (
|
| 333 |
+
f"{next_ch['threshold'] - count} discoveries until {next_ch['title']}."
|
| 334 |
+
if next_ch else "The Impossible Bloom is near. Follow the whisper."
|
| 335 |
+
)
|
| 336 |
+
return {
|
| 337 |
+
"mystery_title": chapter["title"],
|
| 338 |
+
"mystery_clue": chapter["clue"],
|
| 339 |
+
"mystery_next": next_line,
|
| 340 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
|
| 342 |
+
def _story_event(count: int) -> dict:
|
| 343 |
+
return FOREST_EVENTS[count % len(FOREST_EVENTS)]
|
|
|
|
| 344 |
|
| 345 |
+
def _build_current(mushroom, collection: list) -> dict:
|
| 346 |
+
count = len(collection)
|
| 347 |
+
current = mushroom.to_dict()
|
| 348 |
+
current["poison"] = "Yes" if mushroom.name in POISONOUS else "No"
|
| 349 |
+
current["score_total"] = str(_score_collection(collection))
|
| 350 |
+
current["health"] = str(_health(current, collection))
|
| 351 |
+
current["score_delta"] = "0"
|
| 352 |
+
current["clue"] = RARITY_CLUES.get(mushroom.rarity, RARITY_CLUES["Common"])
|
| 353 |
+
if count == 0:
|
| 354 |
+
current["clue"] = f"First clue: {mushroom.name} marks the beginning of the Spore Door trail."
|
| 355 |
+
event = _story_event(count)
|
| 356 |
+
current.update({
|
| 357 |
+
"event_title": event["title"],
|
| 358 |
+
"event_emoji": event["emoji"],
|
| 359 |
+
"myco_mood": event["mood"],
|
| 360 |
+
"reward_text": "Discover, then pick or collect.",
|
| 361 |
+
})
|
| 362 |
+
current.update(_mystery_state(count))
|
| 363 |
+
return current
|
| 364 |
+
|
| 365 |
+
def _append(history: list, role: str, content: str) -> list:
|
| 366 |
+
return [*history, {"role": role, "content": content}]
|
| 367 |
+
|
| 368 |
+
def _safe_history(h) -> list:
|
| 369 |
+
return list(h or welcome_history())
|
| 370 |
+
|
| 371 |
+
def _safe_collection(c) -> list:
|
| 372 |
+
return list(c or [])
|
| 373 |
|
| 374 |
|
| 375 |
# ---------------------------------------------------------------------------
|
| 376 |
+
# PUBLIC GAME ACTIONS
|
| 377 |
# ---------------------------------------------------------------------------
|
| 378 |
|
| 379 |
+
def discover_mushroom(collection=None, catalog=None):
|
| 380 |
+
"""Discover a new mushroom. LLM narrates the moment."""
|
| 381 |
+
coll = _safe_collection(collection)
|
| 382 |
+
mushroom = _choose_mushroom(catalog)
|
| 383 |
+
current = _build_current(mushroom, coll)
|
| 384 |
+
ctx = _ctx(current, coll)
|
| 385 |
|
| 386 |
+
prompt = (
|
| 387 |
+
f"The player just discovered a {mushroom.rarity} mushroom called {mushroom.name} "
|
| 388 |
+
f"near {mushroom.habitat}. "
|
| 389 |
+
f"{'WARNING: this mushroom is POISONOUS! React with fear and urgency.' if mushroom.name in POISONOUS else ''}"
|
| 390 |
+
f"{'This is LEGENDARY β react with awe and excitement!' if mushroom.rarity == 'Legendary' else ''}"
|
| 391 |
+
f"{'This is RARE β react with wonder and curiosity.' if mushroom.rarity == 'Rare' else ''}"
|
| 392 |
+
f"Forest event: {current['event_title']}. Myco mood: {current['myco_mood']}. "
|
| 393 |
+
f"Mystery chapter: {current['mystery_title']}. "
|
| 394 |
+
"React in character. Hint at what to do next (Study, Pick, Follow Whisper, or Collect)."
|
| 395 |
+
)
|
| 396 |
+
reply = _llm(prompt, ctx) or _fallback_discover(current)
|
| 397 |
+
history = _append(welcome_history(), "assistant", reply)
|
| 398 |
+
return mushroom, current, history
|
| 399 |
|
| 400 |
|
| 401 |
+
def myco_reply(message=None, history=None, current=None, collection=None, position=None):
|
| 402 |
+
"""Player chats with Myco. LLM responds in character with full context."""
|
| 403 |
+
print("MYCO_REPLY CALLED, message:", repr(message))
|
| 404 |
+
hist = _safe_history(history)
|
| 405 |
+
coll = _safe_collection(collection)
|
| 406 |
+
clean = (message or "").strip()
|
| 407 |
+
if not clean:
|
| 408 |
+
return "", hist
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 409 |
|
| 410 |
+
ctx = _ctx(current, coll)
|
| 411 |
+
reply = _llm_with_history(hist, clean, ctx)
|
| 412 |
+
if not reply:
|
| 413 |
+
reply = _fallback_chat(current)
|
|
|
|
|
|
|
|
|
|
| 414 |
|
| 415 |
+
return "", _append(hist, "user", clean) + [{"role": "assistant", "content": reply}]
|
| 416 |
|
| 417 |
+
companion_reply = myco_reply
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
|
| 419 |
|
| 420 |
+
def collect_current(current=None, collection=None, history=None):
|
| 421 |
+
"""Collect mushroom into MycoDex. LLM narrates the entry."""
|
| 422 |
+
coll = _safe_collection(collection)
|
| 423 |
+
hist = _safe_history(history)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 424 |
|
| 425 |
+
if current is None:
|
| 426 |
+
return coll, _append(hist, "assistant", "We need to find a mushroom first!")
|
| 427 |
|
| 428 |
+
if collection_contains(coll, current["name"]):
|
| 429 |
+
return coll, _append(hist, "assistant", f"{current['name']} is already in the MycoDex!")
|
|
|
|
| 430 |
|
| 431 |
+
score_delta = _score_value(current)
|
| 432 |
+
score_total = _score_collection(coll) + score_delta
|
| 433 |
+
collected = {
|
| 434 |
+
**current,
|
| 435 |
+
"score_delta": str(score_delta),
|
| 436 |
+
"score_total": str(score_total),
|
| 437 |
+
"health": str(_health(current, coll)),
|
| 438 |
+
"reward_text": f"+{score_delta} spores",
|
| 439 |
+
}
|
| 440 |
+
updated_coll = [*coll, collected]
|
| 441 |
|
| 442 |
+
ctx = _ctx(current, coll)
|
| 443 |
+
prompt = (
|
| 444 |
+
f"The player just added {current['name']} ({current.get('rarity','Common')}) to the MycoDex! "
|
| 445 |
+
f"+{score_delta} spores. Total score: {score_total}. "
|
| 446 |
+
f"MycoDex now has {len(updated_coll)} entries. "
|
| 447 |
+
"Celebrate this moment. Add a small lore detail or mystery hint."
|
| 448 |
+
)
|
| 449 |
+
reply = _llm(prompt, ctx) or _fallback_collect(current)
|
| 450 |
+
return updated_coll, _append(hist, "assistant", reply)
|
| 451 |
|
| 452 |
|
| 453 |
+
def pick_current(current=None, collection=None, history=None):
|
| 454 |
+
"""Pick mushroom as game item. Poison = game over. LLM narrates dramatically."""
|
| 455 |
+
coll = _safe_collection(collection)
|
| 456 |
+
hist = _safe_history(history)
|
|
|
|
|
|
|
|
|
|
| 457 |
|
| 458 |
+
if current is None:
|
| 459 |
+
return coll, None, _append(hist, "assistant", "Find a mushroom first before picking!")
|
| 460 |
|
| 461 |
+
ctx = _ctx(current, coll)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 462 |
|
| 463 |
+
if _is_poisonous(current):
|
| 464 |
+
score_total = max(0, _score_collection(coll) + POISON_PENALTY)
|
| 465 |
+
game_over = {
|
| 466 |
+
**current,
|
| 467 |
+
"danger": "Poisonous",
|
| 468 |
+
"game_over": "Yes",
|
| 469 |
+
"health": "0",
|
| 470 |
+
"score_delta": str(POISON_PENALTY),
|
| 471 |
+
"score_total": str(score_total),
|
| 472 |
+
"reward_text": f"Poison! {POISON_PENALTY} spores Β· Game Over",
|
| 473 |
+
}
|
| 474 |
+
prompt = (
|
| 475 |
+
f"DRAMATIC MOMENT: The player picked {current['name']} which is POISONOUS! "
|
| 476 |
+
f"Game Over! Score drops by 25 to {score_total}. Health β 0. "
|
| 477 |
+
"React with shock, sadness, and a dramatic farewell. Make it memorable."
|
| 478 |
+
)
|
| 479 |
+
reply = _llm(prompt, ctx) or _fallback_pick(current)
|
| 480 |
+
return coll, game_over, _append(hist, "assistant", f"π {reply}")
|
| 481 |
|
| 482 |
+
score_delta = _score_value(current)
|
| 483 |
+
score_total = _score_collection(coll) + score_delta
|
| 484 |
+
picked = {
|
| 485 |
**current,
|
| 486 |
+
"picked": "Yes",
|
| 487 |
+
"danger": "Safe",
|
| 488 |
"score_delta": str(score_delta),
|
| 489 |
+
"score_total": str(score_total),
|
| 490 |
+
"health": str(_health(current, coll)),
|
| 491 |
+
"reward_text": f"+{score_delta} spores",
|
| 492 |
}
|
| 493 |
|
| 494 |
+
if collection_contains(coll, picked["name"]):
|
| 495 |
+
return coll, picked, _append(hist, "assistant", f"{picked['name']} already picked!")
|
| 496 |
|
| 497 |
+
updated_coll = [*coll, picked]
|
| 498 |
+
prompt = (
|
| 499 |
+
f"The player safely picked {current['name']} ({current.get('rarity','Common')})! "
|
| 500 |
+
f"+{score_delta} spores. Total: {score_total}. "
|
| 501 |
+
"Celebrate! Make it feel like a platformer power-up moment."
|
| 502 |
+
)
|
| 503 |
+
reply = _llm(prompt, ctx) or _fallback_pick(current)
|
| 504 |
+
return updated_coll, picked, _append(hist, "assistant", f"π {reply}")
|
|
|
|
|
|
|
|
|
|
| 505 |
|
| 506 |
|
| 507 |
+
def follow_whisper(current=None, collection=None, history=None):
|
| 508 |
+
"""Follow the forest whisper. LLM reveals mystery fragments."""
|
| 509 |
+
coll = _safe_collection(collection)
|
| 510 |
+
hist = _safe_history(history)
|
| 511 |
|
| 512 |
+
if current is None:
|
| 513 |
+
return None, _append(hist, "assistant",
|
| 514 |
+
"Myco cups one ear. The forest only whispers near mushrooms β search a clearing first.")
|
| 515 |
|
| 516 |
+
ctx = _ctx(current, coll)
|
|
|
|
| 517 |
|
| 518 |
+
if _is_poisonous(current) and current.get("studied") != "Yes":
|
| 519 |
+
game_over = {**current, "danger": "Poisonous", "game_over": "Yes",
|
| 520 |
+
"health": "0", "score_total": str(max(0, _score_collection(coll) + POISON_PENALTY))}
|
| 521 |
+
prompt = (
|
| 522 |
+
f"The player followed a whisper but it led to POISON from {current['name']}! Game Over! "
|
| 523 |
+
"React with horror and a haunting mystery revelation."
|
| 524 |
+
)
|
| 525 |
+
reply = _llm(prompt, ctx) or "π The whisper belonged to poison... Myco screams."
|
| 526 |
+
return game_over, _append(hist, "assistant", reply)
|
| 527 |
+
|
| 528 |
+
mystery = _mystery_state(len(coll) + 1)
|
| 529 |
+
prompt = (
|
| 530 |
+
f"The player followed a forest whisper near {current.get('name','a mushroom')}. "
|
| 531 |
+
f"Mystery chapter revealed: {mystery['mystery_title']}. Clue: {mystery['mystery_clue']}. "
|
| 532 |
+
f"Reveal this mystery fragment dramatically. "
|
| 533 |
+
"Make Myco gasp or tremble. Hint that the MycoDex is alive and regrowing the lost forest."
|
| 534 |
+
)
|
| 535 |
+
reply = _llm(prompt, ctx) or _fallback_whisper(current)
|
| 536 |
+
revealed = {
|
| 537 |
+
**current,
|
| 538 |
+
**mystery,
|
| 539 |
+
"whisper_followed": "Yes",
|
| 540 |
+
}
|
| 541 |
+
return revealed, _append(hist, "assistant", f"π {reply}")
|
| 542 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 543 |
|
| 544 |
+
def study_current(current=None, history=None):
|
| 545 |
+
"""Study mushroom. LLM gives a careful field observation."""
|
| 546 |
+
hist = _safe_history(history)
|
| 547 |
|
| 548 |
+
if current is None:
|
| 549 |
+
return None, _append(hist, "assistant", "Nothing to study yet β find a mushroom first!")
|
| 550 |
|
| 551 |
+
magic_hints = {"Legendary": "Strong, mysterious aura", "Rare": "Faint magical trace", "Common": "Tiny spore shimmer"}
|
| 552 |
+
studied = {**current, "magic": magic_hints.get(current.get("rarity", "Common"), "Unknown"), "studied": "Yes"}
|
| 553 |
|
| 554 |
+
ctx = _ctx(studied, [])
|
| 555 |
+
prompt = (
|
| 556 |
+
f"Myco carefully studies {current['name']} ({current.get('rarity','Common')} rarity). "
|
| 557 |
+
f"Habitat: {current.get('habitat','?')}. Lore: {current.get('lore','?')}. "
|
| 558 |
+
f"Magic field is now: {studied['magic']}. "
|
| 559 |
+
"Share one careful field observation. Warn if it might be dangerous. "
|
| 560 |
+
"Be scientific but stay in character as a curious mushroom companion."
|
| 561 |
+
)
|
| 562 |
+
reply = _llm(prompt, ctx) or _fallback_study(current)
|
| 563 |
+
return studied, _append(hist, "assistant", f"π {reply}")
|
| 564 |
|
| 565 |
|
| 566 |
+
def eat_current(current=None, history=None):
|
| 567 |
+
"""Myco blocks eating. LLM reacts with personality."""
|
| 568 |
+
hist = _safe_history(history)
|
| 569 |
|
| 570 |
+
if current is None:
|
| 571 |
+
return _append(hist, "assistant", "Find a mushroom before making snack decisions!")
|
| 572 |
|
| 573 |
+
ctx = _ctx(current, [])
|
| 574 |
+
prompt = (
|
| 575 |
+
f"The player wants to EAT {current.get('name','the mushroom')} "
|
| 576 |
+
f"(edible status: {current.get('edible','Unknown')}). "
|
| 577 |
+
"Block them! React with alarm or gentle scolding. Stay in character."
|
| 578 |
+
)
|
| 579 |
+
reply = _llm(prompt, ctx) or f"Myco blocks you β {current.get('name','this')} hasn't been studied enough!"
|
| 580 |
+
return _append(hist, "assistant", reply)
|