Building LLM Text Games: From Prompts to a State Engine

    This article breaks down how an LLM-driven text adventure works as an interactive state machine, and why keeping narrative, state, and rules in separate layers is the key to long, stable play. It covers a minimal state schema, a contract-style prompt that makes the model propose state patches instead of rewriting data, a deterministic turn loop, a checklist for preventing common long-run failures, and measurable metrics for evaluating playability. The same structure can be adapted to interactive teaching, process drills, and scenario-based training.

    1. The Technical Core: Turning “Storytelling” into a Loop

    Around the New Year, the LLM community picked up a retro-style trend: with no code at all, users run text adventures in a chat window using nothing but natural-language commands. Cultivation epics, palace intrigue, post-apocalyptic survival—the genre switches on command. It looks like idle chatting, but break it apart and it is essentially an interactive state machine driven by a language model.

    Traditional text games (traceable to early MUDs and later interactive fiction engines) usually consist of three parts: story text, state data, and rule evaluation. What LLMs change is this: story text can be generated on the fly, rule evaluation can be “soft-enforced” by the model, and state data must be held firmly by us. In other words, the model handles “narration and association,” while the engineering side handles “constraints and truth.”

    The easiest trap here is handing every responsibility to the model. Once the model is made to handle narration, numbers, evaluation, and saving all at once, a few turns in you get the classic breakdown: stats inflate out of nowhere, items vanish, character memory scrambles, and the difficulty curve spins out of control. The key to stable, playable output is separating trusted state from the generation process.

    2. First Principles: Three Kinds of Information Must Be Separated

    The architecture should split cleanly into three layers:

    1. Narrative layer: The model generates scene descriptions, dialogue, and options; divergence is allowed.
    2. State layer: Structured data and the single source of truth, read and written by the program; the model only “references” it, never “rewrites” it.
    3. Rules layer: Turn progression, resource consumption, evaluation thresholds, and failure conditions, implemented with deterministic code wherever possible.

    A minimal usable state structure could be:

    1. {
    2. "turn": 0,
    3. "scene": "Outer Sect Trial Grounds",
    4. "stats": { "cultivation": 12, "spirit": 30, "hp": 100 },
    5. "inventory": ["Wooden Sword", "Healing Pill x2"],
    6. "flags": { "met_master": false, "has_lost_once": false },
    7. "win_condition": "Place in the top ten of the Sect Grand Tournament",
    8. "lose_condition": "hp<=0 or cultivation fails to grow for three consecutive turns"
    9. }

    The payoff is direct: the model can be swapped, downgraded, or time out, and game progress is not lost; at the same time, numeric balance is guaranteed by code, so you never get the imbalance of “one sentence adds ten thousand cultivation points.”

    3. The Prompt Protocol: Constraining Generation with a Contract

    To get the model to reliably output parseable results, write the prompt as an explicit interface contract rather than a prose-style persona. The core elements are: role, input, output format, prohibitions, and a strategy for handling “out-of-bounds input.”

    An illustrative prompt (usable directly as a system instruction):

    1. You are the engine of a text adventure game. Each turn you must:
    2. 1) Describe the current scene in no more than 120 words;
    3. 2) Give 3 mutually exclusive options, labeled A/B/C;
    4. 3) At the end, output a JSON block with the keys narrative_delta, state_patch, choices.
    5. Constraints:
    6. - Do not directly modify stats or inventory; you may only propose a state_patch;
    7. - If the player's input goes beyond the worldview, provide a "reasonable in-world explanation" and must not reject the player;
    8. - Keep difficulty progressive; forbidden to cross more than two major realms in a single turn.

    The key design here is letting the model only “propose” state changes (state_patch), with the program deciding whether to accept them. For example, if the model suggests { "cultivation": +5 }, the program decides whether to commit it based on the current turn, resource consumption, and thresholds, capping it when necessary. This preserves the freedom of generation while holding the numeric bottom line.

    4. The Turn Loop: Writing the Gameplay as Pseudocode

    With state and protocol in place, the main loop becomes clear:

    1. state = load_or_init()
    2. while not is_over(state):
    3. prompt = build_prompt(state, history_window=8)
    4. reply = llm.generate(prompt) # narrative + choices + state_patch
    5. narrative, patch, choices = parse(reply)
    6. action = get_player_input(choices) # free input allowed, not limited to options
    7. outcome = apply_rules(state, action) # deterministic: consumption, checks, failure
    8. state = merge_patch(state, patch, cap=True)
    9. state = clamp(state) # numeric bounds, item deduplication
    10. history.append((narrative, action, outcome))
    11. autosave(state)

    Three engineering details are worth emphasizing:

    • History window: Do not stuff all history back into the context; organize it as “the most recent N turns plus a summary of key events,” which saves compute and lowers the chance of drifting off track.
    • Free input: Allowing players to ignore the options is the root of why this genre is so addictive; but free input must be normalized through the rules layer—for example, mapping “I want to set up a stall and sell grilled skewers” to a low-risk, low-reward resource conversion event.
    • Failure evaluation: There must be a way to lose. Victory without failure quickly loses tension; writing failure conditions into the state and letting code judge them is more controllable than having the model “decide you lost.”

    5. An Anti-Breakdown Checklist: Keeping Long-Range Consistency Maintainable

    The four most common forms of degradation in long conversations, and the corresponding practices:

    1. Numeric inflation: Route all increments and decrements through a single entry point, with a per-turn change cap and a total cap.
    2. Memory drift: Maintain a “key facts table” (character relationships, acquired artifacts, sworn oaths) and inject only the relevant entries each turn.
    3. Setting conflicts: Write the worldview as inviolable hard-constraint entries; when conflicts arise, hard constraints take priority.
    4. Pacing loss of control: Advance with an “act” structure (three to five turns per act), and run a state check and difficulty calibration at the end of each act.

    If you want to turn the prototype into a service playable by multiple people, common general-purpose cloud capabilities can be combined as needed: use a container platform to host the stateless inference gateway, use object storage to save snapshot saves, use a message queue to smooth peaks and serialize concurrent writes to the same save, and use logging services and monitoring alerts to track timeout rates and parse failure rates. These are general-category capabilities, and the specific choices should be based on your own scale and compliance requirements.

    6. Evaluation: Quantifying Whether It Is “Fun”

    Playability seems subjective, but it can still be broken into measurable metrics:

    • Format compliance rate: Whether the output can be reliably parsed into the agreed structure;
    • State consistency rate: Whether the program state conflicts with the narrative description (e.g., the text says “spiritual power depleted” but the value is full);
    • Failure reachability: Whether a failure branch can be triggered within N turns;
    • Branch entropy: The degree of story divergence caused by options and custom player input;
    • Per-turn latency and cost: Directly affects the smoothness of the experience.

    It is advisable to build a small regression set: fix 10 opening seeds, run 20 turns each, and record the metrics above. After changing the prompt or switching models, rerun and use the data to judge whether it is “more fun” or “more off track.”

    7. Conclusion: Give Imagination to the Model, Order to Engineering

    What is truly worth borrowing from this kind of AI text game is not a particular genre but a division-of-labor paradigm: generation handles possibility, engineering handles certainty. When narrative, state, and rules are clearly layered and connected by contract-style prompts and deterministic evaluation, you get an interactive system that is both wildly imaginative and never out of control. With slight substitutions, the same skeleton can migrate to interactive teaching, process drills, and scenario-based training—turning the driving force of “addictiveness” into measurable product capability.