Efe Anidi
AI Game Dev

How to start making text-based AI games for web and mobile

A starting guide for AI game designers: why text is where generative games genuinely work today, which AI game formats to pick, and the architecture, costs and store rules you need to ship one on the web or a phone.

20 October 2026 · 11 min read

ai game dev

If you want to make games with AI, where a model generates part of the experience while someone plays, start with text. Not because text is a stepping stone to something grander, but because it is the one medium where generative output is fast enough, cheap enough and controllable enough to carry a game loop today. A language model can produce a paragraph of narration in a second or two, you can check it before the player sees it, you can validate it against a schema, and you can store a whole session in a few kilobytes. None of that is yet true for generated video, and only partly true for audio. Here is where an AI game designer should start: the formats, the architecture, the mobile specifics and the costs.

Why text works now

Text games have a long head start. Interactive fiction goes back to Colossal Cave Adventure and the Infocom era, and the conventions are well understood: a parser or a set of choices, a model of the world, a description of what happens next. Generative text slots into exactly the place where those games were always most limited, which is the response. A hand-written adventure can only answer the verbs its author anticipated. A model can answer almost anything.

That was the promise of AI Dungeon, which Nick Walton built on GPT-2 in 2019. It was a remarkable demo and also a clear lesson: unlimited freedom with no rules underneath quickly feels like dream logic. Nothing you do matters because nothing is tracked, and the story forgets the sword you picked up three turns ago.

So the reason text is the right first medium for AI games is not just that models write well. It is that text is cheap to generate, easy to inspect and easy to combine with ordinary code. You can wrap a model in a conventional game (a few hundred lines of state and rules) and let it do the one thing it is good at: describing a consequence in natural language.

Formats worth building

Not every text format suits generation equally. These are the ones that give someone new to AI game design the best ratio of effort to result.

AI interactive fiction. The classic parser game, except the parser is a model that maps free text to a small set of actions, and the narration is generated. The world, inventory and puzzles stay hand-authored. This is the safest format because the model never decides what is true.

Chat-based RPG with a game master. The model plays a game master for a rules-light RPG. Your code rolls the dice, tracks hit points and resolves checks; the model frames scenes and voices characters. The design problem is tension, because a game master that agrees to everything produces none.

Choice-driven stories with generated branches. The player picks from three or four options; the model writes the next passage and the next set of options. You can generate branches live, or generate them ahead of time, review them and ship a fixed tree. The second approach is underrated: you get the variety of generation with the reliability of authored content.

Word and deduction games. Twenty questions, a murder mystery where you interrogate suspects, a riddle duel. The answer is fixed in code before the game starts, and the model only answers questions about it. These are short, replayable and easy to test, which makes them the best first project.

Companion and character games. A persistent character the player talks to over days, with a relationship meter or a shared goal. These are the hardest to do well and the most exposed to safety and wellbeing concerns, so don’t start here.

Format Model’s job Code’s job Difficulty
Word or deduction game Answer questions in character Hold the secret, judge the win Low
AI interactive fiction Parse intent, narrate outcomes World state, puzzles, inventory Medium
Choice-driven story Write passages and options Track flags, cap length, reach an ending Medium
Chat RPG with a game master Frame scenes, voice characters Dice, stats, combat, quests High
Companion game Sustain a character over time Memory, boundaries, moderation High

The architecture: the model narrates, the code rules

The most useful rule for designing around a language model is this: the state machine owns the rules, and the model only narrates. The model can propose; your code decides. If the player types “I persuade the guard to give me the key”, the model may classify that as a persuasion attempt, but your code checks the player’s stats, rolls the check and updates the state. The model is then told what happened and writes the paragraph.

In practice that gives a three-step turn:

  1. Interpret. Send the player’s input plus a compact summary of the current state, and ask for a structured response: which action from an allowed list, which target, and how confident it is.
  2. Resolve. Your code validates the action against the state, applies the rules and produces a new state plus a list of events (door_opened, hp_lost: 3).
  3. Narrate. Send the events back to the model and stream its prose to the player.

A few non-negotiables sit underneath this.

Never call the model from the client. Any API key shipped in a web bundle or a mobile binary can be extracted, and eventually will be. All model calls go through your server or a serverless function, which holds the key, rate-limits per user and logs usage. That is also where moderation lives.

Use structured outputs for anything that touches state. Most major providers can now constrain a response to a JSON schema; OpenAI calls it Structured Outputs, and others offer equivalents. Validate on your side anyway, and have a fallback for when parsing fails.

Stream the narration. Waiting three seconds for a block of text feels slow; watching it start after half a second feels alive. Server-sent events or a streamed fetch response both work in browsers and in mobile web views.

Keep the prompt small and the state authoritative. Do not resend the entire chat history each turn. Send the current state, a short rolling summary and the last few exchanges. The state object is the memory; the transcript is just a log.

A minimal example

Here is a small TypeScript turn handler for a deduction game: the player questions suspects, and the game ends when they accuse someone or run out of questions. It uses Zod for the schema and the OpenAI Node SDK’s structured-output helper, but the shape is the same with any provider. The model name comes from an environment variable because models change faster than articles.

import OpenAI from "openai";
import { zodTextFormat } from "openai/helpers/zod";
import { z } from "zod";

// Game state lives on the server. The model never sees `culprit`.
type GameState = {
  turn: number;
  maxTurns: number;
  suspects: string[];
  culprit: string;
  clues: string[];
  status: "playing" | "won" | "lost";
};

// What the model is allowed to propose for one turn.
const Proposal = z.object({
  action: z.enum(["ask", "accuse", "unknown"]),
  suspect: z.string().nullable(),
  reply: z.string(), // two to four sentences of narration
});

const client = new OpenAI(); // reads OPENAI_API_KEY on the server only

export async function takeTurn(state: GameState, input: string) {
  if (state.status !== "playing") {
    return { state, text: "The case is closed." };
  }

  const res = await client.responses.parse({
    model: process.env.GAME_MODEL!,
    input: [
      {
        role: "system",
        content:
          "You narrate a short murder mystery. Suspects: " +
          state.suspects.join(", ") +
          ". Known clues: " + state.clues.join("; ") +
          ". Classify the player's input and reply in two to four sentences. " +
          "Never reveal who the culprit is.",
      },
      { role: "user", content: input.slice(0, 500) },
    ],
    text: { format: zodTextFormat(Proposal, "proposal") },
  });

  const p = res.output_parsed;
  if (!p || (p.suspect && !state.suspects.includes(p.suspect))) {
    // Model failure costs the player nothing.
    return { state, text: "The inspector frowns. Try asking another way." };
  }

  // The rules live here, not in the prompt.
  const next: GameState = { ...state, turn: state.turn + 1 };
  if (p.action === "accuse" && p.suspect) {
    next.status = p.suspect === state.culprit ? "won" : "lost";
  } else if (next.turn >= next.maxTurns) {
    next.status = "lost";
  }
  return { state: next, text: p.reply };
}

Notice what the model cannot do. It cannot end the game, invent a suspect or change the turn limit. If it hallucinates, the worst outcome is an odd sentence, not a corrupted save. A real build would add moderation, per-session persistence and streaming, but the division of responsibility stays the same.

Web and mobile specifics

PWA or native. A progressive web app is the quickest route: one codebase, instant updates, no review queue, and a text game needs nothing a browser cannot provide. Native, or a native shell around a web view, earns its keep when you want store discovery, platform payments or notifications that behave reliably everywhere. Build the web version first and wrap it later if the game finds players.

Latency. On a phone, time to first token matters more than total generation time. Stream everything, show a typing indicator immediately, and keep the interpret step short so narration can start sooner. A small, fast model is often the better choice for interpreting input even if you use a larger one for prose.

Offline. A server-backed generative game does not work offline, and it should say so rather than fail silently. You can cache the session so the player can reread the story, and queue their next input until the connection returns. Small on-device models are improving, but don’t depend on them for a first project.

Moderation. Players will type anything, and models can be steered into producing things you do not want in your game. Run input and output through a moderation step, keep a block-list specific to your setting, log flagged turns and give players a way to report a response.

Store policies. Both major stores have rules that apply to generative apps, and they change, so read the current versions before submitting. At the time of writing, Google Play has a dedicated AI-generated content policy that makes developers responsible for preventing offensive output and expects them to act on user feedback about it. Apple’s App Review Guidelines cover user-generated content more broadly and, after a November 2025 update, require apps to disclose and get permission before sharing personal data with third-party AI. In practice: a report button, a clear privacy notice saying where player text goes, and an age rating that reflects what the model could plausibly generate.

Design the loop and the failure states

AI generation makes it easy to produce endless content and hard to produce a game. The remedy is the same as in any genre: design the loop first, then decide where the model sits in it.

A good text loop has a goal, a constraint and feedback. The deduction game above has all three: find the culprit, within twelve questions, with clues accumulating as you go. An open-ended chat with a fantasy character has none of them, which is why it feels hollow after twenty minutes.

Some things that help:

  • Hard limits. Turn counts, a clock, a resource that runs down. Limits give choices weight, and they also cap your costs.
  • Real failure. Players should be able to lose, and the code, not the model, decides when. Models tend to be agreeable; left alone they will let the player talk their way out of everything.
  • Visible state. Show the inventory, the suspects, the health bar. If the only record of progress is prose, players cannot plan.
  • Authored anchors. Write the opening, the key reveals and the endings yourself. Let the model fill the space between them.
  • In-world error handling. Timeouts, refusals and malformed JSON will happen. Each needs an in-fiction response (“The line crackles; say that again?”) and must never cost the player a turn.

What it costs

Prices change too often to quote, so here is the method. Estimate tokens per turn, multiply by turns per session, and apply your provider’s current rates from its pricing page.

Game type Turns per session Input tokens per turn Output tokens per turn Tokens per session (approx.)
Word or deduction game 15 600 120 11,000
Choice-driven story 25 1,500 300 45,000
Interactive fiction (two calls per turn) 40 2,500 350 114,000
Chat RPG, long session 80 4,000 400 352,000

These are rough planning figures, not measurements of any product, and your prompts will differ. The pattern is what matters: input tokens dominate because you resend context every turn. That is why compact state summaries matter, and why prompt caching for repeated prefixes, which several providers offer, can make a real difference.

To turn tokens into money: cost per session = (input tokens × input price + output tokens × output price) ÷ 1,000,000, using the per-million-token prices your provider publishes. Run the sum for a small and a large model; the gap is often around an order of magnitude, and a short deduction game rarely needs the larger one. Compare the result with what a session is worth to you, and put a daily cap per user on the server either way.

Takeaways

  • Text is where AI-generated games work today: it is fast, cheap, inspectable and easy to combine with ordinary game code.
  • Start your first AI game with a word or deduction game: the answer fixed in code, a turn limit, and a model that only answers questions.
  • The state machine owns the rules; the model interprets input and narrates outcomes through validated, structured output.
  • Keep API keys on the server, stream responses, moderate input and output, and let players report content.
  • Build a PWA first; go native when you need store distribution or platform payments, and read both stores’ current AI and privacy rules before submitting.
  • Design a loop with a goal, a constraint and real failure, and handle model errors in-world without charging the player a turn.
  • Estimate tokens per session before choosing a model or a business model; resent context is usually the largest cost.