import gradio as gr import spaces import json import textwrap from gradio_client import Client import os import requests from huggingface_hub import InferenceClient from openai import OpenAI #Imported Long Variables - comment for each move to search from relatively_constant_variables import * from leveraging_machine_learning import * from jsconfig_idea_support import * from timeline_and_UI_generation_functions import * from my_text_game_engine_attempt import * from file_explorer_and_upload import * from state_prompt_fileman_UI_functions import * from ui_gr_media_management import * from timeline_narrative_construction_tools import * from bible_as_inspiration_source import * from config_linting import ( validate_branching, generate_story_flags, generate_mermaid_diagram, get_config_health_summary, get_llm_cohesion_prompts, get_validation_with_fixes, apply_all_quick_fixes, format_issues_for_display, get_state_issues_map ) from timeline_and_UI_generation_functions import ( NARRATIVE_TEMPLATES, get_narrative_templates_list, generate_config_from_template, generate_config_from_prompt ) from my_text_game_engine_attempt import ( get_all_states_from_config, jump_to_state, hot_reload_config, get_current_state_id, make_choice_with_state_display, export_playthrough_log, get_initgameinfo, get_path_errors ) from ui_tabs.big_rpg_scale_tab import EntityDatabase # LinPEWFprevious_messages = [] # FILM_SCENARIOS and generate_scenario_sequence moved to film_scenarios.py # ==================== DEMO CONFIGS ==================== SANDWICH_DEMO_CONFIG = { "game_start": { "intro": { "description": "**Sandwich Quest**\n\nYou're hungry! Time to get a sandwich from Tony's shop.", "choices": ["Start adventure"], "transitions": {"Start adventure": "home/start"}, "on_enter": {"set_money": 20, "start_mission": "get_lunch"} } }, "home": { "start": { "description": "**Your Home**\n\nYour stomach growls. The fridge is empty.\n\nYou have 20 gold.", "choices": ["Go outside", "Check wallet"], "transitions": {"Go outside": "street/arrive", "Check wallet": "home/wallet"} }, "wallet": { "description": "You check your wallet. **20 gold** - enough for a sandwich!", "choices": ["Go outside"], "transitions": {"Go outside": "street/arrive"} } }, "street": { "arrive": { "description": "**Main Street**\n\nPeople walk by. You see Tony's Sandwich Shop ahead.\n\nMrs. Jenkins waves at you.", "choices": ["Enter sandwich shop", "Talk to Mrs. Jenkins", "Go home"], "transitions": { "Enter sandwich shop": "sandwich_shop/arrive", "Talk to Mrs. Jenkins": "street/jenkins", "Go home": "home/start" } }, "jenkins": { "description": "**Mrs. Jenkins** smiles.\n\n\"Hello dear! Getting lunch? Tony makes the best sandwiches!\"", "choices": ["Thanks for the tip!", "Goodbye"], "transitions": {"Thanks for the tip!": "street/arrive", "Goodbye": "street/arrive"} } }, "sandwich_shop": { "arrive": { "description": "**Tony's Sandwich Shop**\n\nThe smell of fresh bread fills the air.\n\n**Tony** stands behind the counter.\n\n*Quest objective reached!*", "choices": ["Talk to Tony", "Look at menu", "Leave"], "transitions": { "Talk to Tony": "sandwich_shop/tony", "Look at menu": "sandwich_shop/menu", "Leave": "street/arrive" }, "on_enter": {"set_flag": "reached_sandwich_shop"} }, "menu": { "description": "**Menu:**\n- Classic Sandwich: 5 gold\n- Deluxe Sandwich: 10 gold\n- Super Sandwich: 15 gold", "choices": ["Talk to Tony", "Leave"], "transitions": {"Talk to Tony": "sandwich_shop/tony", "Leave": "street/arrive"} }, "tony": { "description": "**Tony** grins.\n\n\"What can I get you today?\"", "choices": ["Buy Classic (5g)", "Buy Deluxe (10g)", "Just looking"], "transitions": { "Buy Classic (5g)": "sandwich_shop/buy_classic", "Buy Deluxe (10g)": "sandwich_shop/buy_deluxe", "Just looking": "sandwich_shop/arrive" } }, "buy_classic": { "description": "You hand over 5 gold.\n\nTony gives you a **Classic Sandwich**!\n\n*Quest complete!*", "choices": ["Eat it!", "Save for later"], "transitions": {"Eat it!": "sandwich_shop/eat", "Save for later": "street/arrive"}, "on_enter": {"remove_money": 5, "add_item": "Classic Sandwich", "complete_mission": "get_lunch"} }, "buy_deluxe": { "description": "You hand over 10 gold.\n\nTony gives you a **Deluxe Sandwich**!\n\n*Quest complete!*", "choices": ["Eat it!", "Save for later"], "transitions": {"Eat it!": "sandwich_shop/eat", "Save for later": "street/arrive"}, "on_enter": {"remove_money": 10, "add_item": "Deluxe Sandwich", "complete_mission": "get_lunch"} }, "eat": { "description": "Mmm! Delicious!\n\n**THE END**\n\nThanks for playing!", "choices": ["Play again"], "transitions": {"Play again": "game_start/intro"} } } } SKYRIM_DEMO_CONFIG = { "game_start": { "intro": { "description": "**Welcome, Dragonborn!**\n\nYour journey begins. You have 100 gold.\n\n*Main quest: Unbound has started.*", "choices": ["Begin adventure"], "transitions": {"Begin adventure": "whiterun/arrive"}, "on_enter": {"set_money": 100, "start_mission": ["mq101", "mq102"]} } }, "whiterun": { "arrive": { "description": "**Whiterun** (Whiterun Hold)\n\nA bustling city of 200 souls. The streets are alive with activity.\n\nYou see: Belethor the Merchant.", "choices": ["Speak with Belethor", "Browse Belethor's wares", "Travel to Riverwood", "Travel to Dragonsreach", "Check quest journal"], "transitions": { "Speak with Belethor": "whiterun/talk_belethor", "Browse Belethor's wares": "whiterun/shop", "Travel to Riverwood": "riverwood/arrive", "Travel to Dragonsreach": "dragonsreach/arrive", "Check quest journal": "quest_journal/journal" } }, "talk_belethor": { "description": "**Belethor** greets you.\n\n\"Everything's for sale, my friend. Everything. If I had a sister, I'd sell her in a second.\"", "choices": ["What do you have?", "Goodbye"], "transitions": {"What do you have?": "whiterun/shop", "Goodbye": "whiterun/arrive"} }, "shop": { "description": "**Belethor's General Goods**\n\n- Iron Sword (25g)\n- Health Potion (25g)\n- Leather Strips (3g)", "choices": ["Buy Iron Sword", "Buy Health Potion", "Leave"], "transitions": { "Buy Iron Sword": "whiterun/buy_sword", "Buy Health Potion": "whiterun/buy_potion", "Leave": "whiterun/arrive" } }, "buy_sword": { "description": "You purchase an **Iron Sword** for 25 gold.", "choices": ["Continue shopping", "Leave"], "transitions": {"Continue shopping": "whiterun/shop", "Leave": "whiterun/arrive"}, "on_enter": {"remove_money": 25, "add_item": "Iron Sword"} }, "buy_potion": { "description": "You purchase a **Health Potion** for 25 gold.", "choices": ["Continue shopping", "Leave"], "transitions": {"Continue shopping": "whiterun/shop", "Leave": "whiterun/arrive"}, "on_enter": {"remove_money": 25, "add_item": "Health Potion"} } }, "riverwood": { "arrive": { "description": "**Riverwood** (Whiterun Hold)\n\nA quiet village of 50 people. Life here is simple.\n\nYou see: Alvor the Blacksmith.\n\n*Quest objective: Escape to Riverwood - Complete!*", "choices": ["Speak with Alvor", "Travel to Whiterun", "Enter Bleak Falls Barrow", "Check quest journal"], "transitions": { "Speak with Alvor": "riverwood/talk_alvor", "Travel to Whiterun": "whiterun/arrive", "Enter Bleak Falls Barrow": "bleak_falls/arrive", "Check quest journal": "quest_journal/journal" }, "on_enter": {"set_flag": "reached_riverwood", "set_knowledge": {"last_location": "riverwood"}} }, "talk_alvor": { "description": "**Alvor** looks up from his forge.\n\n\"You're the one who escaped Helgen? By the Nine! Come, tell me what happened.\"\n\n*Quest updated: Spoke with Alvor*", "choices": ["Tell him about the dragon", "Ask about Bleak Falls", "Goodbye"], "transitions": { "Tell him about the dragon": "riverwood/dragon_talk", "Ask about Bleak Falls": "riverwood/bleak_falls_info", "Goodbye": "riverwood/arrive" }, "on_enter": {"set_flag": "talked_alvor"} }, "dragon_talk": { "description": "Alvor's face pales.\n\n\"A dragon? Are you sure? We need to warn Jarl Balgruuf in Dragonsreach!\"", "choices": ["I'll go warn him", "Maybe later"], "transitions": {"I'll go warn him": "whiterun/arrive", "Maybe later": "riverwood/arrive"} }, "bleak_falls_info": { "description": "\"Bleak Falls Barrow? That old ruin? Nothing but draugr and bandits up there. But I've heard the court wizard is looking for something from that place.\"", "choices": ["Thanks", "Goodbye"], "transitions": {"Thanks": "riverwood/arrive", "Goodbye": "riverwood/arrive"} } }, "dragonsreach": { "arrive": { "description": "**Dragonsreach** (Whiterun Hold)\n\nThe great hall of the Jarl. Guards watch your every move.\n\nYou see: Jarl Balgruuf on his throne.", "choices": ["Speak with Jarl Balgruuf", "Leave"], "transitions": { "Speak with Jarl Balgruuf": "dragonsreach/talk_balgruuf", "Leave": "whiterun/arrive" } }, "talk_balgruuf": { "description": "**Jarl Balgruuf** regards you from his throne.\n\n\"What brings you to Dragonsreach?\"\n\n*Quest updated: Spoke with the Jarl*", "choices": ["I bring news of the dragon attack", "I seek work", "Farewell"], "transitions": { "I bring news of the dragon attack": "dragonsreach/dragon_news", "I seek work": "dragonsreach/work", "Farewell": "dragonsreach/arrive" }, "on_enter": {"set_flag": "talked_balgruuf"} }, "dragon_news": { "description": "The Jarl leans forward.\n\n\"A dragon? This is grave news indeed. Speak to my court wizard, Farengar. He has been researching dragons.\"\n\n*Quest: Before the Storm progressed*", "choices": ["I'll speak to Farengar", "Where is Farengar?"], "transitions": { "I'll speak to Farengar": "dragonsreach/farengar", "Where is Farengar?": "dragonsreach/farengar" } }, "work": { "description": "\"Work? Perhaps. The Companions are always looking for strong arms. Speak to Kodlak at Jorrvaskr.\"", "choices": ["Thank you"], "transitions": {"Thank you": "dragonsreach/arrive"} }, "farengar": { "description": "**Farengar Secret-Fire** looks up from his books.\n\n\"Ah, the Jarl's new errand person. I need you to fetch something from Bleak Falls Barrow - a stone tablet called the Dragonstone.\"\n\n*New quest: Bleak Falls Barrow*", "choices": ["I'll get it", "Tell me more about the Dragonstone"], "transitions": { "I'll get it": "dragonsreach/arrive", "Tell me more about the Dragonstone": "dragonsreach/dragonstone_info" }, "on_enter": {"start_mission": "mq103"} }, "dragonstone_info": { "description": "\"It's an ancient map of dragon burial sites. If the dragons are truly returning, we need to know where they might appear.\"", "choices": ["I'll retrieve it"], "transitions": {"I'll retrieve it": "dragonsreach/arrive"} } }, "bleak_falls": { "arrive": { "description": "**Bleak Falls Barrow** (Whiterun Hold)\n\nAncient stone corridors stretch into darkness. Danger lurks in every shadow.\n\n*This is the destination of your quest!*", "choices": ["Explore deeper", "Leave"], "transitions": { "Explore deeper": "bleak_falls/explore", "Leave": "riverwood/arrive" }, "on_enter": {"set_flag": "reached_bleak_falls"} }, "explore": { "description": "You venture into the barrow. Cobwebs and ancient dust fill the air.\n\nYou hear shuffling in the darkness...\n\n*A draugr emerges!*", "choices": ["Fight!", "Retreat!"], "transitions": { "Fight!": "bleak_falls/combat", "Retreat!": "bleak_falls/arrive" } }, "combat": { "description": "You strike down the draugr!\n\nDeeper in, you find a chamber with an ancient wall... and the **Dragonstone**!", "choices": ["Take the Dragonstone", "Examine the wall"], "transitions": { "Take the Dragonstone": "bleak_falls/get_stone", "Examine the wall": "bleak_falls/word_wall" } }, "word_wall": { "description": "Strange words glow on the wall... You feel power flowing into you.\n\n*You learned a Word of Power: FUS (Force)*", "choices": ["Take the Dragonstone"], "transitions": {"Take the Dragonstone": "bleak_falls/get_stone"}, "on_enter": {"set_flag": "learned_fus"} }, "get_stone": { "description": "You take the **Dragonstone**!\n\n*Quest updated: Return to Farengar*", "choices": ["Return to Dragonsreach"], "transitions": {"Return to Dragonsreach": "dragonsreach/arrive"}, "on_enter": {"add_item": "Dragonstone", "set_flag": "has_dragonstone"} } }, "quest_journal": { "journal": { "description": "**Quest Journal**\n\n**Main Quests:**\n- Unbound: Escape to Riverwood\n- Before the Storm: Speak to the Jarl\n- Bleak Falls Barrow: Retrieve the Dragonstone", "choices": ["Travel to Riverwood", "Travel to Dragonsreach", "Close journal"], "transitions": { "Travel to Riverwood": "riverwood/arrive", "Travel to Dragonsreach": "dragonsreach/arrive", "Close journal": "whiterun/arrive" } } } } def add_scenario_prompts_to_queue(prompts_text, media_type="image"): """Add generated prompts to the generation queue. Args: prompts_text: Text containing prompts (one per line starting with 'Cinematic shot:') media_type: Type of media to generate ('image', 'audio', '3d', 'tts') """ global generation_queue if not prompts_text or not prompts_text.strip(): return get_queue_dataframe(), f"**Queue: {len(generation_queue)} items**", "No prompts to add" lines = prompts_text.strip().split("\n") added = 0 for line in lines: line = line.strip() # Skip header lines and empty lines if not line or line.startswith("##") or line.startswith("#"): continue # Accept lines starting with "Cinematic shot:" or any non-empty line if line.startswith("Cinematic shot:") or (len(line) > 10 and not line.startswith("Video Prompts")): item = { "id": len(generation_queue) + 1, "type": media_type, # Use image type since video isn't supported yet "prompt": line.strip(), "status": "pending" } generation_queue.append(item) added += 1 return get_queue_dataframe(), f"**Queue: {len(generation_queue)} items**", f"Added {added} {media_type} prompts to queue" def LinPEWFformat_prompt(current_prompt, prev_messages): formatted_prompt = textwrap.dedent(""" Previous prompts and responses: {history} Current prompt: {current} Please respond to the current prompt, taking into account the context from previous prompts and responses. """).strip() history = "\n\n".join(f"Prompt {i+1}: {msg}" for i, msg in enumerate(prev_messages)) return formatted_prompt.format(history=history, current=current_prompt) #----------------------------------------------------------------------------------------------------------------------------------- def TestGradioClientrandommodel(text): try: # client = Client("Qwen/Qwen2-72B-Instruct") # result = client.predict( # query=text, #"Hello!!", # history=[], # system="You are a helpful assistant.", # api_name="/model_chat" # ) client = Client("huggingface-projects/gemma-2-9b-it") result = client.predict( message=text, #"Hello!!", max_new_tokens=1024, temperature=0.6, top_p=0.9, top_k=50, repetition_penalty=1.2, api_name="/chat" ) #print(result) #print(result[1][0]) #All messages in the conversation #print(result[2]) # System prompt except Exception as e: result = str(e) return result #result[1][0][1] # If supporting conversations this needs to return the last message instead #-----=------------------=--------------------=--------------------=----------------------=---- ConfigConversionforExporttoPlatformselector = gr.Dropdown(choices=["playcanvas", "godot", "unreal", "gamemaker", "flutter", "2d map related space", "existing game"]) # Import platform exporters from playcanvas_exporter import export_to_playcanvas from godot_exporter import export_to_godot from unreal_exporter import export_to_unreal # Import LLM playtester from llm_playtester import run_llm_playtest # Import platform exporters package from exporters import ConfigConversionforExporttoPlatform # Import film scenarios and JSON utilities from film_scenarios import FILM_SCENARIOS, generate_scenario_sequence from beat_scenarios import STORY_BEATS, generate_beat_sequence from dnd_scenarios import DND_ENCOUNTERS, generate_dnd_sequence from world_scenarios import WORLD_LOCATIONS, generate_world_sequence from timeline_scenarios import TIMELINE_EVENTS, generate_timeline_sequence from song_scenarios import EMOTIONAL_STATES, generate_song_sequence from mystery_scenarios import MYSTERY_LAYERS, generate_mystery_sequence from json_utils import find_and_visualize_json_errors, join_lines_after_correct_json_errors # Import UI tabs from ui_tabs import create_story_graph_tab, create_3d_study_tab, create_resources_hub_tab, create_mechanic_translation_tab, create_llm_playtest_tab, create_big_rpg_scale_tab, create_dnd_gm_tab, create_story_architect_tab, create_narrative_engine_tab, create_config_analysis_tab from ui_tabs.dnd_gm_tab import search_monsters, search_spells, search_magicitems, search_conditions, search_classes, get_monster_details, get_spell_details, get_magicitem_details # ConfigConversionforExporttoPlatform moved to exporters/router.py # find_and_visualize_json_errors, join_lines_after_correct_json_errors moved to json_utils.py #--------------------------------------- def testgroupingUIremotely(): with gr.Accordion("Mini-Tutorial & Resources", open=False) as testui: with gr.Tabs(): # ============================================================ # TAB 1: TUTORIAL # ============================================================ with gr.Tab("Tutorial"): gr.HTML("""
Main Goal: Rapid prototypes for education/training (game-based learning)
Secondary: Plan stateful game mechanics with AI assistance
Workflow: Config → Assets → Playtest → Port to Real Engine
""") # SECTION 1: Config Shape gr.Markdown("---") gr.Markdown("## 1. Config Shape - The Core Concept") with gr.Row(): with gr.Column(scale=1): gr.Markdown("### Video Explanation") tutorial_video_1 = gr.Video( value="testmedia/Hallo - My Current Understanding of a game is.mp4", label="Config Shape Explained" ) gr.HTML("šŸŽ¬ Talking head video placeholder - generate via Media Studio → Video Generation") with gr.Column(scale=1): gr.Markdown("""### Config Structure ```json { "masterlocation1": { "sublocation1": { "description": "What the player sees", "choices": ["option A", "option B"], "transitions": { "option A": "masterlocation1_sublocation2", "option B": "masterlocation2_start" }, "consequences": { "option A": "lambda player: player.add_item('key')" }, "media": ["background.png", "ambient.mp3"] } } } ``` **Key Points:** - **Masterlocations** = Major areas (village, forest) - **Sublocations** = States within areas - **Transitions** = Where choices lead - **Consequences** = State changes - **Media** = Images, audio, video, 3D """) # SECTION 2: What This Space Can Do gr.Markdown("---") gr.Markdown("## 2. What This Space Can Do") with gr.Row(): with gr.Column(scale=1): gr.Markdown("### Video Overview") tutorial_video_2 = gr.Video( value=None, label="Capabilities Overview" ) gr.HTML("šŸŽ¬ Talking head video placeholder - generate via Media Studio → Video Generation") with gr.Column(scale=1): gr.Markdown("""### Capabilities **Create Games From:** - Your ideas → LLM generates JSON config - Textbooks, songs, memes → Interactive games - Existing designs → Import and modify **Test & Improve:** - Play in-browser with state tracking - LLM automated playtesting - Config validation & Mermaid diagrams **Export To:** - PlayCanvas, Godot 4.x, GameMaker - Flutter, Unreal Engine 5 - 2D Map visualizations (SVG) **Design Tools:** - Mechanic Translation (1D ↔ 2D ↔ 3D) - State system with logic gates - D&D 5e SRD integration """) # Generate Tutorial Videos Section gr.Markdown("---") with gr.Accordion("šŸŽ¬ Generate Tutorial Videos", open=False): gr.Markdown("""### How to Create Tutorial Videos 1. **Go to Media Studio → Video Generation** 2. **Upload a portrait image** (or generate one in Media Studio → HF Spaces → Images) 3. **Enter the script text** - the AI will generate TTS and animate the portrait **Suggested Scripts:** **Video 1 - Config Shape:** > "The config is a nested JSON structure that defines your game. At the top level, you have masterlocations like village or forest. Inside each are sublocations - the actual game states. Each state has a description players see, choices they can make, transitions to other states, and media like images or audio." **Video 2 - Capabilities:** > "This space helps you prototype games quickly. Generate configs from your ideas using AI, test them right in your browser with live state tracking, then export to real game engines like Godot or Unreal. You can also generate images, audio, 3D models, and even talking head videos like this one." """) with gr.Accordion("Legacy Video Tutorial", open=False): gr.Markdown("Original prototype videos using Hallo") gr.Video(value="testmedia/Hallo - My Current Understanding of a game is.mp4") gr.HTML("Talking portrait spaces: Hallo TTS | SadTalker") # ============================================================ # TAB 2: IMPROVEMENT PROCESS # ============================================================ with gr.Tab("Improvement Process"): gr.Markdown("""## The Improvement Process - Core Abstraction The key insight: **systematic improvement with access to the original enables real analysis.** This isn't about UI buttons - it's about understanding HOW configs get better.""") gr.Markdown("---") gr.Markdown("### The 4 Focus Areas") gr.Markdown(""" Each round of improvement focuses on ONE aspect. This prevents overwhelming changes and lets you see what each focus contributes. | Round | Focus | What Changes | Feel Impact | |-------|-------|--------------|-------------| | **R1** | Environment | Descriptions gain sensory details, clues planted | World feels *real*, *explorable* | | **R2** | Characters | NPCs gain motivations, dialogue reveals personality | World feels *inhabited*, *alive* | | **R3** | Choices | More options per state, different approaches | Player feels *agency*, *freedom* | | **R4** | Tension | Time pressure, red herrings, stakes raised | Player feels *urgency*, *engagement* | **The order matters.** Environment first gives characters a world to inhabit. Characters give meaning to choices. Choices create opportunities for tension. """) gr.Markdown("---") gr.Markdown("### Why Compare to Original?") gr.Markdown(""" Without the original, you can't answer: - "Did this round actually improve things?" - "What specifically changed?" - "Did I lose something important?" **The 5-round comparison view** (in Config Analysis) shows the same state across R0→R4, so you can see the journey, not just the destination. """) gr.Markdown("---") gr.Markdown("### Derivative Changes - The RPG Scale Challenge") gr.Markdown(""" At small scale (7-30 states), you can hold the whole config in your head. At RPG scale (100+ states), changing one thing affects many others: | You Change... | Consider Also Updating... | |---------------|---------------------------| | Location name | NPCs who mention it, quests there, travel descriptions | | NPC role | Their dialogue, faction rank, what they sell | | Faction relationship | Cross-faction dialogue, quest availability | | Item properties | Recipes using it, quest objectives, merchant prices | The **Derivative Analyzer** (in Big RPG Scale → Validation) shows these connections before you make changes. """) gr.Markdown("---") gr.Markdown("### The Workflow Pattern") gr.Markdown(""" ``` ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ 1. START │ │ Load a config (starter, demo, or your own) │ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ ↓ ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ 2. ANALYZE │ │ Current state: metrics, issues, graph visualization │ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ ↓ ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ 3. IMPROVE (one focus at a time) │ │ Environment → Characters → Choices → Tension │ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ ↓ ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ 4. COMPARE │ │ Side-by-side with original - what changed? │ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ ↓ ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ 5. TEST │ │ Playtest (manual or AI personas) │ │ Did the changes work? Any new issues? │ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ ↓ ā”Œā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā” │ Happy with result? │ ā””ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”€ā”˜ ↓ ↓ NO YES ↓ ↓ Back to step 3 EXPORT to game engine ``` **The loop is the process.** Each cycle makes the config better. You always have the original to compare against. """) gr.Markdown("---") gr.Markdown("### Coming Full Circle") gr.Markdown(""" This space's purpose: 1. **Idea exposure** - See what's possible with game configs 2. **Abstract the improvement process** - Learn the pattern, not just the tools Once you internalize the 4-focus improvement cycle, you can apply it anywhere - with or without this UI. """) gr.Markdown("---") with gr.Accordion("šŸŽ¬ Tutorial Video Scripts", open=False): gr.Markdown("""### Generate These Videos in Media Studio → Talking Head **How to use:** Copy a script below, go to Media Studio → Video Generation → Talking Head tab, upload a portrait image, paste the script text, and generate. --- **Video 1: The 4 Focus Areas** (~45 seconds) ``` When improving a game config, we focus on ONE aspect at a time. Round one: Environment. Descriptions gain sensory details - what you see, hear, smell. The world starts feeling real and explorable. Round two: Characters. NPCs gain motivations and personality. Their dialogue reveals who they are. The world feels inhabited. Round three: Choices. More options per state. Different approaches to problems. The player feels agency. Round four: Tension. Time pressure, red herrings, raised stakes. The player feels urgency. The order matters. Environment gives characters a world. Characters give meaning to choices. Choices create opportunities for tension. ``` --- **Video 2: Why Compare to Original** (~30 seconds) ``` Why do we keep the original config alongside our improvements? Because without it, you can't answer basic questions: Did this round actually make things better? What specifically changed? Did we accidentally lose something important? The five-round comparison view shows the same state across all rounds. You see the journey, not just the destination. That's how you learn what each focus area contributes. ``` --- **Video 3: The Workflow Loop** (~40 seconds) ``` The improvement process is a loop, not a straight line. Start with a config - a starter, a demo, or your own. Analyze it. What's the current state? Any issues? Improve it - one focus at a time. Compare to the original. What changed? Test it. Play through. Did the changes work? If you're happy, export to your game engine. If not, go back to improve. Each cycle makes the config better. You always have the original to compare against. That's the key insight: systematic improvement with access to the original enables real analysis. ``` --- **Tips:** - Use a clear, front-facing portrait image - Each video takes 1-5 minutes to generate depending on text length - SadTalker works best with natural-sounding scripts """) # ============================================================ # TAB 3: RESOURCES (moved from Media Studio) # ============================================================ with gr.Tab("Resources"): gr.Markdown("## Inspiration, Learning & Licensing") with gr.Accordion("Chat UIs - Free Tier LLMs", open=False): gr.HTML("""Hugging Face Chat | AnyChat (Latest Releases)""") gr.HTML("You can turn any space into a tool for huggingchat and the default image tool can do 5-10 secs per image - paste the current description and ask for images") gr.HTML("Huggingface chat supports - State Management (Threads), Image Generation and editing, Websearch, Document parsing (PDF?), Assistants and larger models than zero gpu can support in July 2024 (Unquantised 30B and above)") gr.HTML("""Lambda Chat - beta and text only - no login so chats expire (October 2024)""") gr.HTML("ChatGPT is good for multiple images in one image - eg game maps and for this space all decisions in one picture") gr.HTML("Gemini") gr.HTML("Claude - Coding") gr.HTML("Existing Assistants to use and planning custom assistants placeholder") with gr.Accordion("Idea / Inspiration Sources", open=False): with gr.Row(): gr.HTML("""Licenses for the spaces still to be evaluated - June 2024
Users to follow with cool spaces:
osanseviero - TheMLGame
jbilcke-hf
dylanebert
fffiloni
artificialguybr
radames
multimodalart""") gr.HTML("""Some Youtube Channels to keep up with updates:

@lev-selector
@fahdmirza""") gr.HTML("""Social media that shows possibilities:

r/aivideo | r/StableDiffusion | r/midjourney | @blizaine | r/singularity""") with gr.Accordion("Examples of Generated Media on Reddit", open=False): gr.HTML("""FaceCam AI - convert image into video
Tripo v2.0 - stunning 3D""") with gr.Accordion("Licensing Notes", open=False): gr.HTML("""To be continued.... Need to find the press release to see license eg. Black Forest Labs announcement""") with gr.Accordion("Future Developments / Links to Integrate", open=False): gr.HTML("""Video games made entirely by o1-preview""") gr.HTML("""Artificial Analysis | lmarena.ai | web.lmarena.ai""") gr.HTML(""" Apache 2.0 models to aim for:
HF Text-to-Image (Apache 2.0)

Inspiration and food for thought:
tost.ai | GaussianAnything-AIGC3D | HF Image-to-3D
List of MCP Servers - awesome-mcp-servers
Llama Mesh Blender addon | Clone Robotics Torso 2
Moondream 0.5B VLM | DepthFlow
AI-generated CSGO on RTX 3090
thuwzy.github.io
Teleoperating robots | Tesla Optimus | Police robots in China
r/aivideo | Driver 2 PS1 reimagined by AI
Llama3 codebase experiments
Llama 3.2 all versions - cpu application considerations
HF Forum Dashboard - how can we make a dashboard for the game
CogVideoX-Fun-5b - Video Gen
open-notebooklm | PDF2Audio | Roblox 3D Assets Generator
HF Video Datasets
Midjourney Kling AI Motion Brush | DART human motions
Genie 2 from Google | SAMURAI vs SAM 2
TRELLIS | Apple DepthPro
Pika 2.0 | Pika Labs update
ExBody2 whole-body tracking | Meta FAIR updates
Parking systems analysis | Joust trailer
Moondream 2B gaze detection | Text to CAD
Gorgeous AI technique | AI standup comedy
Llama Mesh blog post | Research Tracker
Scaling Test-Time Compute | Chess Openings | AnyChat

MIT filter + Modality:
HF Audio Datasets (MIT) | HF Video Datasets (MIT)
VideoChatGPT Dataset - GPU poverty workaround
Llama 3.2 Taiwan Legal LoRA - How LoRAs work
StoryMaker - Consistency | Fish Speech 1.4 | mini-omni
Alibaba MiMo controllable character | ChatGPT Jamaican vibes
Whisper v3 Turbo | OpenMusic | Ovis1.6-Gemma2-9B
Harvard AR glasses | reasoning-base-20k
NVIDIA EdgeRunner | MeshAnything
r/3Dprinting | Color lithopanes
SAM 2.1 Hiera Base Plus
MONST3R geometry estimation | Apple hand gesture
Zamba2-7B | Paper 2410.10306
Unitree offroad | Titans learning
MiniMax01 deepdive | Killed by LLM
Polymathic AI datasets | FrontierMath
Robotic firearm OpenAI integration | Why grokking happens
Fictional characters | DynamicCity
Meta brain-to-AI models
CGDream pricing | Tensor.art
OpenR1 from HuggingFace | Build DeepSeek from scratch (MIT)
Claude 3.7 plays Pokemon | Claude Sonnet 3.7 is insane
Claude 3.7 Manim code | Claude 3.7 coded game
Flappy Bird Claude 3.7 vs o3-mini | Google Veo 2 pricing
Boids simulation Claude 3.7 | AI + real footage
3D Unicorn Claude 3.7 Blender | Veo 2 videogames
More Google Veo videos | CAST 3D scene recovery
Shanghai robot factory | Claude trapped in Mt Moon
Godot Docker image | HF Game-AI Spaces
Robot that can see, hear, talk, dance | LLaDA diffusion model
Gemini Code Assist free
Kimi.ai | Inception Labs Chat
VACE all-in-one video | Gemini visual stories
One-shot character consistency solved
Phone video to animation | Claude inside Blender
New model for animations | Forcing GPT-4o image gen
MathOverflow (Google) | MathOverflow
Maze generation Kruskal's algorithm
Amputee with new prosthetics | ChatGPT memory improved
Google AI Co-Scientist
Mario game by Gemini Pro 2.5 | Multiview 3D by Stability AI
Meta lightning-fast 3D | Feeling the AGI strong
OptimusAlpha MCBench builds | Berkeley Humanoid Lite $5k
2-minute AI short film | ByteDance UI-TARS-1.5
3DTown project

HF Games - Spaces:
FarmingGame | Godot 3D Trucks | Godot 2D
Tetris Game | SimPhysics-HTML5 """) with gr.Accordion("Current Offline Ideas/Developments", open=False): gr.HTML("""1.58-bit LLM Extreme Quantization""") # Resources Hub moved inside Mini-Tutorial & Resources create_resources_hub_tab() return testui #----------------------------------------------------------------------------------------------------------------------------------- with gr.Blocks() as demo: gr.HTML("WIP - Create Config / Improve existing config / Create Media / Plan Story Direction / Learn Some of the current tools available / Playtest") gr.HTML("This space (Q1 2024) original objective is obsolete as new 2025+ LLMs can make the UI reliably (and also struggle less with the syntax) so now is an idea exposure tool and to abstract the improvement process (which naturally means full workflow as well)") # ========== SHARED STATE FOR CROSS-TAB COMMUNICATION ========== # Stores paths of generated media (images, audio, video) for use in game config generated_media_paths = gr.State(value=[]) # Stores the edited config from the render UI (for syncing back to config textbox) edited_config_state = gr.State(value="") testgroupingUIremotely() ui_gr_media_management_acc(generated_media_paths=generated_media_paths) with gr.Tab("Test"): with gr.Tab("Playtest & Edit"): gr.Markdown("## Playtest & Edit Workflow") gr.Markdown("Play the game on the left, edit config on the right. Changes sync back to config for reload.") # Load Demo Configs - prominently placed at top with gr.Accordion("Load a Demo Config", open=False): with gr.Tabs(): with gr.Tab("Traditional (No State)"): gr.Markdown("*Classic configs with deterministic transitions and lambda consequences*") with gr.Row(): ewpwa_demo_btn_village = gr.Button("Village Adventure (Basic)") ewpwa_demo_btn_racing = gr.Button("Racing Game") ewpwa_demo_btn_event = gr.Button("Event Planning") with gr.Row(): ewpwa_demo_btn_timeline = gr.Button("Timeline Structure") ewpwa_demo_btn_memory = gr.Button("Memory Fragments (Advanced)") with gr.Tab("Stateful (With Logic Gates)"): gr.Markdown("*Configs using conditions, effects, dynamic transitions, and state tracking*") with gr.Row(): ewpwa_demo_btn_logic = gr.Button("Logic Gates Demo (Tavern)") ewpwa_demo_btn_reference = gr.Button("State System Reference (Comprehensive)") # ============================================================ # ONE-CLICK TO GAMEPLAY - Multiple Scenario Types # ============================================================ with gr.Accordion("One-Click to Gameplay", open=False): gr.Markdown("### Generate Complete Game from Scenarios") gr.Markdown("Choose a scenario type, configure settings, generate assets, and auto-load into playtest.") # Shared generation settings (at top, used by all tabs) with gr.Accordion("Shared Generation Settings", open=False): otg_gen_mode = gr.Radio( ["Local (ZeroGPU)", "API"], value="Local (ZeroGPU)", label="Generation Mode" ) with gr.Row(): otg_text_model = gr.Dropdown( choices=modelnames, value=modelnames[1] if len(modelnames) > 1 else modelnames[0], label="Text Model" ) otg_image_model = gr.Dropdown( choices=imagemodelnames, value=imagemodelnames[0], label="Image Model" ) with gr.Row(): otg_media_type = gr.Dropdown( choices=["image", "audio", "3d", "tts"], value="image", label="Media Type", scale=1 ) # Tabs for different scenario types with gr.Tabs(): # ==================== TAB 1: FILM SCENARIOS (Original Videographer) ==================== with gr.Tab("Film Scenarios"): gr.Markdown("**Videographer's perspective** - Generate from film scene types") with gr.Row(): otg_count = gr.Slider(minimum=3, maximum=10, value=5, step=1, label="Number of Scenes") with gr.Row(): otg_opening = gr.Checkbox(label="Openings", value=True) otg_tension = gr.Checkbox(label="Tension", value=True) otg_action = gr.Checkbox(label="Action", value=True) otg_emotional = gr.Checkbox(label="Emotional", value=True) with gr.Row(): otg_discovery = gr.Checkbox(label="Discovery", value=True) otg_social = gr.Checkbox(label="Social", value=True) otg_ending = gr.Checkbox(label="Endings", value=True) with gr.Row(): otg_force_opening = gr.Checkbox(label="Force Opening First", value=True) otg_force_ending = gr.Checkbox(label="Force Ending Last", value=True) with gr.Row(): otg_generate_btn = gr.Button("Generate Film Scenario", variant="primary", scale=3) otg_stop_btn = gr.Button("Stop", variant="stop", scale=1, visible=False) # ==================== TAB 2: STORY BEATS (Writer's Perspective) ==================== with gr.Tab("Story Beats"): gr.Markdown("**Writer's perspective** - Generate from narrative beat structures") with gr.Row(): otg_beat_format = gr.Dropdown( choices=[ ("90-Minute Feature Film", "film_90min"), ("30-Minute TV Episode", "tv_30min"), ("9-Minute YouTube Video", "youtube_9min"), ("3-Minute Short", "short_3min"), ], value="film_90min", label="Format" ) otg_beat_genre = gr.Dropdown( choices=[ ("Action", "action"), ("Drama", "drama"), ("Comedy", "comedy"), ("Thriller", "thriller"), ("Romance", "romance"), ("Sci-Fi", "scifi"), ("Fantasy", "fantasy"), ("Horror", "horror"), ], value="thriller", label="Genre" ) with gr.Row(): otg_beat_count = gr.Slider(minimum=3, maximum=15, value=6, step=1, label="Number of Beats") with gr.Row(): otg_beat_generate_btn = gr.Button("Generate Story Beats", variant="primary", scale=3) # ==================== TAB 3: D&D ADVENTURE ==================== with gr.Tab("D&D Adventure"): gr.Markdown("**Fantasy RPG** - Generate from D&D encounter types") with gr.Row(): otg_dnd_difficulty = gr.Dropdown( choices=[ ("Easy", "easy"), ("Medium", "medium"), ("Hard", "hard"), ("Deadly", "deadly"), ], value="medium", label="Difficulty" ) otg_dnd_count = gr.Slider(minimum=3, maximum=10, value=5, step=1, label="Encounter Count") with gr.Row(): otg_dnd_combat = gr.Checkbox(label="Combat", value=True) otg_dnd_social = gr.Checkbox(label="Social", value=True) otg_dnd_exploration = gr.Checkbox(label="Exploration", value=True) otg_dnd_puzzle = gr.Checkbox(label="Puzzle", value=True) with gr.Row(): otg_dnd_boss = gr.Checkbox(label="Include Boss Fight", value=True) otg_dnd_force_boss_end = gr.Checkbox(label="Boss at End", value=True) with gr.Row(): otg_dnd_generate_btn = gr.Button("Generate D&D Adventure", variant="primary", scale=3) # ==================== TAB 4: WORLD EXPLORER ==================== with gr.Tab("World Explorer"): gr.Markdown("**Geography perspective** - Generate explorable world locations") with gr.Row(): otg_world_count = gr.Slider(minimum=3, maximum=12, value=6, step=1, label="Number of Locations") with gr.Row(): otg_world_forest = gr.Checkbox(label="Forest", value=True) otg_world_mountain = gr.Checkbox(label="Mountain", value=True) otg_world_desert = gr.Checkbox(label="Desert", value=False) otg_world_coastal = gr.Checkbox(label="Coastal", value=True) with gr.Row(): otg_world_urban = gr.Checkbox(label="Urban", value=True) otg_world_swamp = gr.Checkbox(label="Swamp", value=False) otg_world_tundra = gr.Checkbox(label="Tundra", value=False) otg_world_urban_start = gr.Checkbox(label="Start in City", value=True) with gr.Row(): otg_world_generate_btn = gr.Button("Generate World Map", variant="primary", scale=3) # ==================== TAB 5: TIMELINE ==================== with gr.Tab("Timeline"): gr.Markdown("**Chronological perspective** - Generate time-based narrative") with gr.Row(): otg_timeline_count = gr.Slider(minimum=3, maximum=12, value=6, step=1, label="Number of Events") with gr.Row(): otg_timeline_morning = gr.Checkbox(label="Morning", value=True) otg_timeline_midday = gr.Checkbox(label="Midday", value=True) otg_timeline_afternoon = gr.Checkbox(label="Afternoon", value=True) otg_timeline_evening = gr.Checkbox(label="Evening", value=True) with gr.Row(): otg_timeline_night = gr.Checkbox(label="Night", value=True) otg_timeline_past = gr.Checkbox(label="Flashbacks", value=False) otg_timeline_future = gr.Checkbox(label="Flash-forwards", value=False) otg_timeline_chrono = gr.Checkbox(label="Chronological Order", value=True) with gr.Row(): otg_timeline_generate_btn = gr.Button("Generate Timeline", variant="primary", scale=3) # ==================== TAB 6: EMOTIONAL JOURNEY ==================== with gr.Tab("Emotional Journey"): gr.Markdown("**Song/Lyrics perspective** - Generate emotional arc narrative") with gr.Row(): otg_song_count = gr.Slider(minimum=3, maximum=10, value=6, step=1, label="Number of Emotional Beats") otg_song_arc = gr.Dropdown( choices=[ ("Varied Journey", "journey"), ("Building Crescendo", "crescendo"), ("Tension to Peace", "resolution"), ], value="journey", label="Emotional Arc" ) with gr.Row(): otg_song_joy = gr.Checkbox(label="Joy", value=True) otg_song_sorrow = gr.Checkbox(label="Sorrow", value=True) otg_song_anger = gr.Checkbox(label="Anger", value=False) otg_song_fear = gr.Checkbox(label="Fear", value=False) with gr.Row(): otg_song_hope = gr.Checkbox(label="Hope", value=True) otg_song_nostalgia = gr.Checkbox(label="Nostalgia", value=True) otg_song_peace = gr.Checkbox(label="Peace", value=True) with gr.Row(): otg_song_generate_btn = gr.Button("Generate Emotional Journey", variant="primary", scale=3) # ==================== TAB 7: MYSTERY ==================== with gr.Tab("Mystery"): gr.Markdown("**Investigation perspective** - Generate layered mystery (iceberg model)") with gr.Row(): otg_mystery_count = gr.Slider(minimum=3, maximum=10, value=5, step=1, label="Number of Clues/Reveals") with gr.Row(): otg_mystery_surface = gr.Checkbox(label="Surface Clues", value=True) otg_mystery_shallow = gr.Checkbox(label="Shallow Secrets", value=True) otg_mystery_mid = gr.Checkbox(label="Mid-Depth", value=True) with gr.Row(): otg_mystery_deep = gr.Checkbox(label="Deep Truths", value=True) otg_mystery_abyss = gr.Checkbox(label="Core Truth (Abyss)", value=True) otg_mystery_gradual = gr.Checkbox(label="Gradual Reveal", value=True) with gr.Row(): otg_mystery_generate_btn = gr.Button("Generate Mystery", variant="primary", scale=3) # Progress display otg_progress_md = gr.Markdown("**Status:** Ready - Configure settings and click Generate") otg_current_item = gr.Textbox(label="Current Item", interactive=False, visible=False) # Preview outputs (collapsed by default) with gr.Accordion("Generation Preview", open=False): otg_sequence_preview = gr.Markdown(label="Generated Sequence") otg_config_preview = gr.Code(label="Generated Config", language="json", lines=10) otg_queue_display = gr.Dataframe( headers=["#", "Type", "Prompt", "Status"], label="Queue Status", interactive=False ) # AI Assistance Prompt section with gr.Accordion("AI Assistance Prompt (Copy to Chat)", open=False): gr.Markdown("Generate a prompt to paste into ChatGPT/Claude for expanding and improving your config.") with gr.Row(): otg_prompt_type = gr.Dropdown( choices=[ ("Auto-detect from config", "auto"), ("World/Geography Exploration", "world"), ("Timeline/Chronological Story", "timeline"), ("Emotional Journey/Song", "song"), ("Mystery/Investigation", "mystery"), ("D&D/Fantasy Adventure", "dnd"), ("Film/Video Scenes", "film"), ("Story Beats", "beats") ], value="auto", label="Config Type", scale=2 ) otg_prompt_focus = gr.Dropdown( choices=[ ("Balanced improvements", "balanced"), ("Add more detail/descriptions", "detail"), ("Add more choices/branches", "choices"), ("Deepen character motivations", "characters"), ("Add environmental storytelling", "environment"), ("Increase dramatic tension", "tension") ], value="balanced", label="Focus Area", scale=2 ) otg_generate_prompt_btn = gr.Button("Generate AI Prompt", variant="secondary", scale=1) otg_ai_prompt_output = gr.Code( label="AI Prompt (click copy button to copy to your chat)", language=None, lines=12 ) # Export section with gr.Accordion("Export Config + Media Files", open=False): gr.Markdown("Download a ZIP containing the config JSON and all generated media files.") with gr.Row(): otg_export_btn = gr.Button("Export as ZIP", variant="secondary") otg_export_file = gr.File(label="Download ZIP", interactive=False) otg_export_status = gr.Textbox(label="Export Status", interactive=False, lines=3) # Hidden state variables otg_generated_config = gr.State(value="") otg_prompts_text = gr.State(value="") with gr.Row(): # ========== LEFT COLUMN: GAME PLAYTEST ========== with gr.Column(scale=1): with gr.Group(): gr.Markdown("### Game Preview") # Current state display ewpwa_current_state_display = gr.Textbox( label="Current State ID", value="No game loaded", interactive=False, max_lines=1 ) # Use lazy getter to avoid import-time game initialization _init_info = get_initgameinfo() ewpwadescription = gr.Textbox(label="Current Situation", lines=3, value=_init_info[0]) ewpwamediabool = gr.State(value=True) ewpwamedia = gr.State(["testmedia/Stable Audio - Raindrops, output.wav"]) @gr.render(inputs=ewpwamedia) def dynamic_with_media(media_items): if media_items and len(media_items) > 0: for item in media_items: create_media_component(item) else: gr.Markdown("*No media for this scene*") ewpwachoices = gr.Radio(label="Your Choices", choices=_init_info[1]) ewpwasubmit_btn = gr.Button("Make Choice", variant="primary") ewpwagame_log = gr.Textbox(label="Game Log", lines=10, value=_init_info[2]) ewpwagame_session = gr.State(value=_init_info[3]) # Jump to State & Hot Reload controls with gr.Accordion("Quick Navigation", open=False): gr.Markdown("**Jump to any state** for testing, or **hot reload** after edits") ewpwa_state_dropdown = gr.Dropdown( label="Jump to State", choices=[], interactive=True ) with gr.Row(): ewpwa_jump_btn = gr.Button("Jump to State") ewpwa_hot_reload_btn = gr.Button("Hot Reload Config", variant="secondary") ewpwa_export_log_btn = gr.Button("Export Playthrough Log") ewpwa_exported_log = gr.Textbox(label="Exported Log", lines=5, visible=False) with gr.Accordion("Config & Debug", open=False): ewpwaerror_box = gr.Textbox(label="Path Errors", lines=2, value=get_path_errors()) gr.Markdown("**Quick Load Demo:**") with gr.Row(): ewpwa_load_sandwich_btn = gr.Button("Sandwich Shop", variant="secondary", size="sm") ewpwa_load_skyrim_btn = gr.Button("Skyrim RPG", variant="secondary", size="sm") ewpwa_load_big_rpg_btn = gr.Button("Big RPG Scale", variant="secondary", size="sm") ewpwacustom_config = gr.Textbox(label="Game Config (JSON)", lines=6) with gr.Row(): ewpwacustom_configbtn = gr.Button("Load Config", variant="primary") ewpwasync_from_edit_btn = gr.Button("Re-apply Last Edit") # NEW: Template-based generation with gr.Accordion("Generate from Template", open=False): gr.Markdown("**Generate a config** from narrative templates or a text prompt") ewpwa_template_dropdown = gr.Dropdown( label="Narrative Template", choices=[(v["name"], k) for k, v in NARRATIVE_TEMPLATES.items()], value="heros_journey" ) ewpwa_template_desc = gr.Textbox( label="Template Description", value=NARRATIVE_TEMPLATES["heros_journey"]["description"], interactive=False, lines=2 ) with gr.Row(): ewpwa_theme_dropdown = gr.Dropdown( label="Theme", choices=["fantasy", "scifi", "modern", "horror"], value="fantasy" ) ewpwa_endings_slider = gr.Slider(1, 5, value=3, step=1, label="Number of Endings") ewpwa_generate_template_btn = gr.Button("Generate from Template", variant="primary") gr.Markdown("---") gr.Markdown("**Or generate from a text prompt:**") ewpwa_prompt_input = gr.Textbox( label="Describe your game", placeholder="e.g., A mystery game with 4 endings where the player investigates a haunted mansion...", lines=2 ) ewpwa_structure_dropdown = gr.Dropdown( label="Structure Type", choices=[("Linear", "linear"), ("Branching", "branching"), ("Hub & Spoke", "hub")], value="branching" ) ewpwa_generate_prompt_btn = gr.Button("Generate from Prompt") with gr.Accordion("Generate Random (Legacy)", open=False): with gr.Row(): ewptimeline_output_with_assets = gr.Textbox(label="Timeline", lines=8) ewpstory_output = gr.Textbox(label="Story", lines=8) with gr.Row(): ewptimeline_output_text = gr.Textbox(label="Suggestions", lines=4) ewptimeline_selected_lists_text = gr.Textbox(label="Source Lists", lines=2) with gr.Row(): ewpgenerate_no_story_timeline_points = gr.Slider(1, 30, value=10, step=1, label="Story Points") ewpgenerate_no_ui_timeline_points = gr.Slider(1, 30, value=10, step=1, label="UI Points") with gr.Row(): ewptimeline_num_lists_slider = gr.Slider(1, len(all_idea_lists), value=3, step=1, label="Idea Lists") ewptimeline_items_per_list_slider = gr.Slider(1, 10, value=3, step=1, label="Items/List") with gr.Row(): ewptimeline_include_existing_games = gr.Checkbox(label="Include Game Inspirations", value=True) ewptimeline_include_multiplayer = gr.Checkbox(label="Include Multiplayer", value=True) ewpgenerate_button = gr.Button("Generate Story and Timeline") # ========== RIGHT COLUMN: CONFIG EDITOR ========== with gr.Column(scale=1): gr.Markdown("### Edit Config While Playing") # State to hold edited config for syncing ewpwa_edited_config = gr.State(value="") # Display available media from saved_media folder (uploads + generations) with gr.Accordion("Available Media Files (uploads + generated)", open=False): ewpwa_media_paths_display = gr.Textbox( label="All media files in saved_media/ - copy filenames into media fields below", lines=5, interactive=False ) ewpwa_refresh_media_btn = gr.Button("Refresh Media List") def get_media_paths_display(gen_paths): # Get all files from saved_media folder all_files = get_all_media_files() if all_files: return "\n".join(all_files) return "No media files yet. Upload files in Media Studio → Library or generate in Media Studio → Generate." ewpwa_refresh_media_btn.click( fn=get_media_paths_display, inputs=[generated_media_paths], outputs=[ewpwa_media_paths_display] ) # Config Validation / Linting - ENHANCED with actionable fixes with gr.Accordion("Validate Config (Story Linting)", open=False): gr.Markdown("**Validation with actionable suggestions and auto-fix**") with gr.Row(): ewpwa_validate_btn = gr.Button("Run Validation", variant="primary") ewpwa_autofix_btn = gr.Button("Auto-Fix All Issues", variant="secondary") ewpwa_mermaid_btn = gr.Button("Generate Diagram") # Stats display ewpwa_validation_stats = gr.Markdown(value="*Run validation to see stats*") # Detailed issues with fix suggestions ewpwa_validation_output = gr.Markdown(label="Validation Results") # Auto-fix log ewpwa_autofix_log = gr.Textbox(label="Auto-Fix Log", lines=4, visible=False) ewpwa_mermaid_output = gr.Code(label="Mermaid Diagram (copy to mermaid.live)", language=None, lines=10) def run_enhanced_validation(config): """Run validation and return formatted results with stats.""" if not config: return "No config loaded", "*Load a config first*" validation = get_validation_with_fixes(config) issues = validation["issues"] stats = validation["stats"] # Format stats stats_md = f"""**Config Stats:** {stats.get('total_states', 0)} states | """ stats_md += f"""{stats.get('total_issues', 0)} issues ({stats.get('fixable_issues', 0)} auto-fixable)""" if stats.get('issue_types'): types_str = ", ".join([f"{k}: {v}" for k, v in stats['issue_types'].items()]) stats_md += f"\n*Issue types: {types_str}*" # Format issues issues_md = format_issues_for_display(issues) return issues_md, stats_md def run_autofix(config): """Apply all auto-fixes and return updated config.""" if not config: return config, "No config loaded", gr.update(visible=False) fixed_config, count, log = apply_all_quick_fixes(config) log_text = f"Applied {count} fixes:\n" + "\n".join(log) return fixed_config, log_text, gr.update(visible=True) ewpwa_validate_btn.click( fn=run_enhanced_validation, inputs=[ewpwacustom_config], outputs=[ewpwa_validation_output, ewpwa_validation_stats] ) ewpwa_autofix_btn.click( fn=run_autofix, inputs=[ewpwacustom_config], outputs=[ewpwacustom_config, ewpwa_autofix_log, ewpwa_autofix_log] ) ewpwa_mermaid_btn.click( fn=generate_mermaid_diagram, inputs=[ewpwacustom_config], outputs=[ewpwa_mermaid_output] ) # LLM Structure Advice with gr.Accordion("Ask LLM for Structure Advice", open=False): gr.Markdown("**Model:** Gemma-2-9b-it via Gradio Client (huggingface-projects/gemma-2-9b-it)") # Preset prompts dropdown cohesion_prompts = get_llm_cohesion_prompts() ewpwa_preset_dropdown = gr.Dropdown( choices=["Custom question"] + list(cohesion_prompts.keys()), value="Custom question", label="Preset Analysis" ) ewpwa_llm_question = gr.Textbox( label="Question about your config", placeholder="e.g., How can I add branching paths? What transitions am I missing?", lines=2 ) ewpwa_llm_advice_btn = gr.Button("Get Advice") ewpwa_llm_response = gr.Textbox(label="LLM Response", lines=8) def get_structure_advice(preset, question, config): if preset != "Custom question" and preset in cohesion_prompts: # Use preset prompt prompt = cohesion_prompts[preset].format(config=config[:3000] if config else "No config loaded") elif question: prompt = f"""Analyze this game config JSON and answer the question. Config: {config[:2000] if config else "No config loaded"} Question: {question} Provide specific, actionable advice for improving the game structure.""" else: return "Please enter a question or select a preset analysis." try: result = TestGradioClientrandommodel(prompt) return result if result else "No response received." except Exception as e: return f"Error: {str(e)}" ewpwa_llm_advice_btn.click( fn=get_structure_advice, inputs=[ewpwa_preset_dropdown, ewpwa_llm_question, ewpwacustom_config], outputs=[ewpwa_llm_response] ) # Dynamic config editor with sync capability ewpwa_edit_output = gr.Textbox(label="Last Built Config (auto-applied to main)", lines=8, visible=True) @gr.render(inputs=[ewpwacustom_config, generated_media_paths]) def render_config_editor(config_json, media_paths): if not config_json: gr.Markdown("*Enter JSON config on left and click 'Load Config' to start editing*") return try: data = json.loads(config_json) except json.JSONDecodeError as e: gr.Markdown(f"**JSON Error:** {str(e)}") return # Get ALL media files from saved_media folder (uploads + generated) all_media_files = get_all_media_files() # Determine structure if 'masterlocation1' in data: locations_data = data['masterlocation1'] wrapper_key = 'masterlocation1' else: locations_data = data wrapper_key = None outputs = [] location_keys = [] for location, details in locations_data.items(): if location == 'end': continue location_keys.append(location) desc_preview = (details.get('description', '')[:40] + '...') if len(details.get('description', '')) > 40 else details.get('description', '') with gr.Accordion(f"{location}: {desc_preview}", open=False): desc = gr.Textbox(label="Description", value=details.get('description', ''), lines=2, interactive=True) outputs.append(desc) events = gr.Textbox(label="Events", value=json.dumps(details.get('events', [])), interactive=True) outputs.append(events) choices = gr.Textbox(label="Choices", value=json.dumps(details.get('choices', [])), interactive=True) outputs.append(choices) transitions = gr.Textbox(label="Transitions", value=json.dumps(details.get('transitions', {})), interactive=True) outputs.append(transitions) with gr.Row(): media = gr.Textbox(label="Media", value=json.dumps(details.get('media', [])), scale=2, interactive=True) if all_media_files: media_dd = gr.Dropdown(choices=all_media_files, label="Add path", scale=1, interactive=True) outputs.append(media) devnotes = gr.Textbox(label="Notes", value=json.dumps(details.get('developernotes', [])) if isinstance(details.get('developernotes'), list) else str(details.get('developernotes', '')), interactive=True) outputs.append(devnotes) if 'end' in locations_data: with gr.Accordion("End State", open=False): gr.JSON(value=locations_data['end']) num_fields = 6 def build_json(*values): result = {} for i, loc in enumerate(location_keys): try: result[loc] = { "description": values[i * num_fields], "events": json.loads(values[i * num_fields + 1]) if values[i * num_fields + 1] else [], "choices": json.loads(values[i * num_fields + 2]) if values[i * num_fields + 2] else [], "transitions": json.loads(values[i * num_fields + 3]) if values[i * num_fields + 3] else {}, "media": json.loads(values[i * num_fields + 4]) if values[i * num_fields + 4] else [], "developernotes": json.loads(values[i * num_fields + 5]) if values[i * num_fields + 5].startswith('[') else values[i * num_fields + 5] } except: result[loc] = {"description": values[i * num_fields], "events": [], "choices": [], "transitions": {}, "media": [], "developernotes": "parse error"} if 'end' in locations_data: result['end'] = locations_data['end'] if wrapper_key: return json.dumps({wrapper_key: result}, indent=2) return json.dumps(result, indent=2) def build_and_sync(*values): result = build_json(*values) return result, result # Return to both edit output and main config sync_btn = gr.Button("Build & Apply Config", variant="primary") sync_btn.click(fn=build_and_sync, inputs=outputs, outputs=[ewpwa_edit_output, ewpwacustom_config]) # ========== EVENT HANDLERS ========== # Note: ewpwasubmit_btn handler moved below with enhanced state display ewpwacustom_configbtn.click( load_game, inputs=[ewpwacustom_config, ewpwamediabool], outputs=[ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia] ) # Demo config loaders def load_sandwich_demo(): config_json = json.dumps(SANDWICH_DEMO_CONFIG, indent=2) return config_json def load_skyrim_demo(): config_json = json.dumps(SKYRIM_DEMO_CONFIG, indent=2) return config_json def load_big_rpg_demo(): """Load the Big RPG Scale demo data and export it as a game config.""" db = EntityDatabase() db.load_demo_data() return db.export_to_game_config() ewpwa_load_sandwich_btn.click( fn=load_sandwich_demo, outputs=[ewpwacustom_config] ) ewpwa_load_skyrim_btn.click( fn=load_skyrim_demo, outputs=[ewpwacustom_config] ) ewpwa_load_big_rpg_btn.click( fn=load_big_rpg_demo, outputs=[ewpwacustom_config] ) # Sync edited config back to main config textbox ewpwasync_from_edit_btn.click( fn=lambda x: x, inputs=[ewpwa_edit_output], outputs=[ewpwacustom_config] ) ewpgenerate_button.click( generate_story_and_timeline, inputs=[ewpgenerate_no_story_timeline_points, ewpgenerate_no_ui_timeline_points, ewptimeline_num_lists_slider, ewptimeline_items_per_list_slider, ewptimeline_include_existing_games, ewptimeline_include_multiplayer], outputs=[ewptimeline_output_with_assets, ewpstory_output, ewpwacustom_config, ewptimeline_output_text, ewptimeline_selected_lists_text] ) # ========== NEW EVENT HANDLERS FOR ENHANCED FEATURES ========== # Update state dropdown when config is loaded def update_state_dropdown(config_json): """Update the jump-to-state dropdown with states from the config.""" states, display_map = get_all_states_from_config(config_json) if states: choices = [(display_map.get(s, s), s) for s in states] return gr.update(choices=choices, value=states[0] if states else None) return gr.update(choices=[], value=None) ewpwacustom_configbtn.click( update_state_dropdown, inputs=[ewpwacustom_config], outputs=[ewpwa_state_dropdown] ) # Jump to state handler def handle_jump_to_state(config_json, state_id): """Handle jumping to a specific state.""" result = jump_to_state(config_json, state_id, with_media=True) # result is: (error_box, game_log, description, choices, config, session, media, state_display) return result ewpwa_jump_btn.click( handle_jump_to_state, inputs=[ewpwacustom_config, ewpwa_state_dropdown], outputs=[ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia, ewpwa_current_state_display] ) # Hot reload handler def handle_hot_reload(config_json, game_session): """Handle hot reloading config while preserving game state.""" result = hot_reload_config(config_json, game_session, with_media=True) # result is: (error_box, game_log, description, choices, config, session, media, state_display) return result ewpwa_hot_reload_btn.click( handle_hot_reload, inputs=[ewpwacustom_config, ewpwagame_session], outputs=[ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia, ewpwa_current_state_display] ) # Update current state display when making choices def make_choice_enhanced(choice, game_session, with_media): """Enhanced make_choice that updates state display.""" result = make_choice_with_state_display(choice, game_session, with_media) # result is: (description, choices, game_log, session, media, state_display) return result ewpwasubmit_btn.click( make_choice_enhanced, inputs=[ewpwachoices, ewpwagame_session, ewpwamediabool], outputs=[ewpwadescription, ewpwachoices, ewpwagame_log, ewpwagame_session, ewpwamedia, ewpwa_current_state_display] ) # Export playthrough log def handle_export_log(game_session): """Export the current playthrough as markdown.""" log = export_playthrough_log(game_session) return log, gr.update(visible=True) ewpwa_export_log_btn.click( handle_export_log, inputs=[ewpwagame_session], outputs=[ewpwa_exported_log, ewpwa_exported_log] ) # Load demo config handler def create_demo_loader(demo_key): """Create a loader function for a specific demo.""" def load_specific_demo(): # Get the config based on the key if demo_key == "finished_product_demo": config_data = finished_product_demo elif demo_key in ExampleGameConfigs: config_data = ExampleGameConfigs[demo_key] else: return ( gr.update(value=f"Demo '{demo_key}' not found"), None, None, gr.update(choices=[]), None, None, None, "Demo not found", gr.update(choices=[], value=None) ) config_json = json.dumps(config_data, default=lambda o: o.__dict__, indent=2) # Load the game result = load_game(config_json, with_media=True) # Also update state dropdown states, display_map = get_all_states_from_config(config_json) state_choices = [(display_map.get(s, s), s) for s in states] if states else [] # Get current state for display current_state = states[0] if states else "No states" return ( result[0], # error_box result[1], # game_log result[2], # description result[3], # choices gr.update(value=config_json), # config textbox result[5], # game_session result[6], # media current_state, # current_state_display gr.update(choices=state_choices, value=states[0] if states else None) # state_dropdown ) return load_specific_demo demo_outputs = [ ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia, ewpwa_current_state_display, ewpwa_state_dropdown ] ewpwa_demo_btn_village.click(create_demo_loader("finished_product_demo"), outputs=demo_outputs) ewpwa_demo_btn_racing.click(create_demo_loader("Racinggametest"), outputs=demo_outputs) ewpwa_demo_btn_event.click(create_demo_loader("Eventplanningstortytest"), outputs=demo_outputs) ewpwa_demo_btn_timeline.click(create_demo_loader("TimelineStructurePlanningAttempt"), outputs=demo_outputs) ewpwa_demo_btn_memory.click(create_demo_loader("MemoryFragments"), outputs=demo_outputs) # Stateful configs (with logic gates) ewpwa_demo_btn_logic.click(create_demo_loader("LogicGatesDemo"), outputs=demo_outputs) ewpwa_demo_btn_reference.click(create_demo_loader("StateSystemReference"), outputs=demo_outputs) # Template-based config generation def update_template_description(template_key): """Update template description when selection changes.""" if template_key in NARRATIVE_TEMPLATES: return NARRATIVE_TEMPLATES[template_key]["description"] return "" ewpwa_template_dropdown.change( update_template_description, inputs=[ewpwa_template_dropdown], outputs=[ewpwa_template_desc] ) def handle_generate_from_template(template_key, theme, num_endings): """Generate config from selected template.""" config = generate_config_from_template(template_key, theme, num_endings) # Also update the state dropdown states, display_map = get_all_states_from_config(config) choices = [(display_map.get(s, s), s) for s in states] if states else [] return config, gr.update(choices=choices, value=states[0] if states else None) ewpwa_generate_template_btn.click( handle_generate_from_template, inputs=[ewpwa_template_dropdown, ewpwa_theme_dropdown, ewpwa_endings_slider], outputs=[ewpwacustom_config, ewpwa_state_dropdown] ) # Prompt-based config generation def handle_generate_from_prompt(prompt, structure_type): """Generate config from text prompt.""" if not prompt: return "", gr.update(choices=[], value=None) config = generate_config_from_prompt(prompt, structure_type) # Also update the state dropdown states, display_map = get_all_states_from_config(config) choices = [(display_map.get(s, s), s) for s in states] if states else [] return config, gr.update(choices=choices, value=states[0] if states else None) ewpwa_generate_prompt_btn.click( handle_generate_from_prompt, inputs=[ewpwa_prompt_input, ewpwa_structure_dropdown], outputs=[ewpwacustom_config, ewpwa_state_dropdown] ) # ============================================================ # ONE-CLICK TO GAMEPLAY EVENT HANDLERS # ============================================================ def otg_start_workflow(count, inc_open, inc_tens, inc_act, inc_emo, inc_disc, inc_soc, inc_end, force_open, force_end, media_type, gen_mode, text_model, image_model): """Step 1: Generate sequence, queue prompts, return initial state.""" # Clear queue and prepare otg_clear_and_prepare_queue() # Generate sequence list_out, json_out, prompts_out = generate_scenario_sequence( count, inc_open, inc_tens, inc_act, inc_emo, inc_disc, inc_soc, inc_end, force_open, force_end ) if "Select at least one category" in list_out: return ( list_out, json_out, [], "**Error:** Select at least one category", gr.update(visible=True), gr.update(visible=False), json_out, prompts_out ) # Add prompts to queue with section tracking queue_df, queue_info, status = otg_add_prompts_with_section_tracking( prompts_out, json_out, media_type ) return ( list_out, json_out, queue_df, f"**Queued {len(generation_queue)} items** - Starting generation...", gr.update(visible=False), # Hide generate button gr.update(visible=True), # Show stop button json_out, prompts_out ) def otg_start_beat_workflow(format_type, genre, beat_count, media_type, gen_mode, text_model, image_model): """Story Beats workflow: Generate sequence, queue prompts, return initial state.""" otg_clear_and_prepare_queue() # Generate story beat sequence list_out, json_out, prompts_out = generate_beat_sequence(format_type, genre, int(beat_count)) if "Select a valid" in list_out or not json_out or json_out == "{}": return ( list_out, json_out, [], "**Error:** Invalid format or genre selection", gr.update(visible=True), gr.update(visible=False), json_out, prompts_out ) # Add prompts to queue with section tracking queue_df, queue_info, status = otg_add_prompts_with_section_tracking( prompts_out, json_out, media_type ) return ( list_out, json_out, queue_df, f"**Queued {len(generation_queue)} items** - Starting {genre} story generation...", gr.update(visible=False), gr.update(visible=True), json_out, prompts_out ) def otg_start_dnd_workflow(difficulty, encounter_count, inc_combat, inc_social, inc_exploration, inc_puzzle, inc_boss, force_boss_end, media_type, gen_mode, text_model, image_model): """D&D Adventure workflow: Generate sequence, queue prompts, return initial state.""" otg_clear_and_prepare_queue() # Generate D&D encounter sequence list_out, json_out, prompts_out = generate_dnd_sequence( int(encounter_count), difficulty, inc_combat, inc_social, inc_exploration, inc_puzzle, inc_boss, force_boss_end ) if "Select at least one" in list_out or not json_out or json_out == "{}": return ( list_out, json_out, [], "**Error:** Select at least one encounter type", gr.update(visible=True), gr.update(visible=False), json_out, prompts_out ) # Add prompts to queue with section tracking queue_df, queue_info, status = otg_add_prompts_with_section_tracking( prompts_out, json_out, media_type ) return ( list_out, json_out, queue_df, f"**Queued {len(generation_queue)} items** - Starting D&D adventure generation...", gr.update(visible=False), gr.update(visible=True), json_out, prompts_out ) def otg_start_world_workflow(location_count, inc_forest, inc_mountain, inc_desert, inc_coastal, inc_urban, inc_swamp, inc_tundra, urban_start, media_type, gen_mode, text_model, image_model): """World Explorer workflow: Generate sequence, queue prompts, return initial state.""" otg_clear_and_prepare_queue() # Generate world exploration sequence list_out, json_out, prompts_out = generate_world_sequence( int(location_count), inc_forest, inc_mountain, inc_desert, inc_coastal, inc_urban, inc_swamp, inc_tundra, urban_start ) if "Select at least one" in list_out or not json_out or json_out == "{}": return ( list_out, json_out, [], "**Error:** Select at least one terrain type", gr.update(visible=True), gr.update(visible=False), json_out, prompts_out ) # Add prompts to queue with section tracking queue_df, queue_info, status = otg_add_prompts_with_section_tracking( prompts_out, json_out, media_type ) return ( list_out, json_out, queue_df, f"**Queued {len(generation_queue)} items** - Starting world exploration generation...", gr.update(visible=False), gr.update(visible=True), json_out, prompts_out ) def otg_start_timeline_workflow(event_count, inc_morning, inc_midday, inc_afternoon, inc_evening, inc_night, inc_past, inc_future, chrono_order, media_type, gen_mode, text_model, image_model): """Timeline workflow: Generate sequence, queue prompts, return initial state.""" otg_clear_and_prepare_queue() # Generate timeline sequence list_out, json_out, prompts_out = generate_timeline_sequence( int(event_count), inc_morning, inc_midday, inc_afternoon, inc_evening, inc_night, inc_past, inc_future, chrono_order ) if "Select at least one" in list_out or not json_out or json_out == "{}": return ( list_out, json_out, [], "**Error:** Select at least one time period", gr.update(visible=True), gr.update(visible=False), json_out, prompts_out ) # Add prompts to queue with section tracking queue_df, queue_info, status = otg_add_prompts_with_section_tracking( prompts_out, json_out, media_type ) return ( list_out, json_out, queue_df, f"**Queued {len(generation_queue)} items** - Starting timeline generation...", gr.update(visible=False), gr.update(visible=True), json_out, prompts_out ) def otg_start_song_workflow(verse_count, emotional_arc, inc_joy, inc_sorrow, inc_anger, inc_fear, inc_hope, inc_nostalgia, inc_peace, media_type, gen_mode, text_model, image_model): """Emotional Journey workflow: Generate sequence, queue prompts, return initial state.""" otg_clear_and_prepare_queue() # Generate emotional journey sequence list_out, json_out, prompts_out = generate_song_sequence( int(verse_count), inc_joy, inc_sorrow, inc_anger, inc_fear, inc_hope, inc_nostalgia, inc_peace, emotional_arc ) if "Select at least one" in list_out or not json_out or json_out == "{}": return ( list_out, json_out, [], "**Error:** Select at least one emotional category", gr.update(visible=True), gr.update(visible=False), json_out, prompts_out ) # Add prompts to queue with section tracking queue_df, queue_info, status = otg_add_prompts_with_section_tracking( prompts_out, json_out, media_type ) return ( list_out, json_out, queue_df, f"**Queued {len(generation_queue)} items** - Starting emotional journey generation...", gr.update(visible=False), gr.update(visible=True), json_out, prompts_out ) def otg_start_mystery_workflow(clue_count, inc_surface, inc_shallow, inc_mid, inc_deep, inc_abyss, gradual_reveal, media_type, gen_mode, text_model, image_model): """Mystery workflow: Generate sequence, queue prompts, return initial state.""" otg_clear_and_prepare_queue() # Generate mystery investigation sequence list_out, json_out, prompts_out = generate_mystery_sequence( int(clue_count), inc_surface, inc_shallow, inc_mid, inc_deep, inc_abyss, gradual_reveal ) if "Select at least one" in list_out or not json_out or json_out == "{}": return ( list_out, json_out, [], "**Error:** Select at least one mystery layer", gr.update(visible=True), gr.update(visible=False), json_out, prompts_out ) # Add prompts to queue with section tracking queue_df, queue_info, status = otg_add_prompts_with_section_tracking( prompts_out, json_out, media_type ) return ( list_out, json_out, queue_df, f"**Queued {len(generation_queue)} items** - Starting mystery investigation generation...", gr.update(visible=False), gr.update(visible=True), json_out, prompts_out ) def otg_process_and_load(gen_mode, text_model, image_model, config_json): """Step 2: Process queue items and auto-load when complete.""" # Use the generator to process items for progress_text, current_item, queue_df, is_complete, final_config, error_details in otg_process_queue_generator( gen_mode, text_model, image_model, use_rag=False, use_streaming=False, api_source="HF Inference", hf_model_id="", replicate_model="" ): if is_complete: # All done - load config into playtest (even with partial results) if final_config and final_config.strip(): try: # Load into playtest with updated media paths result = load_game(final_config, True) states, display_map = get_all_states_from_config(final_config) state_choices = [(display_map.get(s, s), s) for s in states] if states else [] # Add error details to progress if any display_progress = progress_text if error_details: display_progress += f"\n\nErrors:\n{error_details}" yield ( display_progress, queue_df, gr.update(visible=True), # Show generate button gr.update(visible=False), # Hide stop button final_config, # Update config preview with new file paths # Playtest outputs result[0], result[1], result[2], result[3], final_config, result[5], result[6], states[0] if states else "No game loaded", gr.update(choices=state_choices, value=states[0] if states else None) ) except Exception as e: # Error loading config - still show the updated config error_msg = f"{progress_text}\n\n**Error loading game:** {str(e)}" yield ( error_msg, queue_df, gr.update(visible=True), gr.update(visible=False), final_config, # Show updated config even on error gr.update(value=f"Error: {str(e)}"), gr.update(), gr.update(), gr.update(), final_config, gr.update(), gr.update(), gr.update(), gr.update() ) else: # No config generated (all items failed) error_msg = progress_text if error_details: error_msg += f"\n\nErrors:\n{error_details}" yield ( error_msg, queue_df, gr.update(visible=True), gr.update(visible=False), gr.update(), # No config to show gr.update(value="Generation failed - no assets created"), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update() ) return else: # Still processing - yield progress update yield ( progress_text, queue_df, gr.update(), gr.update(), gr.update(), # Config preview unchanged during processing gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update() ) def otg_handle_stop(): """Stop the workflow and show partial results with updated config.""" progress_text, queue_df, partial_config = otg_stop_workflow() return ( progress_text, queue_df, gr.update(visible=True), # Show generate button gr.update(visible=False), # Hide stop button partial_config if partial_config else gr.update() # Update config preview with partial results ) # Wire up the main workflow otg_generate_btn.click( otg_start_workflow, inputs=[ otg_count, otg_opening, otg_tension, otg_action, otg_emotional, otg_discovery, otg_social, otg_ending, otg_force_opening, otg_force_ending, otg_media_type, otg_gen_mode, otg_text_model, otg_image_model ], outputs=[ otg_sequence_preview, otg_config_preview, otg_queue_display, otg_progress_md, otg_generate_btn, otg_stop_btn, otg_generated_config, otg_prompts_text ] ).then( otg_process_and_load, inputs=[otg_gen_mode, otg_text_model, otg_image_model, otg_generated_config], outputs=[ otg_progress_md, otg_queue_display, otg_generate_btn, otg_stop_btn, otg_config_preview, # Update config preview with new file paths # Playtest outputs for auto-load ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia, ewpwa_current_state_display, ewpwa_state_dropdown ] ) otg_stop_btn.click( otg_handle_stop, outputs=[otg_progress_md, otg_queue_display, otg_generate_btn, otg_stop_btn, otg_config_preview] ) # Story Beats generate button otg_beat_generate_btn.click( otg_start_beat_workflow, inputs=[ otg_beat_format, otg_beat_genre, otg_beat_count, otg_media_type, otg_gen_mode, otg_text_model, otg_image_model ], outputs=[ otg_sequence_preview, otg_config_preview, otg_queue_display, otg_progress_md, otg_beat_generate_btn, otg_stop_btn, otg_generated_config, otg_prompts_text ] ).then( otg_process_and_load, inputs=[otg_gen_mode, otg_text_model, otg_image_model, otg_generated_config], outputs=[ otg_progress_md, otg_queue_display, otg_beat_generate_btn, otg_stop_btn, otg_config_preview, ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia, ewpwa_current_state_display, ewpwa_state_dropdown ] ) # D&D Adventure generate button otg_dnd_generate_btn.click( otg_start_dnd_workflow, inputs=[ otg_dnd_difficulty, otg_dnd_count, otg_dnd_combat, otg_dnd_social, otg_dnd_exploration, otg_dnd_puzzle, otg_dnd_boss, otg_dnd_force_boss_end, otg_media_type, otg_gen_mode, otg_text_model, otg_image_model ], outputs=[ otg_sequence_preview, otg_config_preview, otg_queue_display, otg_progress_md, otg_dnd_generate_btn, otg_stop_btn, otg_generated_config, otg_prompts_text ] ).then( otg_process_and_load, inputs=[otg_gen_mode, otg_text_model, otg_image_model, otg_generated_config], outputs=[ otg_progress_md, otg_queue_display, otg_dnd_generate_btn, otg_stop_btn, otg_config_preview, ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia, ewpwa_current_state_display, ewpwa_state_dropdown ] ) # World Explorer generate button otg_world_generate_btn.click( otg_start_world_workflow, inputs=[ otg_world_count, otg_world_forest, otg_world_mountain, otg_world_desert, otg_world_coastal, otg_world_urban, otg_world_swamp, otg_world_tundra, otg_world_urban_start, otg_media_type, otg_gen_mode, otg_text_model, otg_image_model ], outputs=[ otg_sequence_preview, otg_config_preview, otg_queue_display, otg_progress_md, otg_world_generate_btn, otg_stop_btn, otg_generated_config, otg_prompts_text ] ).then( otg_process_and_load, inputs=[otg_gen_mode, otg_text_model, otg_image_model, otg_generated_config], outputs=[ otg_progress_md, otg_queue_display, otg_world_generate_btn, otg_stop_btn, otg_config_preview, ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia, ewpwa_current_state_display, ewpwa_state_dropdown ] ) # Timeline generate button otg_timeline_generate_btn.click( otg_start_timeline_workflow, inputs=[ otg_timeline_count, otg_timeline_morning, otg_timeline_midday, otg_timeline_afternoon, otg_timeline_evening, otg_timeline_night, otg_timeline_past, otg_timeline_future, otg_timeline_chrono, otg_media_type, otg_gen_mode, otg_text_model, otg_image_model ], outputs=[ otg_sequence_preview, otg_config_preview, otg_queue_display, otg_progress_md, otg_timeline_generate_btn, otg_stop_btn, otg_generated_config, otg_prompts_text ] ).then( otg_process_and_load, inputs=[otg_gen_mode, otg_text_model, otg_image_model, otg_generated_config], outputs=[ otg_progress_md, otg_queue_display, otg_timeline_generate_btn, otg_stop_btn, otg_config_preview, ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia, ewpwa_current_state_display, ewpwa_state_dropdown ] ) # Emotional Journey generate button otg_song_generate_btn.click( otg_start_song_workflow, inputs=[ otg_song_count, otg_song_arc, otg_song_joy, otg_song_sorrow, otg_song_anger, otg_song_fear, otg_song_hope, otg_song_nostalgia, otg_song_peace, otg_media_type, otg_gen_mode, otg_text_model, otg_image_model ], outputs=[ otg_sequence_preview, otg_config_preview, otg_queue_display, otg_progress_md, otg_song_generate_btn, otg_stop_btn, otg_generated_config, otg_prompts_text ] ).then( otg_process_and_load, inputs=[otg_gen_mode, otg_text_model, otg_image_model, otg_generated_config], outputs=[ otg_progress_md, otg_queue_display, otg_song_generate_btn, otg_stop_btn, otg_config_preview, ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia, ewpwa_current_state_display, ewpwa_state_dropdown ] ) # Mystery generate button otg_mystery_generate_btn.click( otg_start_mystery_workflow, inputs=[ otg_mystery_count, otg_mystery_surface, otg_mystery_shallow, otg_mystery_mid, otg_mystery_deep, otg_mystery_abyss, otg_mystery_gradual, otg_media_type, otg_gen_mode, otg_text_model, otg_image_model ], outputs=[ otg_sequence_preview, otg_config_preview, otg_queue_display, otg_progress_md, otg_mystery_generate_btn, otg_stop_btn, otg_generated_config, otg_prompts_text ] ).then( otg_process_and_load, inputs=[otg_gen_mode, otg_text_model, otg_image_model, otg_generated_config], outputs=[ otg_progress_md, otg_queue_display, otg_mystery_generate_btn, otg_stop_btn, otg_config_preview, ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia, ewpwa_current_state_display, ewpwa_state_dropdown ] ) # Export config with media files as zip def otg_export_config_with_media(config_json): """Export the generated config and all media files as a zip.""" if not config_json or not config_json.strip(): return None, "No config to export. Generate a sequence first." try: import tempfile import zipfile from datetime import datetime # Parse config to find media files config = json.loads(config_json) media_files = [] # Extract all media paths from config for location_key, location_data in config.items(): if isinstance(location_data, dict): for state_key, state_data in location_data.items(): if isinstance(state_data, dict) and 'media' in state_data: media_list = state_data.get('media', []) if isinstance(media_list, list): media_files.extend(media_list) # Create zip file timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") zip_filename = f"game_export_{timestamp}.zip" zip_path = os.path.join(tempfile.gettempdir(), zip_filename) files_included = 0 files_missing = [] with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: # Add config JSON (named "config.json" for import compatibility) zipf.writestr("config.json", config_json) # Add media files to root (not in media/ subfolder) for import compatibility for media_path in media_files: if media_path and isinstance(media_path, str): # Check if file exists if os.path.exists(media_path): # Add to zip root with just filename arcname = os.path.basename(media_path) zipf.write(media_path, arcname) files_included += 1 else: files_missing.append(media_path) # Build status message status = f"Exported: {zip_filename}\n" status += f"- Config: config.json\n" status += f"- Media files: {files_included} included" if files_missing: status += f"\n- Missing files: {len(files_missing)} ({', '.join(files_missing[:3])}{'...' if len(files_missing) > 3 else ''})" return zip_path, status except json.JSONDecodeError as e: return None, f"Invalid JSON: {str(e)}" except Exception as e: return None, f"Export error: {str(e)}" otg_export_btn.click( otg_export_config_with_media, inputs=[otg_config_preview], outputs=[otg_export_file, otg_export_status] ) # AI Prompt Generation Function def generate_ai_assistance_prompt(config_json, prompt_type, focus_area): """Generate a context-aware prompt for AI chat assistance.""" if not config_json or not config_json.strip() or config_json == "{}": return "Please generate a config first before creating an AI assistance prompt." # Auto-detect config type from content detected_type = prompt_type if prompt_type == "auto": config_lower = config_json.lower() if "world" in config_lower or "location_" in config_lower or "terrain" in config_lower: detected_type = "world" elif "timeline" in config_lower or "event_" in config_lower or "morning" in config_lower or "evening" in config_lower: detected_type = "timeline" elif "emotional_journey" in config_lower or "moment_" in config_lower or "feeling" in config_lower: detected_type = "song" elif "investigation" in config_lower or "clue_" in config_lower or "mystery" in config_lower: detected_type = "mystery" elif "adventure" in config_lower or "encounter_" in config_lower or "combat" in config_lower or "dungeon" in config_lower: detected_type = "dnd" elif "scene_" in config_lower or "film" in config_lower or "camera" in config_lower: detected_type = "film" elif "beat_" in config_lower or "act_" in config_lower: detected_type = "beats" else: detected_type = "film" # Default fallback # Type-specific instructions type_instructions = { "world": """This is a WORLD/GEOGRAPHY exploration game config. The story unfolds through location discovery. Key aspects to enhance: - Each location should have distinct atmosphere and secrets - Connections between locations should feel natural (paths, rivers, roads) - Hidden areas reward thorough exploration - NPCs should have reasons to be in specific locations - Environmental storytelling through descriptions""", "timeline": """This is a TIMELINE/CHRONOLOGICAL narrative config. Events unfold in time sequence. Key aspects to enhance: - Each time period should have distinct mood (morning hope, night danger) - Cause and effect between events should be clear - Flashbacks/flash-forwards should reveal crucial information - Pacing should alternate between action and reflection - Time pressure can create tension""", "song": """This is an EMOTIONAL JOURNEY config based on musical/lyrical structure. Key aspects to enhance: - Emotional transitions should feel earned, not jarring - Verses build detail, choruses reinforce themes - The bridge should offer a perspective shift - Sensory details anchor abstract emotions - The arc should have a satisfying resolution""", "mystery": """This is a MYSTERY/INVESTIGATION config using the iceberg model (surface to deep truths). Key aspects to enhance: - Surface clues should be obvious but misleading - Each layer should recontextualize previous discoveries - Red herrings should be plausible but distinguishable - The core truth should be surprising yet inevitable - Character motivations drive the mystery""", "dnd": """This is a D&D/FANTASY ADVENTURE config with encounters and exploration. Key aspects to enhance: - Combat encounters need tactical variety - Social encounters should have multiple resolution paths - Treasure and rewards should feel earned - Boss encounters should be memorable set pieces - Rest points allow strategic resource management""", "film": """This is a FILM/VIDEO SCENES config structured around visual storytelling. Key aspects to enhance: - Each scene needs a clear visual hook - Camera direction implies emotional tone - Transitions between scenes should be motivated - Dialogue should reveal character through subtext - Visual motifs can recur for thematic resonance""", "beats": """This is a STORY BEATS config following professional screenplay structure. Key aspects to enhance: - Each beat should turn the story in a new direction - Character decisions should drive plot, not coincidence - Stakes should escalate through the midpoint - The dark night of the soul needs emotional weight - The climax should pay off earlier setups""" } # Focus area instructions focus_instructions = { "balanced": """Improve the config with balanced attention to: - Richer descriptions (2-3 sentences per state) - 3-4 meaningful choices per state where appropriate - Clear character motivations - Environmental details that support the mood""", "detail": """Focus on ADDING DETAIL to descriptions: - Expand each description to 3-4 vivid sentences - Include sensory details (sight, sound, smell, touch) - Add atmospheric elements (weather, lighting, ambient sounds) - Include small environmental storytelling details - Make locations feel lived-in and real""", "choices": """Focus on ADDING MORE CHOICES and branches: - Ensure each state has 3-4 distinct choices - Add choices that reflect different playstyles (cautious, bold, clever) - Include hidden or conditional choices - Create meaningful branches that reconverge later - Add optional side paths that reward exploration""", "characters": """Focus on DEEPENING CHARACTER MOTIVATIONS: - Give NPCs clear wants, fears, and secrets - Add dialogue that reveals personality - Create relationship dynamics between characters - Include character-specific choices and reactions - Show character growth through the narrative""", "environment": """Focus on ENVIRONMENTAL STORYTELLING: - Add details that imply history without exposition - Include objects that tell stories (old letters, worn paths, abandoned items) - Use weather and time of day to set mood - Create spaces that feel connected to events - Add discoverable lore through exploration""", "tension": """Focus on INCREASING DRAMATIC TENSION: - Add time pressure or urgency where appropriate - Include moments of difficult moral choice - Create setbacks that raise stakes - Add foreshadowing of dangers - Include moments of false safety before reveals""" } # Count states in config try: config = json.loads(config_json) state_count = 0 for section in config.values(): if isinstance(section, dict): state_count += len(section) except: state_count = "unknown" # Build the prompt prompt = f"""I have a game config JSON for an interactive narrative game. Please help me improve and expand it. **CONFIG TYPE:** {detected_type.upper()} **CURRENT SIZE:** {state_count} states **FOCUS:** {focus_area.replace('_', ' ').title()} {type_instructions.get(detected_type, type_instructions['film'])} {focus_instructions.get(focus_area, focus_instructions['balanced'])} **IMPORTANT RULES:** 1. Return ONLY valid JSON - no explanations before or after 2. Keep the exact same structure (location > state > properties) 3. Every state MUST have: "description", "choices" (list), "transitions" (dict mapping choices to state IDs) 4. Do NOT rename existing state IDs - only add new ones 5. Ensure all transitions point to valid state IDs 6. Keep "media" and "media_prompt" fields if present **HERE IS MY CURRENT CONFIG:** ```json {config_json} ``` Please return an improved version of this config with the enhancements described above. Remember: ONLY return valid JSON, nothing else.""" return prompt otg_generate_prompt_btn.click( generate_ai_assistance_prompt, inputs=[otg_config_preview, otg_prompt_type, otg_prompt_focus], outputs=[otg_ai_prompt_output] ) # ==================== GAME PREVIEW TABS (Moved from Portability) ==================== with gr.Tab("Game Preview (2D)"): gr.Markdown("### 2D MovingDotSpace Preview") gr.Markdown("Generate a 2D top-down exploration game from your config.") with gr.Row(): preview_2d_config = gr.Textbox( label="Game Config JSON", lines=8, placeholder='{"village": {"start": {"description": "You arrive.", "choices": ["Enter tavern"], "transitions": {"Enter tavern": "tavern"}}}}', scale=3 ) with gr.Column(scale=1): preview_2d_demo_btn = gr.Button("Load Demo Config", variant="secondary") preview_2d_generate_btn = gr.Button("Generate & Test", variant="primary") preview_2d_status = gr.Markdown("") gr.Markdown("### Game Preview (click inside to focus, use arrow keys to move)") preview_2d_html = gr.HTML( value='
Click "Generate & Test" to preview your game here
', label="Game Preview" ) with gr.Accordion("Generated HTML Code (copy to save)", open=False): preview_2d_code = gr.Code(label="HTML Source", language="html", lines=15) def load_2d_demo(): import os try: demo_path = os.path.join(os.path.dirname(__file__), "sandwich_quest_demo.json") with open(demo_path, 'r', encoding='utf-8') as f: return f.read() except: return '{"village": {"start": {"description": "Demo village.", "choices": ["Explore"], "transitions": {"Explore": "village_explore"}}}}' def generate_2d_preview(config_json): if not config_json or not config_json.strip(): return "Please provide config JSON", '
Please provide a game config JSON
', "" try: from exporters import export_to_movingdotspace explanation, html_code = export_to_movingdotspace(config_json) if html_code: import base64 html_b64 = base64.b64encode(html_code.encode('utf-8')).decode('utf-8') iframe_html = f'' return f"Generated! {explanation}", iframe_html, html_code return f"Failed: {explanation}", '
Generation failed
', "" except Exception as e: return f"Error: {str(e)}", f'
Error: {str(e)}
', "" preview_2d_demo_btn.click(fn=load_2d_demo, outputs=[preview_2d_config]) preview_2d_generate_btn.click( fn=generate_2d_preview, inputs=[preview_2d_config], outputs=[preview_2d_status, preview_2d_html, preview_2d_code] ) with gr.Tab("Game Preview (3D)"): gr.Markdown("### 3D PlayCanvas Preview") gr.Markdown("Preview your game config as a 3D WebGL scene.") with gr.Row(): preview_3d_config = gr.Textbox( label="Game Config JSON", lines=8, placeholder="Paste your game config JSON here...", scale=3 ) with gr.Column(scale=1): preview_3d_demo_btn = gr.Button("Load Demo Config", variant="secondary") preview_3d_generate_btn = gr.Button("Generate 3D Preview", variant="primary") preview_3d_status = gr.Markdown("") preview_3d_html = gr.HTML( value='
Click "Generate 3D Preview" to see your game
', label="3D Preview" ) with gr.Accordion("Generated HTML Code", open=False): preview_3d_code = gr.Code(label="HTML Source", language="html", lines=15) def load_3d_demo(): return '{"castle": {"entrance": {"description": "A grand castle entrance.", "choices": ["Enter", "Leave"], "transitions": {"Enter": "castle_hall", "Leave": "forest"}}}}' def generate_3d_preview(config_json): if not config_json or not config_json.strip(): return "Please provide config JSON", '
Please provide a game config JSON
', "" try: from exporters import export_to_playcanvas_html explanation, html_code = export_to_playcanvas_html(config_json) if html_code: import base64 html_b64 = base64.b64encode(html_code.encode('utf-8')).decode('utf-8') iframe_html = f'' return f"Generated! {explanation}", iframe_html, html_code return f"Failed: {explanation}", '
Generation failed
', "" except Exception as e: return f"Error: {str(e)}", f'
Error: {str(e)}
', "" preview_3d_demo_btn.click(fn=load_3d_demo, outputs=[preview_3d_config]) preview_3d_generate_btn.click( fn=generate_3d_preview, inputs=[preview_3d_config], outputs=[preview_3d_status, preview_3d_html, preview_3d_code] ) # ==================== D&D GAME MASTER (Moved from Config Dev) ==================== create_dnd_gm_tab() # ==================== CONFIG ANALYSIS & IMPROVEMENT (Merged Tab) ==================== create_config_analysis_tab() create_llm_playtest_tab(modelnames) with gr.Tab("Config Development Assistance"): gr.Markdown("## Config Development Assistance") gr.Markdown("Tools and references for creating game configs. Full design theory available in the Design Reference Guide below.") # ==================== STARTING CONSIDERATIONS ==================== gr.Markdown(""" ### Starting Considerations - Where to Begin? Every game config can begin from different creative angles. Pick the approach that matches your inspiration: """) with gr.Row(): with gr.Column(scale=1): gr.Markdown(""" **šŸŒ World Facts / Geography** Start with locations, regions, and how they connect. Build the world first, then populate it. → **Big RPG Scale** tab → Locations """) with gr.Column(scale=1): gr.Markdown(""" **šŸŽ¬ Video/Film Ideas (Writer)** Structure your story using professional beat templates for 90-min films, 30-min TV episodes, or 9-min YouTube videos. → **Story Architect** tab """) with gr.Column(scale=1): gr.Markdown(""" **šŸ“¹ Video/Film Ideas (Videographer)** Start from camera angles, shot composition, visual grammar, and direction notes. Think visually first. → **Story Architect** tab → Visual Grammar """) with gr.Row(): with gr.Column(scale=1): gr.Markdown(""" **šŸŽµ Song / Lyric Ideas** Transform emotional music or poetry into journey-based games. Each verse becomes a location or mood. → **Source Content to Games** tab """) with gr.Column(scale=1): gr.Markdown(""" **ā±ļø Timeline Events** Build narrative beats positioned on a visual timeline. Great for story-driven games with clear progression. → **Story Graph** tab or **Generate Config** → Timeline Generator """) with gr.Column(scale=1): gr.Markdown(""" **šŸ“š Existing Structures** Use D&D monsters/items, story templates, or classic narrative structures as building blocks. → **D&D 5e SRD** tab, **Mermaid Diagrams** tab """) with gr.Row(): with gr.Column(scale=1): gr.Markdown(""" **🧠 Character Psychology** Create deeply motivated characters that drive the story. Define wants, flaws, and psychological profiles. → **Narrative Engine** tab → Character Generator """) with gr.Column(scale=1): gr.Markdown(""" **šŸ”® Mystery / Hidden Depth** Layer information with surface events hiding deeper truths. Use the 5-layer iceberg model. → **Narrative Engine** tab → Mystery Layers """) with gr.Column(scale=1): gr.Markdown(""" **āš”ļø Faction Politics** Design allegiances, hierarchies, and reputation systems. Build conflict through competing groups. → **Big RPG Scale** tab → Factions """) # ==================== DESIGN REFERENCE GUIDE ==================== # Random tips data for randomiser DESIGN_TIPS = { "core": [ "Make story-based games using mechanics-based games (Chess, Poker, Sudoku) as a conduit", "Sometimes a fun game includes unfairness - Elden Ring uses controls and movement restrictions", "Minimise the cost of exploration so players can explore more (Jonas Tyroller)", "Every theme can be turned into a battle story (resource accumulation across a map)", "Story structure: Ending Conditions → Villain → Travel/Politics/Combat → Characters", "A game is alive when the same decisions won't work over and over", "Boss fights create memorable moments through controlled unfairness", "The best games teach mechanics through play, not tutorials", "Stakes make choices matter - what can the player lose?", "Pacing is about alternating tension and release" ], "blocks": [ "Locations: Jungle, Sea, Desert, Snow, City, Village, Space - each has unique mood", "Character Relations: Friend or foe - but the best stories blur this line", "Conflict Origins: Betrayal, lack of sympathy, unfair expectations, misinterpretation", "GTA Heists: Replayability through overlapping branching narratives", "Tekken: 2/3 mistakes = lost round (casino-style stakes)", "Elden Ring: Storytelling by traversal of map, environmental narrative", "Battlefront: Elites amongst Commoners creates power fantasy variation", "Purpose: Unpredictable Nuances, Simulation, Time capsule, Tangible Metaphor", "Every location should have a secret or hidden element", "NPCs should have their own goals, not just serve the player" ], "workflow": [ "Timeline: Mermaid Diagram → Story → Initial JSON → Corrections → Media → Assets", "Remix an existing config to learn the format quickly", "Ask LLM to generate, then manually fix edge cases", "Endless combination testing reveals unexpected interactions", "Write by hand with format assistance for full control", "Test early, test often - broken configs are harder to fix later", "Keep a library of working configs as templates", "Version control your configs - git is your friend", "Document your design decisions for future reference", "Playtest with fresh eyes after a break" ] } def get_random_design_tip(): """Get random tips from each category.""" import random core = random.choice(DESIGN_TIPS["core"]) blocks = random.choice(DESIGN_TIPS["blocks"]) workflow = random.choice(DESIGN_TIPS["workflow"]) return f"**šŸŽ² Random Design Tips:**\n\n**Core:** {core}\n\n**Building Block:** {blocks}\n\n**Workflow:** {workflow}" with gr.Accordion("Design Reference Guide (Theory & Ideas)", open=False): gr.Markdown("*Full design theory, game fundamentals, and workflow documentation.*") with gr.Row(): random_tip_btn = gr.Button("šŸŽ² Random Tips", variant="secondary", size="sm") random_tip_output = gr.Markdown("") random_tip_btn.click(fn=get_random_design_tip, outputs=[random_tip_output]) with gr.Accordion("Core Principles", open=False): gr.Markdown(""" **End Goal:** Make story-based games using mechanics-based games (Chess, Poker, Sudoku, Rubiks Cube, etc.) as a conduit. **Key Ideas:** - Sometimes a fun game includes unfairness - Elden Ring (Controls and movement restrictions), Boss fights - Minimise the cost of exploration so you can explore more ([Jonas Tyroller](https://youtu.be/o5K0uqhxgsE)) - Every theme can be turned into a battle story (resource accumulation across a map) - Story structure: Ending Conditions → Main Villain/Antagonist → Travel, Politics, Combat → Characters - A game is alive when the same decisions won't work over and over """) with gr.Accordion("Story Building Blocks", open=False): gr.Markdown(""" **Locations:** Jungle, Sea, Desert, Snow, City, Village, Space **Character Relations:** Friend or foe **Conflict Origins:** Betrayal, lack of sympathy, unfair expectations, misinterpretation of actions **Purpose Types:** Unpredictable Nuances, Simulation, Time capsule, Tangible Metaphor, Song Concept, Advert as game **Structural Inspirations:** - GTA Heists - Replayability and stakes, overlapping branching narratives - Tekken - 2/3 mistakes = lost round (casino-style stakes) - Elden Ring - Storytelling by traversal of map - Battlefront - Elites amongst Commoners """) with gr.Accordion("Workflow Overview", open=False): gr.Markdown(""" **Timeline Workflow:** 1. [Pre-creation] Mermaid Diagram → Story 2. [Creation] Initial JSON (LLM + manual fixes) 3. [Post-creation] JSON Corrections → Media prompts → Asset Generation → JSON Media population **Config Writing Approaches:** - Remix an existing config - Ask LLM to generate one - Endless combination testing - Write by hand with format assistance """) # ==================== GENERATE CONFIG TAB ==================== with gr.Tab("Generate Config"): gr.Markdown("### Config Generation Tools") with gr.Accordion("Timeline Generator", open=True): gr.Markdown("Generate a random timeline and story based on UI elements and story events. Use this as a starting point for LLM refinement.") with gr.Row(): cda_timeline_output = gr.Textbox(label="Generated Timeline", lines=15) cda_story_output = gr.Textbox(label="Generated Story", lines=15) with gr.Row(): cda_config_output = gr.Code(label="Generated Config JSON", language="json", lines=10) with gr.Row(): cda_story_points = gr.Slider(minimum=1, value=10, step=1, maximum=30, label="Story Points") cda_ui_points = gr.Slider(minimum=1, value=10, step=1, maximum=30, label="UI Points") with gr.Row(): cda_num_lists = gr.Slider(minimum=1, maximum=len(all_idea_lists), step=1, label="Idea Lists to Use", value=3) cda_items_per_list = gr.Slider(minimum=1, maximum=10, step=1, label="Items per List", value=3) with gr.Row(): cda_include_games = gr.Checkbox(label="Include Game Inspirations", value=True) cda_include_multiplayer = gr.Checkbox(label="Include Multiplayer Features", value=True) with gr.Row(): cda_randomise_btn = gr.Button("šŸŽ² Randomise All", variant="secondary") cda_generate_btn = gr.Button("Generate Story and Timeline", variant="primary") def randomise_timeline_settings(): """Randomise all Timeline Generator settings.""" import random return ( random.randint(5, 25), # story_points random.randint(5, 25), # ui_points random.randint(1, min(5, len(all_idea_lists))), # num_lists random.randint(2, 7), # items_per_list random.choice([True, False]), # include_games random.choice([True, False]) # include_multiplayer ) cda_randomise_btn.click( fn=randomise_timeline_settings, outputs=[cda_story_points, cda_ui_points, cda_num_lists, cda_items_per_list, cda_include_games, cda_include_multiplayer] ) with gr.Row(): cda_suggestions = gr.Textbox(label="Random Suggestions", lines=5) cda_selected_lists = gr.Textbox(label="Selected Idea Lists", lines=2) cda_generate_btn.click( generate_story_and_timeline, inputs=[cda_story_points, cda_ui_points, cda_num_lists, cda_items_per_list, cda_include_games, cda_include_multiplayer], outputs=[cda_timeline_output, cda_story_output, cda_config_output, cda_suggestions, cda_selected_lists] ) with gr.Accordion("Narrative Construction Tool (tnct)", open=False): gr.Markdown("Build narratives using character relationships and interpersonal events.") tnct_ui() with gr.Accordion("Worldbuilding - Bible Stories as Templates", open=False): bible_story_elements() # ==================== STORY GRAPH TAB (Config Development Device) ==================== create_story_graph_tab() # ==================== BIG RPG SCALE TAB (Config Development Device) ==================== create_big_rpg_scale_tab() # ==================== MERMAID DIAGRAMS TAB ==================== with gr.Tab("Mermaid Diagrams"): gr.Markdown("### Visual Story Structure Planning") gr.Markdown("Use Mermaid diagrams to plan your story structure before converting to JSON config.") def get_random_mermaid_template(): """Get a random mermaid template from either story structures or concept blending.""" import random all_templates = {**mermaidstorystructures, **examplemermaidconceptblendingstrutures} name = random.choice(list(all_templates.keys())) return f"**{name}**", all_templates[name] with gr.Row(): cda_mermaid_random_btn = gr.Button("šŸŽ² Random Template", variant="secondary") cda_mermaid_load_btn = gr.Button("Load Mermaid.live Editor", variant="primary") cda_random_template_name = gr.Markdown("*Click 'Random Template' to see a random story structure*") cda_random_template_code = gr.Code(label="Random Template", language=None, lines=10) cda_mermaid_random_btn.click( fn=get_random_mermaid_template, outputs=[cda_random_template_name, cda_random_template_code] ) cda_mermaid_iframe = gr.HTML("") cda_mermaid_load_btn.click( fn=lambda: "", outputs=cda_mermaid_iframe ) with gr.Accordion("Story Structure Templates", open=False): for key, item in mermaidstorystructures.items(): with gr.Accordion(key, open=False): gr.Code(item, label=key, language=None) with gr.Accordion("Concept Blending Examples", open=False): for key, item in examplemermaidconceptblendingstrutures.items(): gr.Code(item, label=key, language=None) # ==================== D&D 5E SRD REFERENCE TAB ==================== with gr.Tab("D&D 5e SRD"): gr.Markdown("### Dungeons & Dragons 5th Edition - System Reference Document") with gr.Accordion("What is D&D 5e?", open=True): gr.Markdown(""" **Dungeons & Dragons 5th Edition** is a tabletop role-playing game (TTRPG) published by Wizards of the Coast. **Core Concepts:** - **Players** create characters with races (Elf, Dwarf, Human, etc.) and classes (Fighter, Wizard, Rogue, etc.) - **Dungeon Master (DM)** narrates the story, controls NPCs/monsters, and adjudicates rules - **Dice-based resolution** - primarily the d20 (20-sided die) for skill checks, attacks, and saves - **Combat** uses turn-based initiative with movement, actions, and reactions - **Character progression** through levels 1-20 with increasing abilities and spells **Why use D&D for game config inspiration?** - Rich ecosystem of monsters, items, spells, and locations - Well-balanced mechanics tested over decades - Familiar framework for many players - Excellent source for fantasy game content """) with gr.Accordion("License Information (CC-BY-4.0)", open=False): gr.Markdown(""" **System Reference Document 5.1 (SRD 5.1)** is available under **Creative Commons Attribution 4.0 International (CC-BY-4.0)**. **What this means:** - āœ… You CAN use SRD 5.1 content in your games (commercial or non-commercial) - āœ… You CAN modify and adapt the content - āœ… You CAN share and redistribute - āš ļø You MUST give appropriate credit to Wizards of the Coast - āŒ You CANNOT use D&D trademarks (like "Dungeons & Dragons" in your product name) **Attribution Example:** > "This work includes material from the System Reference Document 5.1 ("SRD 5.1") by Wizards of the Coast LLC, available at https://dnd.wizards.com/resources/systems-reference-document. The SRD 5.1 is licensed under the Creative Commons Attribution 4.0 International License." **Official Sources:** - [SRD 5.1 PDF](https://dnd.wizards.com/resources/systems-reference-document) - [CC-BY-4.0 License](https://creativecommons.org/licenses/by/4.0/) """) with gr.Accordion("Random Idea Generator (SRD Content)", open=True): gr.Markdown("Generate random D&D elements for game inspiration. All content from SRD 5.1.") # SRD Monster list (subset for demo) DND_MONSTERS = [ "Aboleth", "Animated Armor", "Banshee", "Basilisk", "Behir", "Beholder", "Bugbear", "Bulette", "Centaur", "Chimera", "Cockatrice", "Couatl", "Cyclops", "Death Knight", "Doppelganger", "Dragon (Red)", "Dragon (Gold)", "Dragon (Black)", "Drider", "Dryad", "Duergar", "Elemental (Fire)", "Elemental (Water)", "Elemental (Earth)", "Elemental (Air)", "Ettercap", "Ettin", "Gargoyle", "Genie (Djinni)", "Genie (Efreeti)", "Ghost", "Ghoul", "Giant (Hill)", "Giant (Stone)", "Giant (Frost)", "Giant (Fire)", "Giant (Cloud)", "Giant (Storm)", "Gibbering Mouther", "Gnoll", "Goblin", "Golem (Clay)", "Golem (Stone)", "Golem (Iron)", "Gorgon", "Green Hag", "Griffon", "Harpy", "Hell Hound", "Hippogriff", "Hobgoblin", "Hydra", "Intellect Devourer", "Invisible Stalker", "Kobold", "Kraken", "Lamia", "Lich", "Lizardfolk", "Manticore", "Medusa", "Merfolk", "Mimic", "Mind Flayer", "Minotaur", "Mummy", "Naga (Guardian)", "Nightmare", "Ogre", "Oni", "Orc", "Otyugh", "Owlbear", "Pegasus", "Phase Spider", "Piercer", "Pixie", "Pseudodragon", "Purple Worm", "Rakshasa", "Remorhaz", "Roc", "Roper", "Rust Monster", "Sahuagin", "Salamander", "Satyr", "Shambling Mound", "Shield Guardian", "Skeleton", "Specter", "Sphinx", "Sprite", "Stirge", "Succubus/Incubus", "Tarrasque", "Treant", "Troll", "Unicorn", "Vampire", "Wight", "Will-o'-Wisp", "Wraith", "Wyvern", "Xorn", "Zombie" ] DND_SPELLS = [ "Fireball", "Lightning Bolt", "Magic Missile", "Shield", "Mage Armor", "Detect Magic", "Dispel Magic", "Counterspell", "Fly", "Invisibility", "Polymorph", "Teleport", "Wish", "Power Word Kill", "Meteor Swarm", "Time Stop", "Gate", "True Resurrection", "Heal", "Cure Wounds", "Revivify", "Raise Dead", "Greater Restoration", "Mass Heal", "Bless", "Spirit Guardians", "Guiding Bolt", "Sacred Flame", "Banishment", "Hold Person", "Charm Person", "Suggestion", "Dominate Person", "Fear", "Sleep", "Hypnotic Pattern", "Wall of Fire", "Wall of Force", "Cloudkill", "Cone of Cold", "Chain Lightning", "Disintegrate", "Finger of Death", "Prismatic Spray", "Sunburst", "Earthquake" ] DND_ITEMS = [ "Bag of Holding", "Cloak of Elvenkind", "Boots of Speed", "Ring of Protection", "Wand of Fireballs", "Staff of Power", "Vorpal Sword", "Holy Avenger", "Flame Tongue", "Frost Brand", "Dancing Sword", "Luck Blade", "Rod of Lordly Might", "Sphere of Annihilation", "Deck of Many Things", "Portable Hole", "Immovable Rod", "Rope of Climbing", "Amulet of Proof Against Detection", "Belt of Giant Strength", "Bracers of Defense", "Carpet of Flying", "Crystal Ball", "Eversmoking Bottle", "Figurine of Wondrous Power", "Gauntlets of Ogre Power", "Headband of Intellect", "Helm of Brilliance", "Horn of Blasting", "Ioun Stone", "Lantern of Revealing", "Medallion of Thoughts", "Mirror of Life Trapping", "Necklace of Fireballs", "Periapt of Health", "Robe of Eyes", "Scarab of Protection", "Talisman of Pure Good", "Wings of Flying" ] DND_CLASSES = [ "Barbarian - Primal warriors fueled by rage", "Bard - Magical performers and jack-of-all-trades", "Cleric - Divine spellcasters serving a deity", "Druid - Nature-based spellcasters who shapeshift", "Fighter - Masters of martial combat", "Monk - Martial artists harnessing ki energy", "Paladin - Holy warriors bound by an oath", "Ranger - Wilderness experts and hunters", "Rogue - Stealthy specialists and skill experts", "Sorcerer - Innate magic users with metamagic", "Warlock - Spellcasters with otherworldly patrons", "Wizard - Scholarly magic users with spellbooks" ] DND_LOCATIONS = [ "Ancient Dragon Lair", "Abandoned Dwarven Mine", "Cursed Graveyard", "Floating Castle", "Underground City (Underdark)", "Haunted Manor", "Wizard's Tower", "Sunken Temple", "Frost Giant Stronghold", "Volcanic Forge", "Feywild Glade", "Shadowfell Crossing", "Planar Portal Chamber", "Lich's Phylactery Vault", "Beholder's Lair", "Mind Flayer Colony", "Pirate Cove", "Desert Pyramid", "Jungle Ziggurat", "Arctic Glacier Dungeon" ] import random def generate_dnd_ideas(num_monsters, num_spells, num_items, include_class, include_location): result = [] if num_monsters > 0: monsters = random.sample(DND_MONSTERS, min(num_monsters, len(DND_MONSTERS))) result.append(f"**Monsters ({num_monsters}):**\n" + "\n".join(f"• {m}" for m in monsters)) if num_spells > 0: spells = random.sample(DND_SPELLS, min(num_spells, len(DND_SPELLS))) result.append(f"**Spells ({num_spells}):**\n" + "\n".join(f"• {s}" for s in spells)) if num_items > 0: items = random.sample(DND_ITEMS, min(num_items, len(DND_ITEMS))) result.append(f"**Magic Items ({num_items}):**\n" + "\n".join(f"• {i}" for i in items)) if include_class: char_class = random.choice(DND_CLASSES) result.append(f"**Suggested Class:**\n• {char_class}") if include_location: location = random.choice(DND_LOCATIONS) result.append(f"**Location Idea:**\n• {location}") return "\n\n".join(result) if result else "Select at least one category!" with gr.Row(): dnd_num_monsters = gr.Slider(minimum=0, maximum=10, value=3, step=1, label="Number of Monsters") dnd_num_spells = gr.Slider(minimum=0, maximum=10, value=3, step=1, label="Number of Spells") dnd_num_items = gr.Slider(minimum=0, maximum=10, value=2, step=1, label="Number of Magic Items") with gr.Row(): dnd_include_class = gr.Checkbox(label="Include Random Class", value=True) dnd_include_location = gr.Checkbox(label="Include Random Location", value=True) dnd_generate_btn = gr.Button("Generate Random D&D Ideas", variant="primary") dnd_output = gr.Markdown(label="Generated Ideas") dnd_generate_btn.click( generate_dnd_ideas, inputs=[dnd_num_monsters, dnd_num_spells, dnd_num_items, dnd_include_class, dnd_include_location], outputs=dnd_output ) with gr.Accordion("Quick Reference - Combat Basics", open=False): gr.Markdown(""" **Combat Round Structure:** 1. **Roll Initiative** (d20 + Dexterity modifier) - determines turn order 2. **Take Turns** - each creature gets: Movement + Action + Bonus Action (if available) 3. **Repeat** until combat ends **Action Types:** - **Attack** - Make a weapon or spell attack - **Cast a Spell** - Use a spell (some are bonus actions) - **Dash** - Double your movement - **Disengage** - Move without provoking opportunity attacks - **Dodge** - Attacks against you have disadvantage - **Help** - Give an ally advantage on their next check - **Hide** - Attempt to become hidden - **Ready** - Prepare an action for a trigger **Advantage/Disadvantage:** - **Advantage** = Roll 2d20, take the higher - **Disadvantage** = Roll 2d20, take the lower **For Text Games:** Consider simplifying to choice-based combat with stat checks rather than full dice simulation. """) with gr.Accordion("SRD Lookup (Open5e API)", open=True): gr.Markdown("*Search the full D&D 5e SRD database via Open5e API for detailed monster stats, spell descriptions, and more.*") # Random search terms for "I'm Feeling Lucky" SRD_RANDOM_SEARCHES = { "monsters": ["dragon", "goblin", "orc", "zombie", "skeleton", "wolf", "giant", "demon", "troll", "ogre", "vampire", "ghost", "spider", "bear", "elemental"], "spells": ["fire", "ice", "lightning", "heal", "shield", "teleport", "invisibility", "charm", "sleep", "detect", "summon", "cure", "protection", "dispel", "light"], "magicitems": ["sword", "ring", "staff", "wand", "cloak", "boots", "belt", "amulet", "potion", "bag", "helm", "gauntlets", "armor", "shield", "rod"] } def srd_feeling_lucky(): """Pick a random category and search term, then search.""" import random category = random.choice(["monsters", "spells", "magicitems"]) search_term = random.choice(SRD_RANDOM_SEARCHES[category]) # Return the category, search term (to update inputs) return category, search_term with gr.Row(): srd_api_category = gr.Dropdown( label="Category", choices=[ ("Monsters", "monsters"), ("Spells", "spells"), ("Magic Items", "magicitems"), ("Conditions", "conditions"), ("Classes", "classes") ], value="monsters" ) srd_api_search = gr.Textbox( label="Search", placeholder="goblin, fireball, vorpal...", scale=2 ) srd_api_lucky_btn = gr.Button("šŸŽ² Lucky", variant="secondary") srd_api_search_btn = gr.Button("Search", variant="primary") srd_api_lucky_btn.click( fn=srd_feeling_lucky, outputs=[srd_api_category, srd_api_search] ) srd_api_results = gr.Markdown("*Enter a search term and click Search to query the Open5e API*") with gr.Row(): srd_api_detail_slug = gr.Textbox( label="Get Full Details (slug)", placeholder="goblin, fireball, vorpal-sword...", info="Enter the item's slug (lowercase, hyphenated name) from search results" ) srd_api_detail_btn = gr.Button("Get Full Stats") srd_api_detail_output = gr.Markdown("") def srd_api_search_handler(category, query): """Handle SRD API search.""" if not query.strip(): return "Please enter a search term" if category == "monsters": return search_monsters(query) elif category == "spells": return search_spells(query) elif category == "magicitems": return search_magicitems(query) elif category == "conditions": return search_conditions(query) elif category == "classes": return search_classes(query) return "Select a category" def srd_api_detail_handler(category, slug): """Handle SRD API detail lookup.""" if not slug: return "Enter a slug to get details" slug = slug.lower().strip().replace(" ", "-") if category == "monsters": return get_monster_details(slug) elif category == "spells": return get_spell_details(slug) elif category == "magicitems": return get_magicitem_details(slug) return "Detail view available for Monsters, Spells, and Magic Items" srd_api_search_btn.click( fn=srd_api_search_handler, inputs=[srd_api_category, srd_api_search], outputs=[srd_api_results] ) srd_api_detail_btn.click( fn=srd_api_detail_handler, inputs=[srd_api_category, srd_api_detail_slug], outputs=[srd_api_detail_output] ) gr.Markdown(""" --- *Live data from [Open5e API](https://open5e.com/) - search returns up to 10 results. Use slugs (e.g., "ancient-red-dragon") for full stat blocks.* """) # ==================== STORY ARCHITECT TAB ==================== create_story_architect_tab() # ==================== NARRATIVE ENGINE TAB ==================== create_narrative_engine_tab() # ==================== SOURCE CONTENT TO GAMES TAB ==================== with gr.Tab("Source Content to Games"): gr.Markdown("""## Convert Any Text to Game Configs **Input Sources:** - Textbooks / Educational materials → Interactive learning games - Memes / Sayings / Quotes → Decision-based humor games - Song lyrics / Poetry → Emotional journey games - Books / Stories / Scripts → Narrative adventures **NLP-Guided Process:** 1. Extract key concepts, themes, characters 2. Identify decision points and consequences 3. Map to location → state → choices structure 4. Generate valid JSON config """) with gr.Accordion("Prompts for Each Source Type", open=True): gr.Markdown(""" ### Textbook/Educational Material ``` Convert this educational content into a text adventure game config: [PASTE CONTENT] Create locations for each major concept. Each location should: - Have a description explaining the concept - Offer choices that test understanding - Include consequences that reinforce correct/incorrect answers Output as JSON with this structure: {"location": {"state": {"description": "...", "choices": [...]}}} ``` ### Song Lyrics/Poetry ``` Transform these lyrics into an emotional journey game: [PASTE LYRICS] Each verse = a location. Choices reflect the emotional themes. The chorus can be a recurring location or state change. Output as JSON game config. ``` ### Meme/Saying/Quote ``` Create a short decision game based on this saying: [PASTE QUOTE] The game should explore the meaning through 3-5 choices. Each choice demonstrates understanding or misunderstanding of the wisdom. Output as JSON game config. ``` ### Book/Story Chapter ``` Convert this story excerpt into an interactive adventure: [PASTE TEXT] Identify: characters, locations, key decisions, consequences. Create branching paths where reader choices affect outcomes. Output as JSON game config. ``` """) # ==================== GEMMA SCOPE ANALYSIS TAB ==================== with gr.Tab("Gemma Scope Analysis"): gr.Markdown("""## Analyze Prompt Features with Gemma Scope 2 See which internal features activate when generating game configs. Use this to understand what patterns lead to **interesting** vs **predictable** outputs. """) gr.HTML(''' ''') gr.Markdown("[Open SAE Analyzer in new tab](https://huggingface.co/spaces/KwabsHug/TestSAEGemmaScope)") with gr.Accordion("Understanding Feature IDs", open=False): gr.Markdown(""" ## Gemma Scope Naming Convention A feature ID like `gemma-2-2b_12-gemmascope-res-16k_4667` breaks down as: | Component | Meaning | |-----------|---------| | `gemma-2-2b` | The base language model being analyzed | | `12` | Layer 12 - middle layer where abstract concepts form | | `gemmascope` | The Gemma Scope SAE project | | `res` | **Residual stream** - the main "highway" of information | | `16k` | SAE has 16,384 learned features | | `4667` | This specific feature's ID | ### What Different Layers Capture | Layer Range | What It Captures | |-------------|------------------| | 0-5 | Basic syntax, token patterns, grammar | | 6-12 | Concepts, word meanings, simple relationships | | 13-18 | Abstract reasoning, complex semantics | | 19-25 | Output formatting, final predictions | **Layer 12** (default) is good for capturing meaningful concepts without being too low-level or too output-focused. """) with gr.Accordion("About Gemma Scope 2", open=False): gr.Markdown(""" **What is Gemma Scope 2?** Sparse Autoencoders (SAEs) that decompose model activations into interpretable features. Think of it as a "microscope" for looking inside the AI model. **Use Cases for Game Config Development:** - **Plan interesting configs**: Identify which features lead to creative outputs - **Plan predictable configs**: Find patterns for reliable/consistent results - Analyze feature activations for different game mechanics (combat, exploration, dialogue) - Debug unexpected LLM outputs by seeing which features activated **How to Use:** 1. Enter a prompt you'd use for game config generation 2. Click "Analyze Features" to see which internal features activate 3. Look up specific features to understand what they represent 4. Compare different prompts to understand what patterns the model uses **Resources:** - [Neuronpedia Demo](https://www.neuronpedia.org/gemma-scope-2) - [Technical Paper](https://storage.googleapis.com/deepmind-media/DeepMind.com/Blog/gemma-scope-2-helping-the-ai-safety-community-deepen-understanding-of-complex-language-model-behavior/Gemma_Scope_2_Technical_Paper.pdf) - [SAELens Library](https://github.com/jbloomAus/SAELens) """) # ==================== VIDEOGRAPHER PERSPECTIVE TAB ==================== # NOTE: T5Gemma2 moved to Media Studio → Generate tab with gr.Tab("Videographer Perspective"): gr.Markdown("""## Videographer Perspective for Game Configs Think about your game config like a **film director** or **cinematographer**. Video is now a supported media type - use these concepts to enhance storytelling. """) with gr.Accordion("Shot Types & When to Use Them", open=True): gr.Markdown(""" **Establishing Shot** - Wide view showing the environment - Use for: Location introductions, setting the scene - Config tip: First state in a new location should have establishing imagery/video **Close-Up** - Tight focus on face/object - Use for: Emotional moments, important items, decision points - Config tip: Key choices or reveals deserve close-up media **Medium Shot** - Waist-up framing - Use for: Dialogue, character interactions - Config tip: Standard conversation states **Over-the-Shoulder** - Camera behind one character looking at another - Use for: Conversations, confrontations - Config tip: States where player is observing/listening to NPCs **POV (Point of View)** - What the character sees - Use for: Exploration, discovery, immersion - Config tip: Investigation states, finding clues **Dutch Angle** - Tilted camera - Use for: Unease, disorientation, something wrong - Config tip: Horror/thriller moments, betrayals """) with gr.Accordion("Pacing & Rhythm", open=False): gr.Markdown(""" **Fast Cutting** - Quick transitions between shots - Creates: Tension, action, urgency - Config tip: Short descriptions, many quick choices, time pressure **Long Takes** - Extended continuous shots - Creates: Immersion, realism, building tension - Config tip: Detailed descriptions, fewer choices, let moments breathe **Montage** - Series of shots showing passage of time/progress - Creates: Progression, training, travel - Config tip: Summary states, "time passes" transitions **Parallel Editing** - Cutting between simultaneous events - Creates: Suspense, showing cause/effect - Config tip: State variables tracking multiple storylines """) with gr.Accordion("Lighting & Mood", open=False): gr.Markdown(""" **High Key Lighting** - Bright, even, minimal shadows - Mood: Happy, safe, comedic, optimistic - Config tip: Describe bright environments, daylight scenes **Low Key Lighting** - Dark, strong shadows, contrast - Mood: Mysterious, dangerous, dramatic, noir - Config tip: Describe shadows, dim lighting, hidden corners **Practical Lighting** - Light sources visible in scene - Mood: Realistic, immersive - Config tip: Mention candles, lamps, screens as light sources **Color Temperature** - Warm (orange/yellow): Comfort, nostalgia, intimacy - Cool (blue/green): Isolation, technology, unease - Config tip: Include color descriptions in media prompts """) with gr.Accordion("Camera Movement Concepts", open=False): gr.Markdown(""" **Static Camera** - No movement - Effect: Stability, observation, documentation - Config tip: Standard descriptive states **Pan** - Camera rotates left/right - Effect: Revealing space, following action - Config tip: Descriptions that scan across a scene **Tilt** - Camera rotates up/down - Effect: Showing scale, power dynamics - Config tip: Looking up at imposing structures, down at fallen enemies **Dolly/Tracking** - Camera moves through space - Effect: Following subject, exploration - Config tip: Descriptions of moving through corridors, chasing **Zoom** - Lens adjustment (not camera movement) - Effect: Focusing attention, psychological shift - Config tip: Transitioning from wide context to specific detail """) with gr.Accordion("Video Generation Prompts", open=True): gr.Markdown(""" ### Prompt Templates for Video Media **Establishing Shot:** ``` Wide cinematic shot of [LOCATION], [TIME OF DAY], [WEATHER]. Camera slowly pans across [KEY FEATURES]. [LIGHTING DESCRIPTION]. ``` **Character Introduction:** ``` Medium shot of [CHARACTER], [CLOTHING/APPEARANCE]. [ACTION/POSE]. [EXPRESSION]. [BACKGROUND ELEMENTS]. ``` **Action Sequence:** ``` Dynamic tracking shot following [CHARACTER] as they [ACTION]. Fast-paced movement, [ENVIRONMENT DETAILS]. Urgent atmosphere. ``` **Emotional Moment:** ``` Close-up on [CHARACTER]'s face showing [EMOTION]. Soft lighting, shallow depth of field. [SUBTLE MOVEMENT]. ``` **Suspense/Horror:** ``` POV shot moving slowly through [DARK LOCATION]. Minimal lighting, shadows moving. Something glimpsed in periphery. ``` """) with gr.Accordion("Story Structure Through Video Lens", open=False): gr.Markdown(""" **Three-Act Structure for Videos:** **Act 1 - Setup (25%)** - Establishing shots of world - Character introductions (medium shots) - Normal world before conflict **Act 2 - Confrontation (50%)** - Increasing close-ups as tension rises - More dynamic camera movements - Parallel editing for multiple storylines - Low key lighting as stakes increase **Act 3 - Resolution (25%)** - Climax: Rapid cutting, close-ups, dynamic movement - Resolution: Return to longer takes, breathing room - Final shot: Often mirrors opening but transformed **Apply to Configs:** - Early locations: Establishing shots, bright lighting - Middle locations: More variety, building tension - Late game: Intimate shots, dramatic lighting - Endings: Reflect the journey visually """) with gr.Accordion("65 Classic Film Scenarios", open=False): gr.Markdown(""" ### Frequently Reused Film Scenarios These scenarios appear across countless films. Use them as templates for game states. **OPENINGS & INTRODUCTIONS** 1. **Dawn Patrol** - Character wakes up, morning routine reveals personality/situation 2. **The Arrival** - Protagonist enters new location (city, building, world) for first time 3. **In Medias Res** - Opens mid-action, audience catches up 4. **The Funeral** - Character death sets story in motion, mourners gathered 5. **Voiceover Reflection** - Older character narrates past events we're about to see **TENSION & SUSPENSE** 6. **The Ticking Clock** - Countdown visible/mentioned, deadline approaching 7. **Hiding in Plain Sight** - Character conceals identity among enemies 8. **The Stakeout** - Characters wait and watch from vehicle/building 9. **Parallel Editing Chase** - Cut between pursuer and pursued 10. **The Interrogation** - Character questioned under pressure (police, villain, etc.) 11. **Eavesdropping** - Character overhears crucial conversation 12. **The Setup/Double-Cross** - Trusted ally reveals betrayal 13. **Trapped in Enclosed Space** - Elevator, room, vehicle - no escape 14. **The Hostage Situation** - Loved one held, demands made 15. **Walking Into a Trap** - Audience knows danger character doesn't **ACTION & CONFLICT** 16. **The Standoff** - Multiple parties aim weapons, no one shoots first 17. **The Bar Fight** - Violence erupts in drinking establishment 18. **Car Chase Through City** - Vehicles weave through traffic, obstacles 19. **Rooftop Confrontation** - Final battle on building top, city below 20. **The Heist Execution** - Plan unfolds step by step (with complications) 21. **Training Montage** - Character improves skills over compressed time 22. **The Last Stand** - Outnumbered defenders hold position 23. **One vs Many** - Single fighter takes on multiple opponents 24. **The Duel** - Two opponents face off, formal or informal 25. **Escape Sequence** - Character flees captivity/danger **EMOTIONAL MOMENTS** 26. **The Confession** - Character admits truth (love, crime, secret) 27. **Deathbed Scene** - Dying character's final words/wishes 28. **The Reunion** - Long-separated characters meet again 29. **Breaking the News** - Character learns devastating information 30. **The Sacrifice** - Character gives up something precious for others 31. **Saying Goodbye** - Characters part ways, possibly forever 32. **The Breakdown** - Character's composure finally cracks 33. **Reconciliation** - Estranged characters make peace 34. **The Proposal** - Marriage or significant commitment offered 35. **Visiting the Grave** - Character speaks to deceased at burial site **DISCOVERY & REVELATION** 36. **Finding the Body** - Character discovers corpse 37. **The Evidence Room** - Character finds proof of conspiracy/truth 38. **Flashback Reveal** - Past event recontextualizes everything 39. **The Twist Revealed** - Major plot revelation changes understanding 40. **Reading the Letter/Document** - Written words deliver crucial info 41. **Surveillance Footage** - Character watches recording of key event 42. **The Photograph** - Image reveals connection or identity 43. **Decoding the Message** - Cipher/puzzle solved, meaning clear **SOCIAL SCENARIOS** 44. **The Dinner Party** - Tension beneath polite social gathering 45. **The Job Interview** - Character proves worth or fails to 46. **Meeting the Parents** - Romantic partner meets family 47. **The Courtroom** - Legal proceedings, testimony, verdict 48. **Press Conference** - Public statement, reporters' questions 49. **The Gala/Ball** - Formal event, everyone dressed up, intrigue beneath 50. **The Wake/Reception** - Social gathering after significant event **ENDINGS & CONCLUSIONS** 51. **Walking Into the Sunset** - Hero departs, back to camera, horizon ahead 52. **The Circular Return** - Final scene mirrors opening, showing change 53. **Freeze Frame** - Action stops, often with voiceover or text overlay 54. **The Bittersweet Victory** - Won but at great cost, hollow celebration 55. **New Dawn** - Sun rises on changed world/character, hope restored 56. **The Cliffhanger** - Unresolved tension, question left hanging 57. **Where Are They Now** - Text/montage showing characters' futures 58. **The Twist Ending** - Final revelation reframes entire story 59. **Full Circle Reunion** - Characters gather one last time 60. **The Long Walk Away** - Character leaves location, camera lingers 61. **Passing the Torch** - Legacy/knowledge transferred to next generation 62. **The Final Confrontation** - Last face-to-face with antagonist 63. **Quiet Moment After Storm** - Calm after climax, processing events 64. **The Sacrifice Payoff** - Earlier sacrifice proven worthwhile 65. **Open Road/New Beginning** - Character sets off on next journey --- **Using These in Configs:** - Each scenario = potential game state template - Combine scenarios for complex scenes (Dinner Party + The Setup) - Consider which shot types fit each (Interrogation = close-ups, Chase = tracking) - Match lighting to mood (Funeral = low key, Gala = high key) """) with gr.Accordion("Scenario Sequence Generator", open=True): gr.Markdown("### Generate Story Sequences from Film Scenarios") gr.Markdown("Create 3-10 scene sequences for your game config. Output as list, JSON config, or send prompts to generation queue.") with gr.Row(): seq_count = gr.Slider(minimum=3, maximum=10, value=5, step=1, label="Number of Scenes") with gr.Row(): seq_opening = gr.Checkbox(label="Openings", value=True) seq_tension = gr.Checkbox(label="Tension", value=True) seq_action = gr.Checkbox(label="Action", value=True) seq_emotional = gr.Checkbox(label="Emotional", value=True) with gr.Row(): seq_discovery = gr.Checkbox(label="Discovery", value=True) seq_social = gr.Checkbox(label="Social", value=True) seq_ending = gr.Checkbox(label="Endings", value=True) with gr.Row(): seq_force_opening = gr.Checkbox(label="Force Opening First", value=True) seq_force_ending = gr.Checkbox(label="Force Ending Last", value=True) with gr.Row(): seq_media_type = gr.Dropdown( choices=["image", "audio", "3d", "tts"], value="image", label="Media Type", scale=1 ) seq_auto_queue = gr.Checkbox(label="Auto-add to Queue", value=False, scale=1) seq_generate_btn = gr.Button("Generate Sequence", variant="primary", scale=2) with gr.Row(): with gr.Column(): seq_list_output = gr.Markdown(label="Sequence List") with gr.Column(): seq_json_output = gr.Code(label="Config JSON", language="json", lines=15) with gr.Row(): seq_prompts_output = gr.Textbox(label="Media Prompts (for queue)", lines=8, interactive=False) with gr.Row(): seq_add_to_queue_btn = gr.Button("Add Prompts to Queue", variant="secondary", scale=2) seq_queue_status = gr.Textbox(label="Status", interactive=False, scale=2) seq_queue_count = gr.Textbox(label="Queue", value="0 items", interactive=False, scale=1) def generate_with_optional_queue(count, inc_open, inc_tens, inc_act, inc_emo, inc_disc, inc_soc, inc_end, force_open, force_end, media_type, auto_queue): """Generate sequence and optionally add to queue.""" list_out, json_out, prompts_out = generate_scenario_sequence( count, inc_open, inc_tens, inc_act, inc_emo, inc_disc, inc_soc, inc_end, force_open, force_end ) if auto_queue and prompts_out: _, queue_info, status = add_scenario_prompts_to_queue(prompts_out, media_type) return list_out, json_out, prompts_out, status, queue_info else: return list_out, json_out, prompts_out, "", f"{len(generation_queue)} items" seq_generate_btn.click( generate_with_optional_queue, inputs=[seq_count, seq_opening, seq_tension, seq_action, seq_emotional, seq_discovery, seq_social, seq_ending, seq_force_opening, seq_force_ending, seq_media_type, seq_auto_queue], outputs=[seq_list_output, seq_json_output, seq_prompts_output, seq_queue_status, seq_queue_count] ) def add_prompts_with_type(prompts_text, media_type): """Add prompts to queue with specified media type.""" _, queue_info, status = add_scenario_prompts_to_queue(prompts_text, media_type) return status, queue_info seq_add_to_queue_btn.click( add_prompts_with_type, inputs=[seq_prompts_output, seq_media_type], outputs=[seq_queue_status, seq_queue_count] ) with gr.Tab("Portability & Design"): with gr.Tab("Platform Export"): gr.Markdown("### Export to Game Engines") gr.Markdown("Select a platform, paste your game config JSON, then click Export.") # Platform test info - shows where to test selected platform PLATFORM_TEST_INFO = { "playcanvas": ("PlayCanvas Editor", "https://playcanvas.com/", "Paste JavaScript into a new script component"), "godot": ("GDScript Online", "https://gdscript-online.github.io/", "Test GDScript snippets online, or use Godot Editor"), "unreal": ("Unreal Engine", "https://www.unrealengine.com/", "Requires Unreal Engine 5.x with Python scripting enabled"), "gamemaker": ("GameMaker", "https://gamemaker.io/", "Create new project, add script resource"), "flutter": ("DartPad", "https://dartpad.dev/", "Paste Dart code to test UI logic"), "twine": ("Twinery.org", "https://twinery.org/", "Import HTML or paste into new story"), "renpy": ("Ren'Py", "https://www.renpy.org/", "Download SDK, replace script.rpy"), "ink": ("Inky Editor", "https://www.inklestudios.com/ink/", "Download Inky or use web playground"), "yarn": ("Try Yarn Spinner", "https://try.yarnspinner.dev/", "Paste .yarn code and click Run"), "roblox": ("Roblox Studio", "https://www.roblox.com/create", "Create ModuleScript in ReplicatedStorage"), "rpgmaker": ("RPG Maker MZ", "https://www.rpgmakerweb.com/", "Save as js/plugins/StoryAdventure.js"), "minecraft": ("Minecraft Java", "https://www.minecraft.net/", "Create datapack in world/datapacks folder"), "papyrus": ("Creation Kit", "https://www.creationkit.com/", "Compile .psc with Papyrus compiler"), "vrchat": ("VRChat SDK", "https://hello.vrchat.com/", "Unity 2019.4 + VRChat SDK3 + UdonSharp"), "lensstudio": ("Lens Studio", "https://lensstudio.snapchat.com/", "Free download, create new lens project"), "metaspark": ("Meta Spark Studio", "https://spark.meta.com/", "Free download, create AR effect"), "8thwall": ("8th Wall", "https://www.8thwall.com/", "WebAR - works in mobile browser"), "tiktok": ("Effect House", "https://effecthouse.tiktok.com/", "Free download, create TikTok effect"), "reality": ("Xcode", "https://developer.apple.com/xcode/", "Requires Xcode 15+ for visionOS/iOS"), "inform7": ("Inform 7 / Borogove", "https://borogove.app/", "Online IDE or download Inform 7"), "godot_dialogue": ("Godot + Dialogue Manager", "https://github.com/nathanhoad/godot_dialogue_manager", "Install addon from AssetLib"), "movingdotspace": ("Browser", "", "Self-contained HTML - open in any browser, use arrow keys"), "terminal": ("Python", "https://replit.com/", "Run with 'python game.py' - works on Replit, Pydroid, any Python env"), "existing game": ("Various", "", "JSON format for manual conversion to your target"), } def get_platform_info(platform): """Get test info for selected platform.""" if not platform or platform == "": return "" info = PLATFORM_TEST_INFO.get(platform, ("Unknown", "", "")) name, url, tip = info if url: return f"**Test at:** [{name}]({url}) \n**Tip:** {tip}" elif name: return f"**Test at:** {name} \n**Tip:** {tip}" return "" platform_info_display = gr.Markdown( value=get_platform_info("playcanvas"), elem_classes=["platform-info-box"] ) # Platform dropdown with all options grouped platform_choices = [ ("── Game Engines ──", ""), ("PlayCanvas", "playcanvas"), ("Godot 4.x", "godot"), ("Unreal 5.x", "unreal"), ("GameMaker", "gamemaker"), ("Flutter", "flutter"), ("── Narrative Engines ──", ""), ("Twine", "twine"), ("Ren'Py", "renpy"), ("Ink", "ink"), ("Yarn Spinner", "yarn"), ("── Game Platforms ──", ""), ("Roblox", "roblox"), ("RPG Maker MZ", "rpgmaker"), ("Minecraft", "minecraft"), ("Skyrim/Fallout (Papyrus)", "papyrus"), ("VRChat", "vrchat"), ("── AR/XR Platforms ──", ""), ("Lens Studio", "lensstudio"), ("Meta Spark", "metaspark"), ("8th Wall", "8thwall"), ("TikTok Effect House", "tiktok"), ("Apple Reality", "reality"), ("── Interactive Fiction ──", ""), ("Inform 7", "inform7"), ("Godot Dialogue Manager", "godot_dialogue"), ("── Playable HTML ──", ""), ("MovingDotSpace", "movingdotspace"), ("── Terminal ──", ""), ("Python Terminal Game", "terminal"), ("Existing Game (JSON)", "existing game"), ] with gr.Row(): platform_selector = gr.Dropdown( choices=platform_choices, value="playcanvas", label="Target Platform", scale=2 ) export_btn = gr.Button("Export", variant="primary", scale=1) export_zip_btn = gr.Button("Download ZIP", variant="secondary", scale=1) with gr.Row(): config_input_export = gr.Textbox(label="Paste Game Config JSON", lines=6, placeholder='{"village": {"start": {"description": "...", "choices": [...]}}}', scale=4) load_sandwich_btn = gr.Button("šŸ“„ Load Sandwich Quest Demo", scale=1) # Load sandwich quest demo def load_sandwich_demo(): try: import os demo_path = os.path.join(os.path.dirname(__file__), "sandwich_quest_demo.json") with open(demo_path, 'r', encoding='utf-8') as f: return f.read() except Exception as e: return f'{{"error": "Could not load demo: {str(e)}"}}' load_sandwich_btn.click(fn=load_sandwich_demo, outputs=[config_input_export]) # Update platform info when selection changes platform_selector.change( fn=get_platform_info, inputs=[platform_selector], outputs=[platform_info_display] ) with gr.Row(): export_explanation = gr.Textbox(label="Instructions", lines=8, interactive=False) export_code = gr.Code(label="Generated Code", language="javascript") # ZIP download components with gr.Row(): export_zip_file = gr.File(label="Download ZIP", interactive=False) export_zip_status = gr.Textbox(label="ZIP Status", interactive=False, lines=2) export_btn.click( fn=ConfigConversionforExporttoPlatform, inputs=[platform_selector, config_input_export], outputs=[export_explanation, export_code] ) # ZIP export function def export_platform_as_zip(platform, config_json): """Export platform code as a ZIP file.""" if not config_json or not config_json.strip(): return None, "No config provided" try: import tempfile import zipfile from datetime import datetime # Get the export output explanation, code = ConfigConversionforExporttoPlatform(platform, config_json) if not code: return None, "Export failed - no code generated" timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") zip_filename = f"{platform}_export_{timestamp}.zip" zip_path = os.path.join(tempfile.gettempdir(), zip_filename) with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: # Add setup instructions zipf.writestr("README_SETUP.txt", explanation) # Add code file(s) based on platform if platform == "godot": # Godot outputs multiple files separated by markers # Parse the combined output into separate files files = parse_godot_output(code) for filename, content in files.items(): zipf.writestr(filename, content) elif platform == "playcanvas": zipf.writestr("game.js", code) elif platform == "unreal": zipf.writestr("game_controller.py", code) elif platform == "gamemaker": zipf.writestr("game_controller.gml", code) elif platform == "flutter": zipf.writestr("main.dart", code) elif platform == "twine": zipf.writestr("story.html", code) elif platform == "renpy": zipf.writestr("script.rpy", code) elif platform == "ink": zipf.writestr("story.ink", code) elif platform == "yarn": zipf.writestr("dialogue.yarn", code) elif platform == "roblox": zipf.writestr("StoryModule.lua", code) elif platform == "rpgmaker": zipf.writestr("js/plugins/StoryAdventure.js", code) elif platform == "lensstudio": zipf.writestr("StoryExperience.js", code) elif platform == "metaspark": zipf.writestr("StoryEffect.js", code) elif platform == "8thwall": zipf.writestr("index.html", code) elif platform == "minecraft": zipf.writestr("datapack_instructions.txt", code) elif platform == "papyrus": zipf.writestr("StoryAdventure.psc", code) elif platform == "vrchat": zipf.writestr("StoryAdventure.cs", code) elif platform == "tiktok": zipf.writestr("StoryEffect.js", code) elif platform == "reality": zipf.writestr("StoryView.swift", code) elif platform == "inform7": zipf.writestr("story.ni", code) elif platform == "godot_dialogue": zipf.writestr("story.dialogue", code) elif platform == "movingdotspace" or platform == "2d map related space": zipf.writestr("game.html", code) elif platform == "terminal": zipf.writestr("game.py", code) else: zipf.writestr("export.txt", code) # Add the original config zipf.writestr("config.json", config_json) return zip_path, f"Exported: {zip_filename}" except Exception as e: return None, f"ZIP error: {str(e)}" def parse_godot_output(combined_code): """Parse Godot's combined output into separate files.""" files = {} current_file = None current_content = [] for line in combined_code.split('\n'): # Check for file markers like "# === game_state.gd ===" or "### FILE: game_state.gd ###" if line.startswith('# ===') and '===' in line[5:]: if current_file and current_content: files[current_file] = '\n'.join(current_content) # Extract filename filename = line.replace('# ===', '').replace('===', '').strip() current_file = filename current_content = [] elif line.startswith('### FILE:') and '###' in line[9:]: if current_file and current_content: files[current_file] = '\n'.join(current_content) filename = line.replace('### FILE:', '').replace('###', '').strip() current_file = filename current_content = [] else: current_content.append(line) # Don't forget the last file if current_file and current_content: files[current_file] = '\n'.join(current_content) # If no files were parsed, return as single file if not files: files["export.gd"] = combined_code return files export_zip_btn.click( fn=export_platform_as_zip, inputs=[platform_selector, config_input_export], outputs=[export_zip_file, export_zip_status] ) gr.Markdown(""" | Engine | Status | Output | Test Online | |--------|--------|--------|-------------| | **Game Engines** |||| | PlayCanvas | Ready | JavaScript | [PlayCanvas Editor](https://playcanvas.com/) | | Godot 4.x | Ready | .tscn + GDScript (ZIP) | [GDScript Online](https://gdscript-online.github.io/) | | Unreal 5.x | Ready | Python script | Desktop only | | GameMaker | Ready | GML script | [GameMaker](https://gamemaker.io/) | | Flutter | Ready | Dart code | [DartPad](https://dartpad.dev/) | | **Narrative Engines** |||| | Twine | Ready | HTML story | [Twinery.org](https://twinery.org/) | | Ren'Py | Ready | .rpy script | [Ren'Py](https://www.renpy.org/) | | Ink | Ready | .ink story | [Inky Editor](https://www.inklestudios.com/ink/) | | Yarn Spinner | Ready | .yarn dialogue | [Try Yarn](https://try.yarnspinner.dev/) | | **Game Platforms** |||| | Roblox | Ready | Lua ModuleScript | [Roblox Studio](https://www.roblox.com/create) | | RPG Maker MZ | Ready | .js plugin | [RPG Maker](https://www.rpgmakerweb.com/) | | Minecraft | Ready | Datapack (mcfunction) | In-game testing | | Skyrim/Fallout | Ready | Papyrus .psc | [Creation Kit](https://www.creationkit.com/) | | VRChat | Ready | UdonSharp .cs | [VRChat SDK](https://hello.vrchat.com/) | | **AR/XR Platforms** |||| | Lens Studio | Ready | JavaScript | [Lens Studio](https://lensstudio.snapchat.com/) | | Meta Spark | Ready | JavaScript | [Meta Spark](https://spark.meta.com/) | | 8th Wall | Ready | HTML + A-Frame | [8th Wall](https://www.8thwall.com/) | | TikTok Effect House | Ready | JavaScript | [Effect House](https://effecthouse.tiktok.com/) | | Apple Reality | Ready | Swift/RealityKit | [Xcode](https://developer.apple.com/xcode/) | | **Interactive Fiction** |||| | Inform 7 | Ready | Natural language | [Inform 7](http://inform7.com/) | | Godot Dialogue | Ready | .dialogue file | [Dialogue Manager](https://github.com/nathanhoad/godot_dialogue_manager) | | **Playable HTML** |||| | MovingDotSpace | Ready | Self-contained HTML | Browser (arrow keys + modals) | | **Terminal** |||| | Python Terminal | Ready | Python script | [Replit](https://replit.com/) / Pydroid / Any Python | """) create_mechanic_translation_tab() with gr.Tab("Theory & Expansion Ideas"): # with gr.Row(): # with gr.Column(): with gr.Accordion("'1d' vs 2d vs 3d", open=False): gr.Markdown("""**Test your config in different dimensions:** - **1D (Text):** Test tab → Playtest & Edit - **2D (Top-down):** Test tab → Game Preview (2D) (MovingDotSpace) - **3D (WebGL):** Test tab → Game Preview (3D) (PlayCanvas) --- # Suggestions from Llama 405b through Lambdachat To create 2D and 3D versions of your 1D text-based game, you'll need to expand your game engine to support additional features. Here's a high-level overview of the steps you can follow: 1. For 2D (top-down traversal): a. Create a grid-based system: Instead of just having a linear sequence of decisions, create a 2D grid that represents the game world. Each cell in the grid can represent a location in the game world, and the player can move between adjacent cells. b. Implement movement: Allow the player to move in four directions (up, down, left, right) by updating their position on the grid. You can use input commands like "go north", "go south", "go east", and "go west". c. Add obstacles and interactive objects: Place obstacles (e.g., walls, locked doors) and interactive objects (e.g., keys, items) on the grid. The player will need to navigate around obstacles and interact with objects to progress in the game. d. Update game logic: Modify your game's logic to account for the player's position on the grid and any interactions with objects or NPCs. 2. For 3D: a. Add a third dimension: Expand your 2D grid to a 3D grid by adding a new dimension (e.g., height). This will allow you to create multi-level environments with stairs, elevators, or other vertical traversal methods. b. Implement movement in 3D: Extend your movement system to allow the player to move up and down in addition to the four cardinal directions. You can use input commands like "go up" and "go down". c. Update game logic for 3D: Modify your game's logic to account for the player's position in 3D space, as well as any interactions with objects or NPCs that may occur at different heights. d. Add 3D-specific features: Consider adding features that take advantage of the 3D environment, such as jumping, falling, or flying. In both cases, you'll need to update your game's user interface to accommodate the additional dimensions. This may involve displaying a top-down view of the game world, rendering a 3D environment, or providing additional text descriptions to convey the player's surroundings. Keep in mind that creating 2D and 3D games will require more complex programming and design compared to a 1D text-based game. You may need to learn new programming concepts and tools to achieve your goals. # More ideas for expansion of '1d' ideas Expanding a 1D text-based game into 2D and 3D versions can introduce various new gameplay elements and features. Here are 10 additional points for each expansion, assuming we can debug and code any idea we want: 2D Expansion: 1. Add a mini-map: Implement a mini-map feature that displays the player's current position and the surrounding area, making navigation more intuitive. 2. Introduce NPCs with movement: Create non-player characters (NPCs) that can move around the grid, adding life to the game world and offering new interaction opportunities. 3. Develop a dialogue system: Design a dialogue system that allows players to engage in conversations with NPCs, further enriching the game's narrative. 4. Implement a day-night cycle: Add a day-night cycle that affects gameplay, such as certain events or NPCs only being available during specific times. 5. Design puzzles: Create grid-based puzzles that players must solve to progress in the game, such as pushing blocks to activate switches or navigating mazes. 6. Add character customization: Allow players to customize their character's appearance and attributes, giving them a sense of ownership over their avatar. 7. Introduce a crafting system: Implement a crafting system that enables players to combine items found in the game world to create new, more powerful items. 8. Add weather effects: Introduce weather effects like rain, snow, or fog that can impact gameplay, such as reducing visibility or making certain areas inaccessible. 9. Create a quest system: Design a quest system with various objectives for players to complete, providing a sense of progression and purpose. 10. Develop a party system: Allow players to recruit NPCs to join their party, assisting them in combat and providing unique abilities. 3D Expansion: 1. Add camera controls: Implement camera controls that allow players to rotate and zoom their view of the 3D game world, providing greater flexibility in exploration. 2. Introduce platforming elements: Add platforming elements like jumping, climbing, and ledge-grabbing to enhance traversal in the 3D environment. 3. Develop a physics system: Create a physics system that governs object interactions, enabling realistic behaviors like collisions, gravity, and buoyancy. 4. Implement destructible environments: Design destructible environments that react to player actions, such as breaking walls or collapsing structures. 5. Add aerial gameplay: Introduce flying mounts or vehicles that allow players to explore the game world from the air, opening up new traversal possibilities. 6. Create underwater sections: Design underwater areas with unique gameplay mechanics, such as swimming, diving, and underwater combat. 7. Introduce mounted combat: Allow players to engage in combat while riding mounts, adding a new strategic layer to battles. 8. Develop a dynamic weather system: Create a dynamic weather system that affects gameplay in real-time, such as strong winds impacting movement or lightning strikes causing damage. 9. Implement a stealth system: Design a stealth system that enables players to avoid detection by enemies, using cover, distractions, and silent takedowns. 10. Add virtual reality support: Implement virtual reality support, allowing players to fully immerse themselves in the 3D game world using VR headsets and motion controls. Remember that these ideas can be mixed and matched to create unique gameplay experiences tailored to your vision for the game. # More ideas for '1d' game idea 1D text-based games have their own unique strengths and limitations. Here are some ideas that can be best explored or are exclusive to 1D text-based games: 1. Focus on narrative: 1D text-based games can focus primarily on storytelling, allowing for rich, branching narratives without the need for complex graphics or animations. 2. Emphasize imagination: With no visual elements, 1D text-based games rely on the player's imagination to visualize the game world, making the experience more personal and engaging. 3. Develop complex dialogue trees: In a 1D text-based game, you can create intricate dialogue trees with multiple choices and consequences, allowing for deep character interactions. 4. Create puzzles based on text manipulation: Design puzzles that involve manipulating or deciphering text, such as riddles, word scrambles, or cipher-based challenges. 5. Implement a text-based inventory system: Create an inventory system that relies on text descriptions of items, allowing players to use their imagination to determine how to use or combine objects. 6. Explore experimental storytelling techniques: 1D text-based games can experiment with unconventional narrative structures, such as non-linear storytelling, interactive fiction, or second-person narration. 7. Focus on resource management: Implement resource management mechanics that rely on text descriptions, such as managing a character's hunger, thirst, or fatigue levels. 8. Develop a text-based skill tree: Create a skill tree system that uses text descriptions to convey character progression and abilities, allowing players to make meaningful choices about their character's development. 9. Create a text-based AI companion: Design an AI companion that communicates with the player through text, offering guidance, hints, or engaging in conversations. 10. Emphasize accessibility: 1D text-based games can be more accessible to players with visual impairments, as they can be played using screen readers or other assistive technologies. While some of these ideas can be adapted to 2D and 3D games, they are particularly well-suited for 1D text-based games, where the focus is on narrative, imagination, and text-driven gameplay. """) # with gr.Column(): gr.HTML("Main idea for this tab is ways to reuse the config in same/different way in other platforms - Need a conversion management interface") gr.HTML("Side Quests can be to build with a real world 3D printer - eg. Map or speculating how uncharted territories are") with gr.Accordion("Basic planning for conversions", open=False): gr.Markdown("**Use the Platform Export tool in the 'Platform Export' tab above for actual conversion.**") gr.HTML("MikeTheTech Tutorials (He has many more playlists so check the rest of his channel) -
playcanvas https://www.youtube.com/playlist?list=PLJKGfra8Jl0B845PNo9cMxAQfghJrYH1Y,
unreal engine - https://www.youtube.com/watch?v=STHdIdWO0tk&list=PLJKGfra8Jl0CSjCzk1r0peTp0orIleqdG,
gamemaker - https://www.youtube.com/watch?v=ka_fVrGMOwo&list=PLJKGfra8Jl0AW3rNuwcmi_aq_PdsjQtbu ") gr.HTML("Reskinng and extending the Tutorials / smallest examples = fastest way to gain intuition for whats important") gr.HTML("For 3D with regard to this space - see '3D Study and Tutorials' → '3D Background with UI' tab") with gr.Tab("Twine - Open-source"): gr.Markdown("### Twine Export") gr.HTML("twinery.org - Story based games | Twee File = easy import | Local Install = Actual Save Files instead of local storage in browser") with gr.Row(): twine_config_input = gr.Textbox( label="Game Config JSON", lines=8, placeholder='{"village": {"start": {"description": "You arrive at the village.", "choices": ["Enter tavern", "Talk to guard"], "transitions": {"Enter tavern": "tavern", "Talk to guard": "guard"}}}}', scale=3 ) with gr.Column(scale=1): twine_load_demo_btn = gr.Button("šŸ“„ Load Demo Config", variant="secondary") twine_export_btn = gr.Button("šŸŽ® Export to Twine", variant="primary") twine_output = gr.Code(label="Twine/Twee Output", language="html", lines=12) twine_status = gr.Markdown("") def load_twine_demo(): try: import os demo_path = os.path.join(os.path.dirname(__file__), "sandwich_quest_demo.json") with open(demo_path, 'r', encoding='utf-8') as f: return f.read() except Exception as e: return f'{{"error": "Could not load demo: {str(e)}"}}' def export_to_twine_ui(config_json): if not config_json or not config_json.strip(): return "", "āš ļø Please provide a game config JSON" try: from exporters import export_to_twine explanation, code = export_to_twine(config_json) if code: return code, f"āœ… Twine export generated!\n\n{explanation}" else: return "", f"āŒ Export failed: {explanation}" except Exception as e: return "", f"āŒ Error: {str(e)}" twine_load_demo_btn.click(fn=load_twine_demo, outputs=[twine_config_input]) twine_export_btn.click( fn=export_to_twine_ui, inputs=[twine_config_input], outputs=[twine_output, twine_status] ) with gr.Accordion("Example Twine/Twee File Structure", open=False): gr.Code(ExampleTwineFileStructureasInitialPrompt, language="html") with gr.Tab("3D Engine Resources"): gr.Markdown("""### 3D Game Engine Export Resources Use the **Platform Export** tab to generate code, then use these resources to build your 3D game. """) with gr.Accordion("PlayCanvas", open=True): gr.Markdown("""**Select 'playcanvas' in Platform Export to generate JavaScript code.** Generated code includes: GameState, ConditionEvaluator, EffectApplicator, TransitionResolver, scene entities, and click handling. **Live Preview:** Use the **Game Preview (3D)** tab for interactive 3D preview. """) with gr.Accordion("UI in PlayCanvas", open=False): gr.HTML("Basic - Add 2 Entities to the root of the hierachy (Left top - displays items in the scene) -
one will load the story script and the will hold the UI items and load the UI script (Both Below)
UI entitiy needs to have a screen and script items added under its properties (left hand side)
UI Entity also needs three items added to it. text (need a font as well to load), a container for buttons, and the button that gets turned into a template (hierachy menu options)") with gr.Column(): gr.Code(playcanvasstorymanager) gr.Code(playcanvasuimanager) with gr.Accordion("Tutorials & Resources", open=False): gr.HTML("Playcanvas Tutorials - https://developer.playcanvas.com/tutorials/webxr-hello-world/, Wow - https://developer.playcanvas.com/user-manual/assets/types/wasm/
https://github.com/playcanvas/playcanvas.github.io - https://playcanvas.vercel.app/#/misc/hello-world ") gr.HTML(""" https://playcanvas.vercel.app/#/physics/vehicle https://forum.playcanvas.com/t/assets-free-3d-models-sprites-icons-and-sounds-for-your-games/19199 https://github.com/playcanvas/playcanvas.github.io/tree/main https://github.com/playcanvas/engine https://github.com/playcanvas/engine/blob/main/examples/src/examples/physics/vehicle.example.mjs https://github.com/playcanvas/engine/blob/main/examples/src/examples/misc/editor.example.mjs https://github.com/playcanvas/engine/blob/main/examples/src/examples/input/keyboard.example.mjs https://github.com/playcanvas/engine/blob/main/examples/src/examples/input/mouse.example.mjs https://github.com/playcanvas/engine/blob/main/examples/src/examples/camera/first-person.example.mjs """) gr.HTML("https://youtu.be/a3pJiZ86XgA (Learn.Nimagin) - Youtube video showing user interface in playcanvas") with gr.Accordion("Notes", open=False): gr.HTML("How can add 100 shapes in playcanvas very quickly? - Seems one at a time during editor phase") gr.HTML("Each location is new scene?") gr.HTML("Repurpose the ball demo - ball replaced with a custom 3D object
platform can used as map floor by changing dimensions, islands unlock = hidden platforms unhidden by a trigger (verticality as location access control)
Teleport can be loader for UI ") with gr.Accordion("Godot 4.x", open=False): gr.Markdown("""**Select 'godot' in Platform Export to generate GDScript + Scene files.** Generated files: - `main.tscn` - Scene with all locations and choices - `game_state.gd` - AutoLoad singleton (add in Project Settings) - `game_controller.gd` - Navigation and state management - `condition_evaluator.gd`, `effect_applicator.gd`, `transition_resolver.gd` - `choice.gd` - Script for clickable choice boxes **Setup:** Add `game_state.gd` as AutoLoad named "GameState" in Project Settings. """) with gr.Accordion("Tutorials & Resources", open=False): gr.HTML("Godot Docs - https://docs.godotengine.org/en/stable/") gr.HTML("GDQuest - https://www.gdquest.com/") gr.HTML("https://github.com/godotengine/godot-demo-projects") with gr.Accordion("Unreal Engine 5", open=False): gr.Markdown("""**Select 'unreal' in Platform Export to generate a Python script.** **Requirements:** Enable "Python Editor Script Plugin" in Edit -> Plugins **Usage:** 1. Open Python Console: Window -> Developer Tools -> Output Log 2. Paste the generated script 3. Run `start_game()` to create the scene 4. Use `list_choices()` and `select_choice('id')` to play Note: This is for prototyping in-editor. For a shipped game, convert to Blueprints. """) with gr.Accordion("Tutorials & Resources", open=False): gr.HTML("Learning Centre - https://dev.epicgames.com/community/unreal-engine/learning") gr.HTML("Python in Unreal - https://docs.unrealengine.com/5.0/en-US/scripting-the-unreal-editor-using-python/") with gr.Accordion("Existing Games as Engines", open=False): gr.HTML("Unreal Engine for Fortnite https://dev.epicgames.com/community/fortnite/getting-started/uefn") gr.HTML("https://www.reddit.com/r/singularity/comments/1fd4oo1/roblox_announces_ai_tool_for_generating_3d_game/ - roblox and genai") gr.HTML("Modding Tools? eg. Skyrim, GTA, sims 4 custom scenarios") gr.HTML("GTA (Rockstar Editor) - UI or mission next objective system") gr.HTML("SIMS - Buildings as Paths - Like a maze path is your decisions") gr.HTML("Racing Game - Next turn = choice") gr.HTML("Other games as Iframes and MLM as the judge (visual confirmation) aka the quest completion algorithm") with gr.Tab("AR/XR Integration (Future)"): gr.Markdown("""## AR/XR Integration Notes **Full AR/XR documentation has been moved to a dedicated section.** For comprehensive AR/XR resources including: - Platform comparison tables (Lens Studio, Meta Spark, Effect House, Adobe Aero, 8th Wall) - File types, export formats, and testing devices - Detailed workflows for each platform - Integration ideas for game configs - WebXR and browser-based AR - Publishing and distribution guides - Animation resources (Mixamo alternatives) **See: 3D Study and Tutorials → AR/XR Development tab** This keeps AR/XR content consolidated with other 3D resources for easier reference. """) gr.Markdown("---") gr.Markdown("*Navigate to '3D Study and Tutorials' → 'AR/XR Development' for full documentation.*") # NOTE: "Leveraging Machine Learning" tab has been merged into "Media Studio" (ui_gr_media_management.py) # All content preserved in: Media Studio → Generate → Local (ZeroGPU), API, Resources # NOTE: Resources Hub tab moved inside Mini-Tutorial & Resources accordion (testgroupingUIremotely) # 3D Study tab (extracted to ui_tabs/study_3d_tab.py) create_3d_study_tab() # Story Graph and Big RPG Scale moved to Config Development Assistance tab demo.queue().launch(share=True)