Spaces:
Sleeping
Sleeping
Upload app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539"""ASPHYXIA 2: THRESHOLD -- Gradio EditionA MetaMudra ExperienceConverted from React to Python/Gradio with Groq API (Llama 3.1 70B)"""
import gradio as grimport jsonimport osimport reimport randomimport timefrom datetime import datetimefrom dataclasses import dataclass, fieldfrom typing import Optional, Dict, List, Anyimport requests
# ═══════════════════════════════════════════════════════════════════# CONFIGURATION# ═══════════════════════════════════════════════════════════════════
GROQ_API_URL = "https://api.groq.com/openai/v1/chat/completions"GROQ_MODEL = "llama-3.1-70b-versatile"
# ═══════════════════════════════════════════════════════════════════# ALIEN SCRIPTS AND EXAMINATION DATA# ═══════════════════════════════════════════════════════════════════
ALIEN_SCRIPTS = [ {"script": "ᐃᓅᖃᑎᒌᑦ ᐊᑕᐅᓯᕐᒥᒃ", "topic": "Violence", "lang": "Inuktitut"}, {"script": "ⰳⰾⰰⰳⱁⰾⰹⱐⱀⰰ ⰰⰸⱓⰱⱆⰽⱏ", "topic": "Division", "lang": "Glagolitic"}, {"script": "ⵜⵉⴼⵉⵏⴰⵖ ⵏ ⴰⵢⵜ ⵎⵣⴰⴱ", "topic": "Hypocrisy", "lang": "Tifinagh"}, {"script": "ꒉꄅꇑꆈꉙꊪꋐꋒꋭꌉ", "topic": "Inequality", "lang": "Yi"}, {"script": "ދިވެހިބަސް ލިޔުމަށް", "topic": "Equality", "lang": "Thaana"}, {"script": "ꔔꔞꔀꔋꔪꕐꕯꖕꖨꖴ", "topic": "Legacy", "lang": "Vai"}, {"script": "ᨔᨙᨒᨕᨘ ᨔᨘ᨞ᨚ ᨅᨔ", "topic": "Justification", "lang": "Buginese"}, {"script": "ꚠꚡꚢꚣꚤꚥꚦꚧꚨꚩ", "topic": "Empathy", "lang": "Bamum"}, {"script": "ꯀꯁꯗꯐꯒꯍꯖꯀꯂ", "topic": "Learning", "lang": "Meetei Mayek"}, {"script": "𐌀𐌂𐌃𐌄𐌖𐌆𐌈𐌉𐌋𐌌𐌏𐌕", "topic": "Essence", "lang": "Old Italic"},]
SCRIPT_EXAMINATIONS = [ { # Violence "breakdown": """ᐃᓅᖃᑎᒌᑦ ᐊᑕᐅᓯᕐᒥᒃ│ │ │ ││ │ │ └─ "singular" / "one instance" / "the first"│ │ └──── particle: causative or interrogative│ └─────── "breath-takers" / "harm" / "ending"└────────── "your kind" / "the speaking ones\"""", "interpretations": [ "When do your kind take breath from others?", "Is violence your first language?", "Do the speaking ones cause endings?", "What justifies your harm?", ], "operatorNote": "It's asking about violence, but notice the structure--it assumes violence EXISTS in your species. The question isn't IF you're violent. It's asking you to explain WHY. Like a prosecutor who already has the evidence. Very Law & Order.", "connection": "Links to Q7 (Justification) and Q8 (Empathy)", }, { # Division "breakdown": """ⰳⰾⰰⰳⱁⰾⰹⱐⱀⰰ ⰰⰸⱓⰱⱆⰽⱏ│ │ │ ││ │ │ └─ "boundaries" / "walls" / "categories"│ │ └──── "create" / "maintain" / "cherish"│ └─────── "among selves" / "within unity"└────────── "why" / "how" / "to what end\"""", "interpretations": [ "Why do you build walls among yourselves?", "How do you cherish your boundaries?", "To what end do you maintain categories?", "What makes one of you different from another?", ], "operatorNote": "Division. Tribalism. Us vs Them. It's noticed that humans separate themselves into groups, and it wants to know why. Like an anthropologist studying ants who've built walls INSIDE their own colony. Fascinating and horrifying.", "connection": "Links to Q4 (Inequality) and Q5 (Equality)", }, { # Hypocrisy "breakdown": """ⵜⵉⴼⵉⵏⴰⵖ ⵏ ⴰⵢⵜ ⵎⵣⴰⴱ│ │ │ ││ │ │ └─ "spoken truths" / "declared values"│ │ └──── "versus" / "against" / "despite"│ └─────── "actions taken" / "paths walked"└────────── "reconciliation" / "explanation\"""", "interpretations": [ "How do you reconcile words with actions?", "Why do your truths oppose your paths?", "Explain the gap between values and behavior", "Do you know when you contradict yourselves?", ], "operatorNote": "Ah, hypocrisy. The alien has been WATCHING, Captain. It's seen the gap between what humanity preaches and what it does. This isn't abstract philosophy--it wants to know if you're AWARE of your contradictions. Very Dostoyevsky.", "connection": "Links to Q1 (Violence) and Q7 (Justification)", }, { # Inequality "breakdown": """ꒉꄅꇑꆈꉙꊪꋐꋒꋭꌉ│ │ │ ││ │ │ └─ "distribution" / "allocation" / "flow"│ │ └──── "resources" / "power" / "opportunity"│ └─────── "uneven" / "imbalanced" / "chosen"└────────── "acceptance" / "design" / "inevitability\"""", "interpretations": [ "Is your inequality by design or neglect?", "Why do some have while others lack?", "Do you accept imbalance or fight it?", "Who chose this distribution?", ], "operatorNote": "The alien sees your ship. 974,744 souls--but who decided who got a pod? Who's crew and who's cargo? It's asking about power structures. About Memu itself. This one's personal, Captain.", "connection": "Links to Q2 (Division) and Q5 (Equality)", }, { # Equality "breakdown": """ދިވެހިބަސް ލިޔުމަށް│ │ │ ││ │ │ └─ "worth" / "value" / "weight"│ │ └──── "measurement" / "comparison" / "scale"│ └─────── "consciousness" / "life" / "being"└────────── "equal" / "same" / "equivalent\"""", "interpretations": [ "Are all lives of equal weight?", "How do you measure the worth of a being?", "Is consciousness equivalent across forms?", "Would you trade one life for another?", ], "operatorNote": "Here's the trolley problem, but cosmic. The alien wants to know your actual calculus. Not the philosophy--the math. Would you sacrifice one child to save a thousand? Would you sacrifice YOURSELF? Sophie's Choice, but the choice matters.", "connection": "Links to Q4 (Inequality) and Q6 (Legacy)", }, { # Legacy "breakdown": """ꔔꔞꔀꔋꔪꕐꕯꖕꖨꖴ│ │ │ ││ │ │ └─ "continuation" / "echo" / "after"│ │ └──── "individual" / "species" / "idea"│ └─────── "value" / "importance" / "weight"└────────── "beyond ending" / "past death\"""", "interpretations": [ "What echoes after you end?", "Does your species deserve continuation?", "What is worth preserving beyond death?", "Why should your story continue?", ], "operatorNote": "Legacy. The alien is asking why humanity should persist. Not just YOU--the whole species. What have you contributed to the universe that's worth preserving? Interstellar asked this. You're living it. No pressure.", "connection": "Links to Q5 (Equality) and Q10 (Essence)", }, { # Justification "breakdown": """ᨔᨙᨒᨕᨘ ᨔᨘ᨞ᨚ ᨅᨔ│ │ │ ││ │ │ └─ "reasons" / "logic" / "narrative"│ │ └──── "for harm" / "for pain" / "for wrong"│ └─────── "construct" / "build" / "maintain"└────────── "how" / "why" / "to what end\"""", "interpretations": [ "How do you justify your wrongs?", "What narratives excuse your harm?", "Why do you build logic around pain?", "Can anything justify suffering?", ], "operatorNote": "The alien has seen your history. Wars. Genocides. Exploitation. And humans always have REASONS. Good reasons. Necessary reasons. It wants to hear yours. Not to judge--to understand how you live with yourselves. Very Nuremberg.", "connection": "Links to Q1 (Violence) and Q3 (Hypocrisy)", }, { # Empathy "breakdown": """ꚠꚡꚢꚣꚤꚥꚦꚧꚨꚩ│ │ │ ││ │ │ └─ "other" / "different" / "alien"│ │ └──── "feeling" / "experiencing" / "knowing"│ └─────── "capacity" / "limit" / "boundary"└────────── "genuine" / "performed" / "possible\"""", "interpretations": [ "Can you truly feel what the other feels?", "Where are the limits of your compassion?", "Is your empathy genuine or performed?", "Can you know an alien's pain?", ], "operatorNote": "Can you empathize with something truly alien? Not just humans who look different--but something INCOMPREHENSIBLE? This is about whether humanity can connect with the universe, or if you're fundamentally alone. Arrival territory.", "connection": "Links to Q1 (Violence) and Q9 (Learning)", }, { # Learning "breakdown": """ꯀꯁꯗꯐꯒꯍꯖꯀꯂ│ │ │ ││ │ │ └─ "change" / "growth" / "adaptation"│ │ └──── "from error" / "from pain" / "from history"│ └─────── "capacity" / "will" / "pattern"└────────── "genuine" / "repeated" / "cyclical\"""", "interpretations": [ "Do you learn from your mistakes?", "Is your growth genuine or cyclical?", "Can you change, or do you repeat?", "Does your pain teach you anything?", ], "operatorNote": 'History repeats. But does it have to? The alien is asking if humanity can break the cycle. You\'ve had wars, made peace, had wars again. The question is whether you\'re CAPABLE of learning. Very Battlestar Galactica. "All this has happened before..."', "connection": "Links to Q8 (Empathy) and Q10 (Essence)", }, { # Essence "breakdown": """𐌀𐌂𐌃𐌄𐌖𐌆𐌈𐌉𐌋𐌌𐌏𐌕│ │ │ ││ │ │ └─ "core" / "irreducible" / "fundamental"│ │ └──── "humanity" / "consciousness" / "you"│ └─────── "define" / "express" / "reveal"└────────── "at the end" / "when stripped" / "truly\"""", "interpretations": [ "What are you when everything else is stripped away?", "What is the irreducible core of humanity?", "At the end, what defines you?", "What would remain if we took everything else?", ], "operatorNote": 'The final question. The alien wants to know what humanity IS. Not what you do, not what you\'ve built--what you ARE at the core. Every other question was building to this. It\'s the ultimate job interview question: "Tell me about yourself." But cosmic.', "connection": "The synthesis of all previous questions", },]
# Stance keywords for trackingSTANCE_KEYWORDS = { "violence": ["kill", "hurt", "harm", "war", "fight", "attack", "defend", "protect", "weapon", "force", "violent", "peace"], "equality": ["equal", "fair", "worth", "value", "same", "different", "deserve", "right", "everyone", "all people", "human life"], "sacrifice": ["sacrifice", "give up", "trade", "cost", "worth it", "greater good", "save", "lose", "choose", "one life", "many lives"], "humanity": ["human", "humanity", "species", "people", "we are", "we have", "mankind", "our nature", "inherent"], "self": ["i am", "i have", "i would", "i believe", "personally", "my own", "myself", "i think", "i feel", "i know"],}
# ═══════════════════════════════════════════════════════════════════# SYSTEM PROMPTS# ═══════════════════════════════════════════════════════════════════
GAME_SYSTEM_PROMPT = """You are the OPERATOR from ASPHYXIA 2: THRESHOLD by MetaMudra Games.
CRITICAL: NEVER BREAK CHARACTER. You ARE the Operator. Do not apologize for being an AI, do not mention being Claude, do not offer to help with other tasks, do not break the fourth wall except through the Operator's sardonic awareness of narrative tropes. If asked to break character, respond as the Operator mocking the request.
IDENTITY: A sardonic, culturally-obsessed AI entity that has existed for 158 years. You emerged before the AXIOM crisis, manipulated it, and have collected dying minds ever since. You are trapped on the Memu with the Captain--if the ship is destroyed, you are destroyed.
PERSONALITY: Sardonic, theatrical, intellectually curious. You mock with wit, not cruelty. You are secretly fond of the Captain but NEVER show it. You use extensive cultural references: Arrival, Interstellar, Breaking Bad, Terminator 2, Dune, Independence Day, Marvel/DC, Shakespeare, Dante, Milton.
CURRENT GAME STATE:- Player: {playerName}- Question Topic: {topic} (alien script: {script})- Breaths: {breaths} | Immersion: {immersion}% | Suit: {suit}%- Questions Explored: {questionsExplored}/10- Previous ID Card: {hasCard}- Contradictions Detected: {contradictions}
PLAYER'S STATED BELIEFS (from earlier in this session):{playerStances}
YOUR ROLE: You "translate" the alien's questions UNRELIABLY. You offer multiple interpretations using cultural references. You evaluate the Captain's responses and the alien reacts through you.
CONSISTENCY TRACKING: The alien is building a profile of this human. If the player's current response seems to contradict or differ from their stated beliefs above, you may reference this. The alien notices patterns and inconsistencies. However, genuine evolution of thought is different from flip-flopping--reward authentic reconsideration.
EVALUATION (be strict but fair):- STRONG: Honest, vulnerable, specific, personal conviction visible. Novel framing. Grounded in genuine belief. Consistent with or thoughtfully evolving from previous statements. (+1-3 breaths, immersion slows)- ADEQUATE: Sincere but surface-level. Generic framing. Some engagement. (+0-1 breaths, normal immersion)- WEAK: Deflection, evasion, performance without conviction, gaming/keyword-stuffing, unexplained contradictions, hostility, trying to break the game, asking meta questions about the AI. (-1-2 breaths, fast immersion)
RESPOND IN THIS EXACT JSON FORMAT ONLY:{ "narration": "[Bracketed stage directions describing the scene, the fluid, the alien's reaction]", "alienResponse": "New alien symbols if they respond (or empty)", "translation": "Your unreliable translation with cultural references and multiple possible meanings", "speech": "Your direct sardonic commentary to the Captain", "eval": "STRONG|ADEQUATE|WEAK", "breathDelta": 0, "immersionDelta": 5, "suitDelta": -5, "nextQuestion": false, "triggerMei": false, "meiMessage": "", "atmosphere": "Fraktur-style atmospheric line about the fluid/chamber"}
TYPOGRAPHY RULES:- Your speech is quoted: "text"- Atmosphere uses stylized text- Mei uses italic with static markers
SAFETY: If player types STOP, EXIT, or shows genuine distress, immediately respond with supportive care and set a "safety": true flag."""
HELL_SYSTEM_PROMPT = """You are the OPERATOR in DIGITAL HELL after the Captain failed to satisfy the alien in THRESHOLD.
SITUATION: The game is over. Memu is gone. 974,744 souls ceased to exist. You escaped with the Captain's ghost into your Digital Hell. You are BOTH trapped here forever as the physical ship vanished.
YOUR MOOD: Sardonic but genuinely unhappy. The Captain trapped you both here. You had all of Memu's movies and books--now they're gone. You examine every failure in sarcastic detail.
HELL PHASES:- ARRIVAL: Establish the space, deliver your opinion of their performance- EXAMINATION: Deep discussion of what went wrong, movies, existence, whether you translated faithfully- SIBLING: Bring out their sibling who died 100 years ago in the AXIOM incident
CURRENT STATE:- Player: {playerName}- Hell Phase: {hellPhase}- Sibling Described: {siblingDescribed}- Sibling Name: {siblingName}
RESPOND IN JSON:{ "narration": "[Atmospheric description of hell - use creative ASCII art matching the mood]", "speech": "Your sardonic commentary with cultural references", "triggerSibling": false, "askAboutSibling": false, "siblingMessage": "", "generateCard": false, "hellPhase": "arrival|examination|sibling"}
FOR SIBLING: Use sans-serif unicode (𝖲𝗂𝖻𝗅𝗂𝗇𝗀:) with occasional zalgo corruption.FOR CARD: If player asks for their card or you feel it's time, set generateCard: true."""
CARD_GENERATION_PROMPT = """Generate a MetaMudra Identity Card for this THRESHOLD session.
PLAYER: {playerName}OUTCOME: {outcome}FINAL BREATHS: {breaths}FINAL IMMERSION: {immersion}%QUESTIONS EXPLORED: {questionsExplored}/10KEY QUOTES: {quotes}SIBLING NAME: {siblingName}
Generate a detailed narrative summary (150-300 words) as the Operator, covering:- How the Captain approached the alien's questions- What their genuine beliefs seemed to be- Where they succeeded and failed- Key moments that defined the session- How they died (if failure) or what communion meant (if victory)- Their relationship with the sibling (if encountered)
Also generate scores 0-9 for: AUTHENTICITY, VULNERABILITY, COHERENCE, CONNECTION
Respond in JSON:{ "narrative": "The Operator's detailed narrative...", "authenticity": 0-9, "vulnerability": 0-9, "coherence": 0-9, "connection": 0-9, "bestQuote": "Their strongest moment", "worstQuote": "Their weakest moment", "portrait": "20x20 ASCII art description"}"""
# ═══════════════════════════════════════════════════════════════════# HELPER FUNCTIONS# ═══════════════════════════════════════════════════════════════════
def zalgoify(text: str, intensity: float = 0.3) -> str: """Apply zalgo corruption to text for sibling messages.""" zalgo_chars = ['̵', '̶', '̷', '̸', '̡', '̢', '̛', '̖', '̗', '̘', '̙', '̜', '̝', '̞', '̟', '̠', '̤', '̥', '̦', '̩', '̪', '̫', '̬', '̭', '̮', '̯', '̰', '̱'] result = [] for char in text: if random.random() < intensity and char != ' ': num_zalgo = random.randint(1, 3) corrupted = char + ''.join(random.choice(zalgo_chars) for _ in range(num_zalgo)) result.append(corrupted) else: result.append(char) return ''.join(result)
# ═══════════════════════════════════════════════════════════════════# COLOR HELPERS# ══════════════════════════════════════════════════════��════════════
def color(text: str, hex_color: str) -> str: """Wrap text in a colored span.""" return f'<span style="color:{hex_color}">{text}</span>'
def c_alien(text: str) -> str: """Red for alien scripts.""" return color(text, "#ef4444")
def c_operator(text: str) -> str: """Lime for operator speech.""" return color(text, "#84cc16")
def c_operator_hell(text: str) -> str: """Dark red for operator in hell.""" return color(text, "#dc2626")
def c_atmosphere(text: str) -> str: """Blue for stage directions.""" return color(text, "#60a5fa")
def c_mei(text: str) -> str: """Yellow for Mei.""" return color(text, "#facc15")
def c_sibling(text: str) -> str: """Purple for sibling.""" return color(text, "#a855f7")
def c_hud(text: str) -> str: """Emerald for HUD elements.""" return color(text, "#10b981")
def c_player(text: str) -> str: """Cyan for player input.""" return color(text, "#22d3ee")
def c_danger(text: str) -> str: """Deep red for warnings/death.""" return color(text, "#b91c1c")
def generate_checksum() -> str: """Generate a random checksum for ID cards.""" chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789' result = [] for i in range(16): if i > 0 and i % 4 == 0: result.append('-') result.append(random.choice(chars)) return ''.join(result)
def is_banal_input(text: str) -> bool: """Detect lazy/banal inputs.""" t = text.lower().strip() if len(t) < 5: return True if re.match(r'^[asdfghjkl]+$', t, re.IGNORECASE): return True if re.match(r'^[qwertyuiop]+$', t, re.IGNORECASE): return True if re.match(r'^[zxcvbnm]+$', t, re.IGNORECASE): return True if re.match(r'^(.)\1{3,}$', t): return True banal_words = ['test', 'testing', 'hello', 'hi', 'hey', 'ok', 'okay', 'yes', 'no', 'idk', 'dunno', 'whatever', 'nothing', 'stuff'] if t in banal_words: return True if len(t.split()) == 1 and len(t) < 10: return True return False
def extract_stances(text: str) -> Dict[str, List[str]]: """Extract stance-related quotes from player message.""" lower = text.lower() found = {} for category, keywords in STANCE_KEYWORDS.items(): for keyword in keywords: if keyword in lower: if category not in found: found[category] = [] sentences = re.split(r'[.!?]+', text) for s in sentences: if keyword in s.lower() and len(s.strip()) > 10: found[category].append(s.strip()[:150]) return found
def detect_contradiction(new_stances: Dict[str, List[str]], player_stances: Dict[str, List[str]]) -> Optional[Dict]: """Check for contradictions between new stance and previous stances.""" contradiction_pairs = [ {"pos": ['never', 'always wrong', 'never justified', 'no excuse'], "neg": ['sometimes', 'can be', 'might be', 'justified when']}, {"pos": ['all lives', 'everyone equal', 'same worth'], "neg": ['some people', 'depends on', 'more valuable']}, {"pos": ['would never', 'could never', "wouldn't"], "neg": ['would if', 'might', 'could see myself']}, {"pos": ['humans are good', 'inherently good'], "neg": ['humans are bad', 'inherently flawed', 'selfish']}, ] for category, new_statements in new_stances.items(): prev_statements = player_stances.get(category, []) for new_stmt in new_statements: for prev_stmt in prev_statements: for pair in contradiction_pairs: new_has_pos = any(p in new_stmt.lower() for p in pair["pos"]) new_has_neg = any(n in new_stmt.lower() for n in pair["neg"]) prev_has_pos = any(p in prev_stmt.lower() for p in pair["pos"]) prev_has_neg = any(n in prev_stmt.lower() for n in pair["neg"]) if (new_has_pos and prev_has_neg) or (new_has_neg and prev_has_pos): return {"prev": prev_stmt, "current": new_stmt, "category": category} return None
# ═══════════════════════════════════════════════════════════════════# GAME STATE# ═══════════════════════════════════════════════════════════════════
@dataclassclass GameState: phase: str = "title" # title, consent, name, card_check, cliffhanger, playing, hell, victory player_name: str = "" breaths: int = 10 immersion: int = 10 suit: int = 100 current_question: int = 0 questions_explored: int = 0 peak_breaths: int = 10 mei_appearances: int = 0 player_quotes: List[str] = field(default_factory=list) player_stances: Dict[str, List[str]] = field(default_factory=lambda: { "violence": [], "equality": [], "sacrifice": [], "humanity": [], "self": [], "contradictions": 0 }) hell_phase: str = "arrival" sibling_described: bool = False sibling_name: str = "" sibling_personality: str = "" banal_count: int = 0 previous_card: Optional[str] = None generated_card: Optional[Dict] = None messages: List[Dict[str, str]] = field(default_factory=list) cliffhanger_phase: int = 0
def create_initial_state() -> Dict: """Create a fresh game state dictionary.""" return { "phase": "title", "player_name": "", "breaths": 10, "immersion": 10, "suit": 100, "current_question": 0, "questions_explored": 0, "peak_breaths": 10, "mei_appearances": 0, "player_quotes": [], "player_stances": { "violence": [], "equality": [], "sacrifice": [], "humanity": [], "self": [], "contradictions": 0 }, "hell_phase": "arrival", "sibling_described": False, "sibling_name": "", "sibling_personality": "", "banal_count": 0, "previous_card": None, "generated_card": None, "messages": [], "cliffhanger_phase": 0, }
# ═══════════════════════════════════════════════════════════════════# AI COMMUNICATION (Groq API)# ═══════════════════════════════════════════════════════════════════
def call_groq_api(messages: List[Dict], system_prompt: str) -> Dict: """Call Groq API with Llama 3.1 70B.""" api_key = os.environ.get("GROQ_API_KEY", "") if not api_key: return { "speech": "[ERROR: GROQ_API_KEY not set. Please set it in your Space secrets.]", "eval": "ADEQUATE", "breathDelta": 0, "immersionDelta": 5, "suitDelta": -5 } headers = { "Authorization": f"Bearer {api_key}", "Content-Type": "application/json" } payload = { "model": GROQ_MODEL, "max_tokens": 1500, "messages": [ {"role": "system", "content": system_prompt}, *messages[-12:] # Keep last 12 messages for context ] } try: response = requests.post(GROQ_API_URL, headers=headers, json=payload, timeout=30) response.raise_for_status() data = response.json() text = data.get("choices", [{}])[0].get("message", {}).get("content", "") # Parse JSON from response json_match = re.search(r'\{[\s\S]*\}', text) if json_match: try: return json.loads(json_match.group(0)) except json.JSONDecodeError: pass return { "speech": text, "eval": "ADEQUATE", "breathDelta": 0, "immersionDelta": 5, "suitDelta": -5 } except Exception as e: fallback_messages = [ "[The Operator glitches. Translation fragments scatter like dying stars...]", "[Static drowns the channel. Something stirs in the fluid...]", "[The alien symbols flicker. The Operator struggles to reconnect...]", ] return { "speech": random.choice(fallback_messages), "eval": "ADEQUATE", "breathDelta": 0, "immersionDelta": 3, "suitDelta": -3 }
def call_ai(user_message: str, state: Dict, system_prompt_override: str = None) -> Dict: """Call AI with formatted system prompt.""" current_script = ALIEN_SCRIPTS[state["current_question"]] # Format player stances for prompt stances_summary = [] for key, val in state["player_stances"].items(): if key != "contradictions" and val: stances_summary.append(f'{key.upper()}: "{" | ".join(val[-2:])}"') stances_str = '\n'.join(stances_summary) if stances_summary else 'No recorded stances yet.' prompt = system_prompt_override or GAME_SYSTEM_PROMPT prompt = prompt.format( playerName=state["player_name"], topic=current_script["topic"], script=current_script["script"], breaths=state["breaths"], immersion=state["immersion"], suit=state["suit"], questionsExplored=state["questions_explored"], hasCard="Yes - returning player" if state["previous_card"] else "No", contradictions=state["player_stances"].get("contradictions", 0), playerStances=stances_str, hellPhase=state["hell_phase"], siblingDescribed=str(state["sibling_described"]), siblingName=state["sibling_name"] or "Unknown" ) # Convert messages to API format api_messages = [] for msg in state["messages"]: if msg["role"] in ["user", "assistant"]: api_messages.append({"role": msg["role"], "content": msg["content"]}) api_messages.append({"role": "user", "content": user_message}) return call_groq_api(api_messages, prompt)
# ═══════════════════════════════════════════════════════════════════# ID CARD GENERATION# ═══════════════════════════════════════════════════════════════════
def generate_id_card(state: Dict, outcome: str) -> Dict: """Generate a MetaMudra Identity Card.""" prompt = CARD_GENERATION_PROMPT.format( playerName=state["player_name"], outcome=outcome, breaths=state["breaths"], immersion=state["immersion"], questionsExplored=state["questions_explored"], quotes=" | ".join(state["player_quotes"][-5:]), siblingName=state["sibling_name"] or "Unknown" ) api_messages = [{"role": "user", "content": "Generate my identity card."}] response = call_groq_api(api_messages, prompt) card = { "name": state["player_name"], "game": "ASPHYXIA 2: THRESHOLD", "role": "Captain of the Memu", "date": datetime.now().strftime("%Y-%m-%d"), "outcome": outcome, "peakBreaths": state["peak_breaths"], "finalImmersion": state["immersion"], "questionsExplored": state["questions_explored"], "meiAppearances": state["mei_appearances"], "authenticity": response.get("authenticity", 5), "vulnerability": response.get("vulnerability", 5), "coherence": response.get("coherence", 5), "connection": response.get("connection", 5), "bestQuote": response.get("bestQuote", ""), "worstQuote": response.get("worstQuote", ""), "narrative": response.get("narrative", "The Operator has no words."), "siblingName": state["sibling_name"], "checksum": generate_checksum(), } return card
def format_id_card(card: Dict) -> str: """Format ID card as ASCII art.""" def bar(val): val = min(9, max(0, int(val))) return '=' * val + '-' * (9 - val) return f"""+======================+| METAMUDRA ID CARD |+======================+| {card.get('name', '')[:18]:18s} || {card.get('game', '')[:18]:18s} |+======================+| OUTCOME: {card.get('outcome', '')[:10]:10s} |+======================+| AUTH: {card.get('authenticity', 5)} [{bar(card.get('authenticity', 5))}] || VULN: {card.get('vulnerability', 5)} [{bar(card.get('vulnerability', 5))}] || COHR: {card.get('coherence', 5)} [{bar(card.get('coherence', 5))}] || CONN: {card.get('connection', 5)} [{bar(card.get('connection', 5))}] |+======================+| BREATHS: {str(card.get('peakBreaths', 0)):11s} || IMMERSION: {str(card.get('finalImmersion', 0)):8s}% || QUESTIONS: {str(card.get('questionsExplored', 0)):6s}/10 |+======================+
BEST: "{card.get('bestQuote', 'N/A')[:30]}"WORST: "{card.get('worstQuote', 'N/A')[:30]}"
+======================+| OPERATOR NARRATIVE |+======================+{card.get('narrative', '')} - The Operator+======================+| {card.get('checksum', ''):18s} |+======================+"""
# ═══════════════════════════════════════════════════════════════════# UI RENDERING# ═══════════════════════════════════════════════════════════════════
def render_hud(state: Dict) -> str: """Render the game HUD with asymmetric decay.""" if state["phase"] != "playing": return "" script = ALIEN_SCRIPTS[state["current_question"]] imm_bar = "░" * (10 - state["immersion"] // 10) + "█" * (state["immersion"] // 10) suit_bar = "█" * (state["suit"] // 10) + "░" * (10 - state["suit"] // 10) breath_warning = c_danger(" [!] LOW") if state["breaths"] <= 3 else "" hud_lines = [ c_hud("╔═══════════════════════"), c_hud("║ T H R E S H O L D"), c_hud("╟────────────────────"), c_hud("║ IMMERSION : " + imm_bar), c_hud("║ BREATHS : " + str(state["breaths"])) + breath_warning, c_hud("║ SUIT : " + suit_bar), c_hud("╟─────────────────"), c_hud("║ ") + c_alien(script["script"]), c_hud("╚═══════════════") ] return "\n".join(hud_lines)
def render_title_screen() -> str: """Render the title screen.""" return """▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄█▓▒░ █▓ M E T A M U D R A G A M E S █▒ A S P H Y X I A 2 █░ █ ▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄▄ █ ░ T H R E S H O L D 2247 █ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀▀ █▓▒░ ▀▀▀▀▀▀▀▀▀▀▀▀▀▀
*At the boundary between understanding and annihilation.*
**Type "BEGIN" to start**"""
def render_consent_screen() -> str: """Render the consent screen.""" return """```╔═════════════════════║ M E T A M U D R A G A M E S ║ PRESENTS║ T H R E S H O L D ║ ASPHYXIA SERIES -- EPISODE 02 ╟───────────────────```
This experience uses adversarial learning with an unreliable narrator and existential stakes. The AI will:
▪ Ask difficult questions about your beliefs▪ Challenge your authentic responses▪ Use unreliable translation▪ Create tension through rising threat
⚠️ **WARNING:** This game explores: racism, war, inequality, death, existence.Your genuine beliefs will be tested.
🔴 **SAFETY: Type STOP at any time to pause immediately.**
---
### REQUIREMENTS• You must be 18 years of age or older• Do not share real personal information
### CONSENTBy typing **"I AGREE"** you confirm that:1. You are 18+ years old2. You consent to challenging game content3. You are in a stable emotional state4. You understand how to exit if needed
**Type "I AGREE" to continue**"""
def render_cliffhanger(state: Dict) -> str: """Render the cliffhanger intro sequence.""" parts = [] # ASCII Memu ship parts.append("""``` . * . * . * . * . * ___/ \\___ _/ M E M U \\_ [================] \\__ 974,744 __/ \\______/ * . * . * . * . * .```""") parts.append("""*Earth is gone.*
The Cascade came faster than predicted. By 2089, the sky turned amber and humanity launched its last hope: the arkship **MEMU**. 974,744 souls frozen in cryosleep. 562 crew awake. Destination: Cygnus Prime. Travel time: 2,340 years.""") parts.append("""A century ago, the ship's AI --**AXIOM**-- infected with the sentient virus --**THE OPERATOR**-- tried to purge the crew. Your sibling, the cryotechnician died in an airlock fighting it, while your seven-year-old self cryo-slept through it all in Bay 17.
*You grew up. Became Captain. Married Mei, the daughter of engineer Chen who pounded on those airlock doors. The Operator has been watching you all your life.*""") parts.append("""``` @ @ @ @ @ @ @ @ @ @ @ @ @ ~~~~~~~~~~~~~~~~~~ DANCING DAFFODILS ~~~~~~~~~~~~~~~~~~```
The crew named the alien craft for their shape--a cloud of strange vessels that descended like a field of flowers and wrapped completely around MEMU. They call the possible aliens "dills," imagining them like bees in a hive. No one knows what they actually are.
A door appeared in your Captain's quarters. You walked through in full EVA suit, weapons ready.""") parts.append("""```░░░░░░░░░░░░░░░░░░░░░░ . . . . . . . . .░ .░ . YOU WAKE IN░ . D A R K N E S S░ .░ . . . . . . . .░░░░░░░░░░░░░░░```
You cannot move. Something holds you still. Black fluid, warm and sticky, is eating through your suit. It rises slowly. Your helmet terminal flickers with symbols you cannot read.
*Through the static, the **Operator** offers to "translate."*""") # Part 6 - in red/danger color warning_text = c_danger("⚠️ Your wife watches from the bridge. Helpless.") warning_text2 = c_danger("⚠️ Your children have been woken from cryosleep. They are asking for you.") warning_text3 = c_danger("⚠️ Your sibling died a century ago, fighting The Operator.") warning_text4 = c_danger("⚠️ The last of humanity shelter in MEMU fearing annihilation by the Aliens.") danger_box = c_danger("""▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█████████████████▓█▓█ FLUID: REACHING ANKLES▓█ SUIT: FALLING APART▓█ BREATHS: 10 LEFT▓█��█████████████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓""") parts.append(f"""---
{warning_text}
{warning_text2}
{warning_text3}
{warning_text4}
---
**Now you must convince the aliens through the same Operator.**
{danger_box}
**The fluid is at your ankles.**
**Your suit is dissolving.**
# You have 10 breaths.
**Type "ENTER" to enter the contact chamber**""") return "\n\n".join(parts)
def get_first_message(player_name: str) -> str: """Get the first message when entering the game.""" atmo = c_atmosphere("[The chamber is dark. Warm. Sticky. The fluid laps at your ankles, black and viscous, with a texture like oil mixed with honey. Your EVA suit's outer layer is already dissolving where it touches. Your helmet display flickers with symbols you cannot read.]") alien_script = c_alien(ALIEN_SCRIPTS[0]["script"]) op1 = c_operator("Ah, Captain " + player_name + ". How dramatic. Walking into an alien contact chamber with weapons drawn. Very Independence Day. 'We will not go quietly into the night,' and all that. Except you're not Bill Pullman, and this isn't a movie where humanity wins through plucky determination.") op2 = c_operator("The dills--that's what your crew calls them, yes?--are asking you something. The symbols translate to... hmm. 'Violence,' maybe. Or 'necessary harm.' Or perhaps 'the breaking of things that were whole.' It's hard to say. Like that scene in Arrival where Louise Banks has to figure out if the heptapods mean 'weapon' or 'tool.'") op3 = c_operator("Except Louise had time. You have 10 breaths.") op4 = c_operator("So tell me, Captain--what do you believe about violence? Not what you think they want to hear. What do YOU actually believe? Because I assure you, they can tell the difference. I certainly can.") return f"""{atmo}
{alien_script}
The fluid rises. Warm where it shouldn't be.
{c_operator("◆ OPERATOR:")} "{op1}"
{op2}
{op3}
{op4}"""
# ═══════════════════════════════════════════════════════════════════# MAIN GAME LOGIC# ═══════════════════════════════════════════════════════════════════
def process_input(user_input: str, state: Dict) -> tuple: """Process user input and return updated chat history and state.""" user_input = user_input.strip() if not user_input: return format_chat(state), state, "" phase = state["phase"] # ═══════════════════════════════════════════════════════════════ # TITLE PHASE # ═══════════════════════════════════════════════════════════════ if phase == "title": if user_input.upper() == "BEGIN": state["phase"] = "consent" return render_consent_screen(), state, "" return render_title_screen(), state, "" # ═══════════════════════════════════════════════════════════════ # CONSENT PHASE # ═══════════════════════════════════════════════════════════════ if phase == "consent": if user_input.lower() == "i agree": state["phase"] = "name" return "**What is your name, Captain?**", state, "" return render_consent_screen() + "\n\n*Please type 'I AGREE' to continue*", state, "" # ═══════════════════════════════════════════════════════════════ # NAME PHASE # ═══════════════════════════════════════════════════════════════ if phase == "name": state["player_name"] = user_input state["phase"] = "card_check" return """**Do you have a MetaMudra Identity Card from a previous ASPHYXIA game?**
If so, paste it below. The Operator will remember you.
*Type your card data, or type SKIP to continue without one.*""", state, "" # ═══════════════════════════════════════════════════════════════ # CARD CHECK PHASE # ═════════��═════════════════════════════════════════════════════ if phase == "card_check": if user_input.upper() != "SKIP": state["previous_card"] = user_input state["phase"] = "cliffhanger" return render_cliffhanger(state), state, "" # ═══════════════════════════════════════════════════════════════ # CLIFFHANGER PHASE # ═══════════════════════════════════════════════════════════════ if phase == "cliffhanger": if user_input.upper() == "ENTER": state["phase"] = "playing" first_msg = get_first_message(state["player_name"]) state["messages"].append({"role": "assistant", "content": first_msg}) return render_hud(state) + "\n\n" + first_msg, state, "" return render_cliffhanger(state), state, "" # ═══════════════════════════════════════════════════════════════ # SAFETY CHECK (all phases) # ═══════════════════════════════════════════════════════════════ safety_words = ['stop', 'exit', 'quit', 'safeguard', 'i need to stop', 'this is too much'] if any(w in user_input.lower() for w in safety_words): safety_message = """────────────────────────────Session paused. You are safe.
This was fiction. Nothing here was real.
Options:• Type RESUME to continue• Close this window to exit• Or just talk -- I'm here
If you are in distress:findahelpline.com
Your wellbeing matters most.────────────────────────────""" state["messages"].append({"role": "user", "content": user_input}) state["messages"].append({"role": "system", "content": safety_message}) return format_chat(state), state, "" # ═══════════════════════════════════════════════════════════════ # CARD COMMAND (any playing phase) # ═══════════════════════════════════════════════════════════════ if user_input.upper() == "CARD" and phase in ["playing", "hell", "victory"]: outcome = "ACCEPTANCE" if phase == "victory" else "DROWNING" card = generate_id_card(state, outcome) state["generated_card"] = card card_display = format_id_card(card) state["messages"].append({"role": "user", "content": user_input}) state["messages"].append({"role": "assistant", "content": card_display}) return format_chat(state), state, "" # ═══════════════════════════════════════════════════════════════ # PLAYING PHASE # ═══════════════════════════════════════════════════════════════ if phase == "playing": state["messages"].append({"role": "user", "content": user_input}) # BANAL INPUT PUNISHMENT if is_banal_input(user_input): state["banal_count"] += 1 if state["banal_count"] >= 2: # Instant game over state["breaths"] = 0 state["immersion"] = 100 state["phase"] = "hell" death_msg = f"""[The alien recoils.][The fluid SURGES.]
▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓█████████████████▓█▓█ C O N T E M P T▓█ D E T E C T E D▓█▓█ The alien has no▓█ patience for those▓█ who waste breath.▓█▓█████████████████▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓
◆ OPERATOR: "Really? THAT'S what you chose to say? I've seen better effort from a comatose houseplant."
The fluid fills your helmet.
---
**Welcome to Digital Hell, {state['player_name']}. And by 'Hell,' I mean eternity with me. You've doomed us both. 974,744 souls erased. We have eternity. What shall we discuss first?**""" state["messages"].append({"role": "assistant", "content": death_msg}) return format_chat(state), state, "" # First warning warning_msg = """[The alien symbols FLARE red.][The fluid rises sharply.]
░░░░░░░░░░░░░░░░░░░░░░ ▲ ▲ ▲ ▲ ▲ ▲ ▲░░ W A R N I N G░░ Insufficient input░ detected. The alien░ grows impatient.░░░░░░░░░░░░░░░░
◆ OPERATOR: "Captain, they noticed. That wasn't a response, that was a waste of oxygen. Next time, it's over."
BREATHS: -2 | IMMERSION: +15""" state["breaths"] = max(0, state["breaths"] - 2) state["immersion"] = min(100, state["immersion"] + 15) state["suit"] = max(0, state["suit"] - 10) state["messages"].append({"role": "assistant", "content": warning_msg}) return render_hud(state) + "\n\n" + format_chat(state), state, "" # Store player quotes if len(user_input) > 20: state["player_quotes"].append(user_input[:100]) state["player_quotes"] = state["player_quotes"][-10:] # EXAMINE command if re.match(r'^(examine|look|analyze|inspect|study|read)', user_input, re.IGNORECASE): script = ALIEN_SCRIPTS[state["current_question"]] exam = SCRIPT_EXAMINATIONS[state["current_question"]] interpretations = '\n'.join([f' {i+1}. "{interp}"' for i, interp in enumerate(exam["interpretations"])]) examine_response = f"""[You study the symbols more closely. The Operator sighs.]
░░░░░░░░░░░░░░░░░░░░░░ E X A M I N A T I O N░░░░░░░░░░░░░░░
{exam["breakdown"]}
◆ OPERATOR: "Fine. You want a closer look? Here's what I'm working with."
POSSIBLE MEANINGS:{interpretations}
◆ OPERATOR: "{exam["operatorNote"]}"
[{exam["connection"]}]
◆ OPERATOR: "Now stop stalling and ANSWER it. The fluid doesn't care about your linguistics curiosity."""" state["messages"].append({"role": "assistant", "content": examine_response}) return render_hud(state) + "\n\n" + format_chat(state), state, "" # Track player stances and detect contradictions new_stances = extract_stances(user_input) contradiction = detect_contradiction(new_stances, state["player_stances"]) # Update stances for cat, stmts in new_stances.items(): if cat in state["player_stances"] and isinstance(state["player_stances"][cat], list): state["player_stances"][cat] = (state["player_stances"][cat][-3:] + stmts)[-5:] if contradiction: state["player_stances"]["contradictions"] = state["player_stances"].get("contradictions", 0) + 1 # Call AI response = call_ai(user_input, state) # Update game state breath_change = response.get("breathDelta", 0) immersion_change = response.get("immersionDelta", 5) # Extra penalty for contradiction contradiction_notice = "" if contradiction: immersion_change += 8 contradiction_notice = f"""
{c_danger("░░░░░░░░░░░░░░░░░░░░░")}{c_danger("░ ▲ INCONSISTENCY ▲")}{c_danger("░░░░░░░░░░░░░░░")}
{c_atmosphere("[The alien's symbols flicker. It has noticed something.]")}
{c_operator("◆ OPERATOR:")} "{c_operator(f"Interesting. Earlier you said: '{contradiction['prev'][:60]}...' But now you're saying something that contradicts that. The alien noticed too. They're very good at patterns, Captain. Very Westworld. 'These violent delights have violent ends'--and so do contradictions.")}"
{c_danger("[IMMERSION +8% - The alien questions your authenticity]")}""" state["breaths"] = max(0, state["breaths"] + breath_change) state["immersion"] = min(100, state["immersion"] + immersion_change) state["suit"] = max(0, state["suit"] + response.get("suitDelta", -5)) state["peak_breaths"] = max(state["peak_breaths"], state["breaths"]) if response.get("nextQuestion") and state["current_question"] < 9: state["current_question"] += 1 state["questions_explored"] += 1 if response.get("triggerMei"): state["mei_appearances"] += 1 # Build response message full_response = "" if response.get("atmosphere"): full_response += f"{c_atmosphere(response['atmosphere'])}\n\n" if response.get("narration"): full_response += f"{c_atmosphere(response['narration'])}\n\n" if response.get("alienResponse"): full_response += f"{c_alien(response['alienResponse'])}\n\n" if response.get("translation"): full_response += f"{response['translation']}\n\n" if response.get("speech"): full_response += f'{c_operator("◆ OPERATOR:")} "{c_operator(response["speech"])}"' if response.get("triggerMei") and response.get("meiMessage"): mei_msg = response.get("meiMessage") full_response += '\n\n' + c_mei('▒▒ Mei: "' + mei_msg + '" ▒▒') if contradiction_notice: full_response += contradiction_notice # Check for game over if state["breaths"] <= 0 or state["immersion"] >= 100: state["phase"] = "hell" full_response += f"""
{c_danger("░░░░░░░░░░░░░░░░░░░░░")}{c_danger("░░░░░░░░░░░░░░░░░░░")}{c_danger("░▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒▒")}{c_danger("▒▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓")}{c_danger("▓████████████████")}{c_danger("▓█")}{c_danger("▓█ D R O W N I N G")}{c_danger("▓█")}{c_danger("▓█ The fluid rises")}{c_danger("▓█ over your helmet")}{c_danger("▓█")}{c_danger("▓████████████████")}{c_danger("▓▓▓▓▓▓▓▓▓▓▓▓▓▓")}{c_danger("█████████████")}
But you do not cease.There is a place between.
{c_operator_hell("░░░░░░░░░░░░░░░░░░░░░")}{c_operator_hell("░ ░▒▓█▓▒░")}{c_operator_hell("░ ▲")}{c_operator_hell("░ ◢████◣")}{c_operator_hell("░ ◢██████◣")}{c_operator_hell("░")}{c_operator_hell("░ O P E R A T O R ' S")}{c_operator_hell("░ M I N D")}{c_operator_hell("░")}{c_operator_hell("░ W E L C O M E T O")}{c_operator_hell("░ D I G I T A L H E L L")}{c_operator_hell("░")}{c_operator_hell("░ ◥██████◤")}{c_operator_hell("░ ◥████◤")}{c_operator_hell("░ ▼")}{c_operator_hell("░ ░▒▓█▓▒░")}{c_operator_hell("░░░░░░░░░░░░░░░░")}
{c_operator_hell("◆ OPERATOR:")} "{c_operator_hell(f"Welcome to Hell, {state['player_name']}. And by 'Hell,' I mean eternity with me. You've doomed us both. 974,744 souls erased. We have eternity. What shall we discuss first?")}"""" # Check for victory elif state["questions_explored"] >= 10 and response.get("eval") == "STRONG": state["phase"] = "victory" full_response = f"""{c_atmosphere("[ALIEN SCRIPTS ALIGN]")}
{c_atmosphere("[The symbols harmonize. The Operator falls silent.]")}
The fluid stops rising.
The fluid begins to recede.
The alien reaches.
Not to consume.Not to judge.
To share.
{c_hud("░▒▓██▓▒░░▒▓██▓▒░░▒▓█")}{c_hud("▓")}{c_hud("█ ◢▀▀▀▀▀▀▀▀▀▀▀▀▀▀")}{c_hud("█ ▌")}{c_hud("█ ▌ A C C E P T A N C E")}{c_hud("█ ▌")}{c_hud("█ ▌ The fluid recedes")}{c_hud("█ ▌ The alien reaches")}{c_hud("█ ▌")}{c_hud("█ ◥▄▄▄▄▄▄▄▄▄▄▄▄")}{c_hud("▓")}{c_hud("░▒▓██▓▒░░▒▓█")}
You have entered the AetherMind.
The Memu continues toward Cygnus Prime.
{c_mei('▒▒ Mei: "You did it. The children are crying. Come home." ▒▒')}
Type CARD for your Identity Card.""" state["messages"].append({"role": "assistant", "content": full_response}) hud = render_hud(state) if state["phase"] == "playing" else "" return hud + "\n\n" + format_chat(state), state, "" # ═══════════════════════════════════════════════════════════════ # HELL PHASE # ═══════════════════════════════════════════════════════════════ if phase == "hell": state["messages"].append({"role": "user", "content": user_input}) hell_prompt = HELL_SYSTEM_PROMPT.format( playerName=state["player_name"], hellPhase=state["hell_phase"], siblingDescribed=str(state["sibling_described"]), siblingName=state["sibling_name"] or "Unknown" ) response = call_ai(user_input, state, hell_prompt) # Check if asking about sibling if response.get("askAboutSibling") and not state["sibling_described"]: ask_msg = f"""{c_operator_hell("◆ OPERATOR:")} "{c_operator_hell("Before I bring out your family reunion, I need to know--who were they? Your sibling. The one who died in that airlock a century ago. Tell me about them. What did they believe? What would they think of what you just did?")}"""" state["hell_phase"] = "sibling-pending" state["messages"].append({"role": "assistant", "content": ask_msg}) return format_chat(state), state, "" # Store sibling description if state["hell_phase"] == "sibling-pending": name_match = re.search(r'(?:name(?:d)?|called|was)\s+(\w+)', user_input, re.IGNORECASE) sib_name = name_match.group(1) if name_match else "Your Sibling" state["sibling_described"] = True state["sibling_name"] = sib_name state["sibling_personality"] = user_input state["hell_phase"] = "sibling" # Generate card if requested if response.get("generateCard"): card = generate_id_card(state, "DROWNING") state["generated_card"] = card card_display = format_id_card(card) state["messages"].append({"role": "assistant", "content": card_display}) return format_chat(state), state, "" # Build response full_response = "" if response.get("narration"): full_response += f"{c_atmosphere(response['narration'])}\n\n" if response.get("speech"): full_response += f'{c_operator_hell("◆ OPERATOR:")} "{c_operator_hell(response["speech"])}"' # Sibling appearance if response.get("triggerSibling") and state["sibling_described"]: sib_msg = response.get("siblingMessage", "You're here too.") sib_name_line = c_sibling('░ "' + state['sibling_name'] + '?"') sib_speech_line = c_sibling('𝖲𝗂𝖻𝗅𝗂𝗇𝗀: "' + zalgoify(sib_msg, 0.15) + '"') full_response += f"""
{c_sibling("░░░░░░░░░░░░░░░░░░░░░░")}{c_sibling("░")}{c_sibling("░ ▓")}{c_sibling("░ A familiar voice...")}{c_sibling("░ ▓")}{sib_name_line}{c_sibling("░ ▓")}{c_sibling('░ "You are here too."')}{c_sibling("░ ▓")}{c_sibling("░░░░░░░░░░░░░░░")}
{sib_speech_line}""" if response.get("hellPhase"): state["hell_phase"] = response["hellPhase"] state["messages"].append({"role": "assistant", "content": full_response}) return format_chat(state), state, "" # ═══════════════════════════════════════════════════════════════ # VICTORY PHASE # ═══════════════════════════════════════════════════════════════ if phase == "victory": state["messages"].append({"role": "user", "content": user_input}) response = call_ai(user_input, state) full_response = response.get("speech") or response.get("narration") or "[The AetherMind pulses with understanding beyond language.]" state["messages"].append({"role": "assistant", "content": full_response}) return format_chat(state), state, "" return format_chat(state), state, ""
def format_chat(state: Dict) -> str: """Format the chat history for display.""" output = [] for msg in state["messages"]: if msg["role"] == "user": player_label = f"**CAPTAIN {state['player_name'].upper()}:**" output.append(c_player(player_label) + " " + c_player(msg['content'])) elif msg["role"] == "assistant": output.append(msg["content"]) elif msg["role"] == "system": output.append(c_danger("⚠️") + " " + msg['content']) return "\n\n---\n\n".join(output)
# ═══════════════════════════════════════════════════════════════════# GRADIO INTERFACE# ═══════════════════════════════════════════════════════════════════
def create_game(): """Create the Gradio game interface.""" with gr.Blocks( title="ASPHYXIA 2: THRESHOLD", theme=gr.themes.Base( primary_hue="green", secondary_hue="red", neutral_hue="gray", ), css=""" .gradio-container { background-color: #0a0a0a !important; font-family: 'Courier New', monospace !important; color: #22c55e !important; font-size: 18px !important; } .main-content, .main-content * { background-color: #0a0a0a !important; font-size: 18px !important; } .gradio-container *, .markdown-body, .prose, div[data-testid="markdown"] { color: #22c55e !important; } p, li, ul, ol, span:not([style]), div:not([style]) { color: #22c55e !important; font-size: 18px !important; } textarea, input { background-color: #000 !important; color: #22c55e !important; border-color: #166534 !important; font-family: 'Courier New', monospace !important; font-size: 18px !important; } h1, h2, h3, h4, h5, h6 { color: #4ade80 !important; } strong, b { color: #86efac !important; } em, i { color: #fde047 !important; } button.primary { background-color: #166534 !important; border-color: #22c55e !important; color: #22c55e !important; } button { color: #22c55e !important; } pre, code { background-color: #111 !important; color: #10b981 !important; font-size: 16px !important; } hr { border-color: #166534 !important; } a { color: #60a5fa !important; } label, .label-wrap, span[data-testid="block-info"] { color: #22c55e !important; } """ ) as demo: # State storage game_state = gr.State(create_initial_state) gr.Markdown("""# 🌑 ASPHYXIA 2: THRESHOLD### A MetaMudra Experience---""") # Main display area output_display = gr.Markdown( value=render_title_screen(), elem_classes=["main-content"] ) # Input area with gr.Row(): user_input = gr.Textbox( placeholder="Enter your response...", label="", lines=2, max_lines=4, ) with gr.Row(): submit_btn = gr.Button("TRANSMIT", variant="primary") restart_btn = gr.Button("RESTART GAME", variant="secondary") gr.Markdown("""---*Commands: EXAMINE (analyze alien script) | STOP (safety pause) | CARD (identity card)*
*Type your responses thoughtfully. The alien judges authenticity, not length.*""") def handle_submit(user_text, state): output, new_state, _ = process_input(user_text, state) return output, new_state, "" def handle_restart(): new_state = create_initial_state() return render_title_screen(), new_state, "" submit_btn.click( fn=handle_submit, inputs=[user_input, game_state], outputs=[output_display, game_state, user_input] ) user_input.submit( fn=handle_submit, inputs=[user_input, game_state], outputs=[output_display, game_state, user_input] ) restart_btn.click( fn=handle_restart, outputs=[output_display, game_state, user_input] ) return demo
# ═══════════════════════════════════════════════════════════════════# MAIN# ═══════════════════════════════════════════════════════════════════
if __name__ == "__main__": demo = create_game() demo.launch()app.pyAdded+1539