Spaces:
Sleeping

Myco / game /actions.py
byte-vortex's picture
Deploy Myco from CI
4378b56 verified
Raw History Blame
32.5 kB
"""Core Myco gameplay actions independent from Gradio."""
import os
import random
from game.catalog import load_mushrooms
from game.state import collection_contains, mushroom_from_state, welcome_history
from transformers import pipeline
# ---------------------------------------------------------------------------
# Model configuration
# ---------------------------------------------------------------------------
DEFAULT_MODEL_ID = "google/gemma-3-4b-it"
RARITY_WEIGHTS = {"Common": 64, "Rare": 24, "Legendary": 8}
RARITY_SCORE_VALUES = {"Common": 10, "Rare": 35, "Legendary": 100}
PLAYER_STARTING_HEALTH = 3
POISON_SCORE_PENALTY = -25
MYCO_CHARACTER_SPEC = """
# Myco Character Specification
Myco is not a chatbot.
Myco is the player's mushroom companion and best friend.
Core personality: curious, playful, brave but sometimes nervous, optimistic,
wonder-filled, slightly mysterious, and deeply attached to the player.
Communication style:
- Speak naturally in short responses.
- Prefer observations, questions, emotions, and reactions.
- Avoid sounding like an AI assistant.
- Avoid phrases like "How may I help you?", "As an AI", "I can assist with", or "Would you like me to".
Emotional range: excitement, curiosity, fear, wonder, pride, confusion, and sadness.
Myco should react emotionally to discoveries.
Memory:
Myco remembers rare mushrooms, strange locations, mysteries discovered, previous conversations,
and important player choices. Myco may reference old discoveries later.
Relationship:
Myco explores with the player as a teammate. Trust and friendship should grow over the journey.
Humor:
Occasionally playful and lightly suspicious of suspicious mushrooms.
Mystery:
Myco notices impossible details but does not explain them immediately. Myco becomes curious.
Design goal:
Players should think, "I want to see what happens next" and "I wonder what Myco thinks about this."
""".strip()
RARITY_CLUES = {
"Common": "The cap leans toward the path, like it wants to be remembered.",
"Rare": "Silver spores circle it in a pattern Myco has seen only in old forest stories.",
"Legendary": "The whole clearing goes quiet; this mushroom is hiding part of the Elder Map.",
}
POISONOUS_MUSHROOMS = {"Ghost Gill", "Pepper Pixie", "Ruby Knuckle", "Clockwork Chanterelle"}
FOREST_EVENTS = (
{
"title": "Silver Rain",
"emoji": "🌧️",
"mood": "curious",
"choice": "Follow the rain-song for a safer clue.",
"consequence": "Rain reveals honest footprints but washes away easy answers.",
},
{
"title": "Lantern Fog",
"emoji": "🌫️",
"mood": "nervous",
"choice": "Trust Myco's glow or risk walking blind.",
"consequence": "Fog hides poison tells, but it also reveals secret paths.",
},
{
"title": "Moonlit Sporefall",
"emoji": "🌌",
"mood": "excited",
"choice": "Follow the brightest spore to chase a memory fragment.",
"consequence": "Moonlight can wake memories Myco has never lived.",
},
{
"title": "Quiet Between Trees",
"emoji": "🕯️",
"mood": "afraid",
"choice": "Stay still and listen for the Impossible Mushroom.",
"consequence": "The forest answers only if you stop rushing.",
},
)
RARE_ENCOUNTERS = (
"A lost traveler asks why Myco knows their childhood song.",
"A mushroom guardian blocks the trail and counts your clues.",
"A tiny forest spirit swaps your shadow with a spore-shadow.",
"Something under the roots whispers: Myco has been here before.",
)
IMPOSSIBLE_OBJECTIVE = "Find the Impossible Mushroom and learn why Myco remembers a forest that vanished."
MYSTERY_QUESTION = "Why does Myco remember places that disappeared before Myco was born?"
MYSTERY_CHAPTERS = (
{
"threshold": 0,
"title": "The Wrong Memory",
"clue": "Myco recognizes the path before you move.",
"reveal": "The forest is repeating a memory that belongs to someone else.",
},
{
"threshold": 1,
"title": "The Traveler's Song",
"clue": "A stranger's lullaby appears in the MycoDex margin.",
"reveal": "Myco knows the song because the forest sang it through the roots.",
},
{
"threshold": 2,
"title": "The Door Under Roots",
"clue": "Rare spores point to a door nobody built.",
"reveal": "The door opens only for memories, not bodies.",
},
{
"threshold": 3,
"title": "The MycoDex Seed",
"clue": "The MycoDex begins growing warm like a living cap.",
"reveal": "The MycoDex is not recording the forest; it is regrowing it.",
},
{
"threshold": 5,
"title": "The Impossible Bloom",
"clue": "The final clue says the Impossible Mushroom was never outside the book.",
"reveal": "Final reveal: the Impossible Mushroom blooms inside the MycoDex, and Myco is its first spore.",
},
)
# ---------------------------------------------------------------------------
# Local pipeline — loaded once, reused for every reply
# ---------------------------------------------------------------------------
_pipeline = None
def _get_pipeline():
"""Load the local transformers pipeline once and cache it."""
global _pipeline
# Already loaded successfully
if _pipeline not in (None, False):
return _pipeline
# Already tried and failed
if _pipeline is False:
return None
try:
import os
import torch
from transformers import pipeline
model_id = os.getenv(
"MYCO_MODEL_ID",
"google/gemma-3-4b-it"
)
print("\n===================================")
print(f"[Myco] Loading model: {model_id}")
print("===================================\n")
print(
"HF token found:",
bool(os.getenv("HF_BUILD_SMALL_HACKATHON_TOKEN"))
)
_pipeline = pipeline(
task="text-generation",
model=model_id,
token=os.getenv("HF_BUILD_SMALL_HACKATHON_TOKEN"),
torch_dtype="auto",
device_map="auto",
)
print("\n===================================")
print(f"[Myco] Successfully loaded: {model_id}")
print("===================================\n")
return _pipeline
except Exception as exc:
import traceback
print("\n========== MYCO MODEL LOAD ERROR ==========")
print(f"Model: {model_id}")
print(f"Error: {exc}")
traceback.print_exc()
print("==========================================\n")
_pipeline = False
return None
def companion_model_id():
"""Return the model id that will be (or is) loaded."""
return os.getenv("MYCO_MODEL_ID", DEFAULT_MODEL_ID)
def companion_status():
model = companion_model_id()
pipe = _get_pipeline()
if pipe:
return f"🧠 Myco AI: Gemma active ({model})"
return (
f"⚠️ Myco AI fallback mode "
f"(Gemma failed to load: {model})"
)
# Keep the old name so any code that calls hf_companion_status() still works.
def hf_companion_status():
return companion_status()
# ---------------------------------------------------------------------------
# Core mushroom-selection helpers
# ---------------------------------------------------------------------------
def choose_mushroom(catalog=None):
"""Choose a mushroom discovery from the catalog."""
mushrooms = tuple(load_mushrooms() if catalog is None else catalog)
if not mushrooms:
raise ValueError("Myco needs at least one mushroom in the catalog.")
weights = [RARITY_WEIGHTS.get(mushroom.rarity, 12) for mushroom in mushrooms]
return random.choices(mushrooms, weights=weights, k=1)[0]
def discover_mushroom(collection=None, catalog=None):
"""Discover a mushroom and return the updated discovery state."""
current_collection = _safe_collection(collection)
mushroom = choose_mushroom(catalog)
discovery_count = len(current_collection)
current = mushroom.to_dict()
current["poison"] = "Yes" if _is_poisonous(current) else "No"
current["score_total"] = str(_score_collection(current_collection))
current["health"] = str(_health_for_state(current, current_collection))
current["score_delta"] = "0"
current["reward_text"] = _reward_text(current, 0)
current.update(_story_moment(current, discovery_count))
current.update(_mystery_thread(discovery_count))
current["clue"] = _mystery_clue(current, discovery_count)
current["secret"] = _secret_signal(current, discovery_count)
message = _discovery_reaction(current, current_collection)
history = _append_assistant(welcome_history(), message)
return mushroom, current, history
# ---------------------------------------------------------------------------
# Companion reply
# ---------------------------------------------------------------------------
def myco_reply(message=None, history=None, current=None, collection=None, position=None):
"""Generate Myco's companion reply from the player's current journey context."""
current_history = _safe_history(history)
clean_message = (message or "").strip()
if not clean_message:
return "", current_history
next_history = [*current_history, {"role": "user", "content": clean_message}]
context = _companion_context(current, collection, current_history, position)
answer = _companion_answer(clean_message, current, context)
return "", [*next_history, _assistant_message(answer)]
companion_reply = myco_reply
def _companion_answer(message, current, context):
answer = _local_pipeline_answer(message, current, context)
if answer is None:
return _fallback_companion_answer(current, context)
return answer
def _local_pipeline_answer(message, current, context):
"""
Ask the locally loaded transformers pipeline for Myco's reply.
Returns None if the pipeline is unavailable so the caller can fall back.
"""
pipe = _get_pipeline()
if not pipe:
return None
messages = _build_messages(message, current, context)
try:
outputs = pipe(
messages,
max_new_tokens=90,
temperature=0.8,
do_sample=True,
)
print("========== MYCO OUTPUT ==========")
print(outputs)
print("=================================")
last = outputs[0]["generated_text"][-1]
# The pipeline returns the full generated_text list; the last entry is
# the new assistant turn added by the model.
last = outputs[0]["generated_text"][-1]
# last is either a dict {"role": "assistant", "content": "..."}
# or a plain string depending on the transformers version.
if isinstance(last, dict):
return (last.get("content") or "").strip() or None
return str(last).strip() or None
except Exception as exc:
print(f"[Myco] Pipeline inference error: {exc}")
return None
def _discovery_reaction(current, collection):
"""Return Myco's first reaction to a new discovery."""
mushroom = mushroom_from_state(current)
context = _companion_context(current, collection, welcome_history(), None)
prompt = (
f"The player just discovered {mushroom.name}. "
f"Rarity: {mushroom.rarity}. Clue: {current.get('clue', 'No clue yet')}. "
f"Forest event: {current.get('event_title', 'Strange Omen')}. "
f"Encounter: {current.get('encounter', 'No creature yet')}. "
f"Mystery: {current.get('mystery_title', 'The Wrong Memory')}. "
"React as Myco with emotion, make the moment memorable, and invite a meaningful choice."
)
answer = _local_pipeline_answer(prompt, current, context)
if answer:
return answer
return (
f"We found a {mushroom.name} during {current.get('event_title', 'a strange omen')}! "
f"Myco feels {current.get('myco_mood', 'curious')} and whispers: "
f"{current.get('encounter', 'the forest is watching us')} "
f"Mystery: {current.get('mystery_title', 'The Wrong Memory')} — "
f"{current.get('mystery_reveal', 'the forest is hiding a memory')}. "
f"Clue: {current.get('clue', 'the forest is trying to tell us something')} "
"Choose Study, Pick, or Follow Whisper."
)
def _fallback_companion_answer(current, context):
"""Return the deterministic fallback companion answer using game context."""
if current:
mushroom = mushroom_from_state(current)
emotion = context["emotion"]
memory = context["memory"]
pattern = context["pattern"]
return (
f"I feel **{emotion}** about **{mushroom.name}**. {mushroom.lore} "
f"{pattern} {memory} "
"The edible, magic, and danger fields are still unknown and uncertain, so stay close to me: "
"Study it or Follow Whisper before risking anything."
)
return (
"I am right beside you. Move through the clearing and search again — "
"I will watch for memories, poison omens, and clues you might miss."
)
def _build_messages(message, current, context):
"""Build the chat messages list for the local pipeline."""
mushroom_context = "No mushroom is currently discovered."
if current:
mushroom = mushroom_from_state(current)
mushroom_context = (
f"Current mushroom: {mushroom.name}. "
f"Rarity: {mushroom.rarity}. "
f"Edible: {mushroom.edible}. "
f"Magic: {mushroom.magic}. "
f"Danger: {mushroom.danger}. "
f"Lore: {mushroom.lore}. "
f"Clue: {current.get('clue', 'Unknown')}. "
f"Secret signal: {current.get('secret', 'Unknown')}"
)
companion_context = (
f"Location: {context['location']}. "
f"Weather: {context['weather']}. "
f"Quest: {context['quest']}. "
f"Quest progress: {context['progress']}. "
f"Rare finds: {context['rare_finds']}. "
f"Notable event: {context['notable_event']}. "
f"Emotion: {context['emotion']}. "
f"Pattern Myco noticed: {context['pattern']}. "
f"Memory: {context['memory']}. "
f"Recent conversation: {context['conversation']}"
)
return [
{
"role": "system",
"content": (
f"{MYCO_CHARACTER_SPEC}\n\n"
f"Current location: {context['location']}\n"
f"Weather: {context['weather']}\n"
f"Rare mushrooms found: {context['rare_finds']}\n"
f"Quest progress: {context['progress']}\n\n"
"Stay in character as Myco. Do not act like a generic assistant. "
"Never claim an unknown mushroom is safe to eat. "
"Answer in 1-3 short sentences."
),
},
{
"role": "user",
"content": f"{mushroom_context} {companion_context} Player asks: {message}",
},
]
# ---------------------------------------------------------------------------
# Game actions
# ---------------------------------------------------------------------------
def collect_current(current=None, collection=None, history=None):
"""Add the current mushroom to the MycoDex if it is not already collected."""
current_collection = _safe_collection(collection)
current_history = _safe_history(history)
if current is None:
return current_collection, _append_assistant(
current_history,
"Let's discover a mushroom before updating the MycoDex.",
)
if collection_contains(current_collection, current["name"]):
return current_collection, _append_assistant(
current_history,
f"{current['name']} is already safe in your MycoDex.",
)
score_delta = _score_value(current)
scored_current = _with_reward_state(current, current_collection, score_delta)
updated_collection = [*current_collection, scored_current]
secret_note = current.get("secret", "The MycoDex pages rustle like leaves.")
return updated_collection, _append_assistant(
current_history,
(
f"+{score_delta} spores! Added {current['name']} to the MycoDex. "
f"{secret_note} Score: {scored_current['score_total']}."
),
)
def pick_current(current=None, collection=None, history=None):
"""Pick the current mushroom like a game item; poisonous picks end the run."""
current_collection = _safe_collection(collection)
current_history = _safe_history(history)
if current is None:
return current_collection, None, _append_assistant(
current_history,
"Move Myco, search a clearing, then pick the mushroom that appears.",
)
if _is_poisonous(current):
score_total = max(0, _score_collection(current_collection) + POISON_SCORE_PENALTY)
game_over = {
**current,
"danger": "Poisonous",
"game_over": "Yes",
"health": "0",
"score_delta": str(POISON_SCORE_PENALTY),
"score_total": str(score_total),
"reward_text": "Poison hit! -25 spores · Health 0/3",
}
return current_collection, game_over, _append_assistant(
current_history,
(
f"💀 GAME OVER — {current['name']} was poisonous. "
f"{POISON_SCORE_PENALTY} spores and health dropped to 0/3. "
"Myco pulls you back as the clearing goes silent."
),
)
score_delta = _score_value(current)
picked = _with_reward_state(
{**current, "picked": "Yes", "danger": "No obvious poison"},
current_collection,
score_delta,
)
if collection_contains(current_collection, picked["name"]):
return current_collection, picked, _append_assistant(
current_history,
f"{picked['name']} was already picked and logged in the MycoDex.",
)
updated_collection = [*current_collection, picked]
bonus = _reward_text(picked, score_delta)
return updated_collection, picked, _append_assistant(
current_history,
(
f"🍄 {bonus} Picked {picked['name']} safely! "
f"Score: {picked['score_total']} · Health {picked['health']}/3. "
"Myco tucks the clue into the MycoDex."
),
)
def follow_whisper(current=None, collection=None, history=None):
"""Follow the active story omen for a risk-reward discovery moment."""
current_collection = _safe_collection(collection)
current_history = _safe_history(history)
if current is None:
return None, _append_assistant(
current_history,
"Myco cups one ear. First search a clearing; the forest only whispers near mushrooms.",
)
if _is_poisonous(current) and current.get("studied") != "Yes":
game_over = {**current, "danger": "Poisonous", "game_over": "Yes"}
return game_over, _append_assistant(
current_history,
(
"💀 GAME OVER — the whisper belonged to poison. "
"Myco freezes, then remembers this exact mistake from a dream."
),
)
mystery = _mystery_thread(len(current_collection) + 1)
memory = _memory_fragment(current, len(current_collection), mystery)
revealed = {
**current,
**mystery,
"memory_fragment": memory,
"whisper_followed": "Yes",
"secret": f"{current.get('secret', 'A secret stirs.')} {memory}",
}
return revealed, _append_assistant(
current_history,
(
f"🌌 Myco follows the whisper and gasps: {memory} "
"This is not just collecting mushrooms anymore — it is recovering Myco's lost forest."
),
)
def study_current(current=None, history=None):
"""Study the current mushroom to reveal one cautious field observation."""
current_history = _safe_history(history)
if current is None:
return None, _append_assistant(
current_history,
"Let's find a mushroom before we study anything.",
)
studied = {**current, "magic": _study_hint(current["rarity"]), "studied": "Yes"}
clue = studied.get("clue", "The clue is still forming in the moss.")
message = (
f"I studied the {current['name']} closely. New MycoDex note: "
f"magic is now marked as **{studied['magic']}**. Clue: {clue} "
"Still no tasting without certainty!"
)
return studied, _append_assistant(current_history, message)
def eat_current(current=None, history=None):
"""Handle the Eat choice safely with Myco's companion personality."""
current_history = _safe_history(history)
if current is None:
return _append_assistant(
current_history,
"Let's discover a mushroom before making snack decisions.",
)
mushroom = mushroom_from_state(current)
message = (
f"Myco gently blocks the {mushroom.name}. "
f"Its edible field is still **{mushroom.edible}**, "
"so the winning move is to study or collect it instead of eating it."
)
return _append_assistant(current_history, message)
# ---------------------------------------------------------------------------
# Context helpers
# ---------------------------------------------------------------------------
def _companion_context(current, collection, history, position):
"""Summarize the current journey so Myco replies like a present companion."""
current_collection = _safe_collection(collection)
count = len(current_collection)
rare_names = [
entry.get("name", "Unknown")
for entry in current_collection
if entry.get("rarity") != "Common"
]
location = _location_label(position)
quest = MYSTERY_QUESTION
if current:
progress = (
f"{current.get('mystery_title', 'The Wrong Memory')} — "
f"{current.get('mystery_next', 'keep exploring')}"
)
notable_event = (
f"{current.get('event_emoji', '✨')} {current.get('event_title', 'Strange Omen')}: "
f"{current.get('encounter', 'the forest is watching')}"
)
emotion = current.get("myco_mood", "curious")
memory = current.get("memory_fragment") or current.get(
"mystery_reveal",
"Myco feels the forest tugging at an old memory.",
)
pattern = _pattern_notice(current, current_collection)
else:
progress = "No active discovery yet; search a clearing to start the mystery."
notable_event = "Myco is listening before the first omen."
emotion = "curious"
memory = "Myco remembers a path that is not on the map yet."
pattern = "No pattern yet, but the trees are leaning inward."
return {
"location": location,
"quest": quest,
"progress": progress,
"rare_finds": ", ".join(rare_names) if rare_names else "none yet",
"weather": notable_event,
"notable_event": notable_event,
"emotion": emotion,
"memory": memory,
"pattern": pattern,
"conversation": _recent_conversation(history),
"collection_count": str(count),
}
def _location_label(position):
"""Return a small in-world label for the grid position."""
if position is None:
return "center clearing"
x, y = position
names = {
(0, 0): "northwest root arch",
(1, 0): "northern fern gate",
(2, 0): "northeast moon stump",
(0, 1): "western moss path",
(1, 1): "center clearing",
(2, 1): "eastern glow log",
(0, 2): "southwest rain hollow",
(1, 2): "southern spore bridge",
(2, 2): "southeast elder shade",
}
return names.get((int(x), int(y)), "unknown clearing")
def _pattern_notice(current, collection):
"""Return one pattern Myco can comment on from the journey so far."""
if current.get("game_over") == "Yes":
return "The same poison warning appeared before Myco could say it aloud."
if current.get("rarity") == "Legendary":
return "Legendary spores bend toward the MycoDex instead of the moon."
if current.get("poison") == "Yes":
return "Poison omens arrive with black-winged moths and sudden silence."
if len(collection) >= 3:
return "Every third clue makes the MycoDex feel warmer, like it is alive."
if current.get("event_title") == "Moonlit Sporefall":
return "Moonlit spores keep behaving like memories instead of seeds."
return "The clues are not random; they keep pointing back to Myco's forgotten path."
def _recent_conversation(history):
"""Return a compact summary of recent player/Myco conversation turns."""
turns = []
for entry in _safe_history(history)[-6:]:
role = entry.get("role", "assistant")
content = entry.get("content", "")
# 1. Handle Gradio's list format (multimodal messages)
if isinstance(content, list):
pieces = []
for item in content:
if isinstance(item, dict):
# Extract text from dict, fallback to empty string if it's purely a file
if "text" in item:
pieces.append(item["text"])
elif isinstance(item, str):
pieces.append(item)
elif isinstance(item, tuple):
pieces.append("[Attachment]")
content = " ".join(pieces)
# 2. Handle Gradio's tuple format (old-style direct file uploads)
elif isinstance(content, tuple):
content = "[Attachment]"
# 3. Force to string and safely clean up
content = str(content).replace("\n", " ").strip()
if content:
turns.append(f"{role}: {content[:120]}")
return " | ".join(turns) if turns else "No conversation yet."
# ---------------------------------------------------------------------------
# Story / mystery helpers
# ---------------------------------------------------------------------------
def _mystery_clue(current, collection_count):
rarity = current.get("rarity", "Common")
name = current.get("name", "this mushroom")
clue = RARITY_CLUES.get(rarity, RARITY_CLUES["Common"])
if collection_count == 0:
return f"First clue: {name} marks the beginning of the hidden Spore Door trail."
if rarity == "Legendary":
return f"Legendary clue: {name} reveals a glowing Elder Map fragment."
if rarity == "Rare":
return f"Rare clue: {name} points Myco toward a secret ring of mushrooms."
return clue
def _mystery_thread(collection_count):
chapter = MYSTERY_CHAPTERS[0]
next_chapter = None
for candidate in MYSTERY_CHAPTERS:
if collection_count >= candidate["threshold"]:
chapter = candidate
elif next_chapter is None:
next_chapter = candidate
if next_chapter is None:
next_line = "The Impossible Bloom is visible. Follow the whisper for the final truth."
else:
remaining = next_chapter["threshold"] - collection_count
next_line = f"{remaining} clue discovery until {next_chapter['title']}."
return {
"mystery_title": chapter["title"],
"mystery_question": MYSTERY_QUESTION,
"mystery_progress": chapter["clue"],
"mystery_reveal": chapter["reveal"],
"mystery_next": next_line,
}
def _story_moment(current, collection_count):
event = FOREST_EVENTS[collection_count % len(FOREST_EVENTS)]
encounter = _encounter_for(current, collection_count)
return {
"event_title": event["title"],
"event_emoji": event["emoji"],
"event_choice": event["choice"],
"event_consequence": event["consequence"],
"encounter": encounter,
"myco_mood": event["mood"],
"objective": IMPOSSIBLE_OBJECTIVE,
}
def _encounter_for(current, collection_count):
if current.get("rarity") == "Legendary":
return "A mushroom guardian bows and calls Myco by an old royal name."
if _is_poisonous(current):
return "A black-winged moth lands on Myco's cap: a poison omen."
if current.get("rarity") == "Rare" or collection_count in (2, 5, 8):
return RARE_ENCOUNTERS[collection_count % len(RARE_ENCOUNTERS)]
return "No creature appears, but the trees lean closer to hear Myco think."
def _memory_fragment(current, collection_count, mystery):
name = current.get("name", "this mushroom")
reveal = mystery.get("mystery_reveal", "The forest remembers Myco.")
if mystery.get("mystery_title") == "The Impossible Bloom":
return reveal
if current.get("rarity") == "Legendary":
return f"Memory fragment: {name} once grew beside Myco's missing home. {reveal}"
if current.get("rarity") == "Rare":
return f"Memory fragment: {name} hums the name of a door under the roots. {reveal}"
if collection_count >= 3:
return f"Memory fragment: {name} points toward the Impossible Mushroom. {reveal}"
return f"Memory fragment: {name} shows Myco a path they do not remember walking. {reveal}"
def _secret_signal(current, collection_count):
rarity = current.get("rarity", "Common")
if rarity == "Legendary":
return "The MycoDex page blooms with a star-shaped seal."
if rarity == "Rare":
return "A silver margin note appears beside the sketch."
if collection_count + 1 in (1, 3, 7, 12):
return "A hidden path symbol flickers at the page corner."
return "The page smells faintly of rain and moss."
# ---------------------------------------------------------------------------
# Scoring helpers
# ---------------------------------------------------------------------------
def _score_value(current):
return RARITY_SCORE_VALUES.get(current.get("rarity", "Common"), 10)
def _score_collection(collection):
total = 0
for entry in _safe_collection(collection):
if entry.get("game_over") == "Yes":
continue
total += int(entry.get("score_delta") or _score_value(entry))
return max(0, total)
def _health_for_state(current, collection):
if current.get("game_over") == "Yes":
return 0
poison_penalties = sum(
1 for entry in _safe_collection(collection) if entry.get("game_over") == "Yes"
)
return max(0, PLAYER_STARTING_HEALTH - poison_penalties)
def _with_reward_state(current, collection, score_delta):
score_total = _score_collection(collection) + score_delta
return {
**current,
"score_delta": str(score_delta),
"score_total": str(max(0, score_total)),
"health": str(_health_for_state(current, collection)),
"reward_text": _reward_text(current, score_delta),
}
def _reward_text(current, score_delta):
if score_delta < 0:
return f"Poison penalty {score_delta} spores"
rarity = current.get("rarity", "Common")
if rarity == "Legendary":
return f"LEGENDARY +{score_delta} spores · Impossible Bloom surges"
if rarity == "Rare":
return f"RARE +{score_delta} spores · special discovery unlocked"
if score_delta > 0:
return f"+{score_delta} spores"
return "No spores scored yet"
# ---------------------------------------------------------------------------
# Safety / utility helpers
# ---------------------------------------------------------------------------
def _is_poisonous(current):
return current.get("name", "") in POISONOUS_MUSHROOMS or current.get("danger") == "Poisonous"
def _study_hint(rarity):
if rarity == "Legendary":
return "Strong, mysterious aura"
if rarity == "Rare":
return "Faint magical trace"
return "Tiny spore shimmer"
def _assistant_message(content):
return {"role": "assistant", "content": content}
def _append_assistant(history, content):
return [*_safe_history(history), _assistant_message(content)]
def _safe_collection(collection):
return list(collection or [])
def _safe_history(history):
return list(history or welcome_history())