Game With AI NPC: Examples and How to Build One (With Code)

By Arron R.9 min read
A game with AI NPC characters uses either classic game AI (state machines, schedules) or a language model that answers free text. Learn how each works, how to s

A game with AI NPC behavior can mean two very different things: characters driven by classic game AI, like the ghosts in Pac-Man, or characters wired to a language model that answer whatever you type. This guide explains both, shows how to tell which one a game uses, walks through how talking NPCs work under the hood, and then builds one with a short JavaScript example you can drop into your own project.

What is a game with AI NPC characters?

A non-player character (NPC) is any character in a game that the player does not control: shopkeepers, guards, enemies, companions, quest givers. The term comes from tabletop role-playing games, where the game master voiced everyone the players did not.

“AI” in the phrase is where the confusion starts. In game development, AI has always meant the systems that decide what NPCs do. As the Wikipedia overview of game AI points out, most of it is not “true” artificial intelligence at all. It is a set of rules, state machines and pathfinding tuned to feel believable and fun, not to think.

Since language models became cheap enough to call from a game, a second meaning has taken over: a game with AI NPCs is now often a game where you can talk to characters in your own words and get an original reply. Both meanings are valid, and a good design usually mixes them.

Scripted game AI vs language-model NPCs

Scripted game AI

Classic NPC behavior is built from predictable parts:

  • Finite-state machines (FSMs): an NPC sits in one state at a time (idle, patrol, chase, flee) and switches when a condition is met. Pac-Man’s ghosts alternate between a “chase” mode and a “scatter” mode, and each ghost targets the player in its own way, which is why they feel like they have personalities.
  • Schedules and goals: Bethesda’s Radiant AI lets NPCs in the Elder Scrolls games make choices about how to meet goals like eating or sleeping, instead of following one fixed script.
  • Pathfinding: algorithms such as A* that find a route around walls.
  • Behavior trees and utility scoring: structured ways to pick the most sensible action from many options.

Scripted AI is fast, cheap, testable and runs offline. Its weakness is conversation: dialogue is a tree of options a writer prepared in advance.

Language-model NPCs

A language-model NPC sends the player’s words, plus a description of the character and what it remembers, to a large language model, then shows the reply. The player can ask anything. The character can react to things no writer anticipated.

The cost is real: every reply takes time (often a second or more), usually costs money per request, needs a network connection unless you run a local model, and can drift off-script. That is why shipped games almost never let the language model control everything. It handles the talking, while ordinary game code still decides who attacks, what quests unlock and what items exist.

Diagram comparing a scripted NPC state machine with a language-model NPC pipeline
Two kinds of AI NPC: rule-based state machines on the left, language-model dialogue on the right.

Examples of games with AI NPCs you can talk to

The idea is older than most players assume. Façade, released in 2005, let players type freely to two characters in an interactive drama, years before modern language models existed. The Sims series is often praised for NPCs that run their own lives without player input, and Radiant AI did similar work for the Elder Scrolls games.

For typed or spoken conversation powered by language models, the landscape splits into three groups:

  • Released commercial games marketed with free-text NPC conversation, such as Where Winds Meet and inZOI.
  • Mods for existing games: community projects connect Skyrim NPCs to language models and voice synthesis, so you can speak to a guard and get a new, voiced answer. Similar experiments exist for other moddable open-world games, including GTA V police mods. Talk about big upcoming open-world releases getting language-model NPCs is speculation until the studio says otherwise.
  • Indie and game-jam projects: small detective games, interrogations, social deduction and roleplay sims, often playable in the browser. This is where most experimentation happens, because a tiny team can build a game with AI NPCs in a weekend.

The best designs give the conversation a purpose. A suspect you must trick into contradicting herself, a merchant you can haggle with, or a guard you need to talk past are all stronger than “chat with a villager” because the player has a goal and the game can check whether they reached it.

How to tell if a game uses AI NPCs

A quick checklist:

  1. Check the input. A menu of dialogue choices means scripted dialogue. A free text box or microphone input points to a language model.
  2. Repeat a question with different wording. Scripted NPCs give identical lines; model-driven ones rephrase.
  3. Reference something odd. Ask about an event from ten minutes ago, or something outside the game world. A model-driven NPC will usually try to answer, sometimes revealing guardrails (“I don’t know about that, traveller”).
  4. Watch the timing. A short pause before every reply often means a network round trip.
  5. Read the store page. Online requirements and generative AI disclosures are strong hints.

Remember that “good AI” in older reviews almost always means scripted behavior done well, not conversation.

How a talking NPC works under the hood

Every language-model NPC, from a mod to a commercial title, runs the same loop:

  1. Character prompt: a fixed description of who the NPC is, how they speak, what they know and what they must never do.
  2. Memory: a short list of recent exchanges and key facts (“player paid 20 gold”, “player insulted my brother”). Keep it short; long histories cost more and drift.
  3. World state: the facts the NPC can see right now, such as time of day, the player’s reputation, items in the shop.
  4. Structured reply: ask the model for JSON with a say line and an optional action from a fixed list.
  5. Validation: your game code checks the action against the rules before applying it. The model proposes; the game decides.

Here is a minimal, complete client-side version in plain JavaScript. It calls /api/npc, which is your own small server that holds the language model API key and forwards the request. Never put a model API key in browser code; anyone can read it.

const ALLOWED_ACTIONS = ["none", "give_discount", "open_gate", "call_guard"];

const npc = {
  name: "Mara",
  persona:
    "You are Mara, a tired blacksmith in a mountain village. " +
    "You speak in short, dry sentences. You never mention being an AI. " +
    "You only know about the village, smithing and the road north.",
  memory: [],
  mood: 0 // -3 hostile ... +3 friendly
};

function buildPrompt(playerText, world) {
  return [
    { role: "system", content: npc.persona +
      " Reply ONLY with JSON: {\"say\": string, \"action\": one of " +
      JSON.stringify(ALLOWED_ACTIONS) + ", \"moodDelta\": -1, 0 or 1}." },
    { role: "system", content: "World: " + JSON.stringify(world) +
      " Current mood: " + npc.mood },
    ...npc.memory.slice(-8),
    { role: "user", content: playerText.slice(0, 300) }
  ];
}

async function talkToNpc(playerText, world) {
  let reply = { say: "Hm. Say that again.", action: "none", moodDelta: 0 };
  try {
    const res = await fetch("/api/npc", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ messages: buildPrompt(playerText, world) })
    });
    const data = await res.json();
    const parsed = JSON.parse(data.text);
    if (typeof parsed.say === "string") reply = parsed;
  } catch (err) {
    console.warn("NPC fallback used:", err);
  }

  // The game, not the model, has the final word.
  if (!ALLOWED_ACTIONS.includes(reply.action)) reply.action = "none";
  if (reply.action === "give_discount" && npc.mood < 2) reply.action = "none";
  npc.mood = Math.max(-3, Math.min(3, npc.mood + (Number(reply.moodDelta) || 0)));

  npc.memory.push({ role: "user", content: playerText });
  npc.memory.push({ role: "assistant", content: reply.say });
  return reply;
}

// Example use:
talkToNpc("Any work for a traveller?", { time: "dusk", gold: 12 })
  .then(r => console.log(npc.name + ": " + r.say, "| action:", r.action));

Notice the safeguards: input is capped at 300 characters, memory is trimmed to the last eight messages, there is a fallback line if the request or the JSON fails, and the discount only happens if the mood is high enough, no matter what the model says. Those four lines are the difference between a fun NPC and one players can talk into handing over the whole shop.

Five-step pipeline showing how a talking NPC turns player input into a game action
The talking-NPC loop: the model proposes, your game code decides.

Build your own game with AI NPCs in WizardGenie

Wiring all of this up by hand (the game loop, the dialogue UI, the server proxy, the state machine for the parts that are not conversation) is a lot of code for a beginner. WizardGenie is the AI-native game engine at the heart of Sorceress: you describe the game you want, and it writes, runs and iterates on it in real time. That fits NPC work well, because talking characters need constant tuning: you play, notice the blacksmith is too chatty, describe the fix, and try again.

A practical way to use it:

  1. Describe the core loop first, without the language model. For example: “A top-down village game. The player walks with WASD. Three NPCs stand in the square. Walking up to one and pressing E opens a text box.” Get that playing before anything else.
  2. Add the NPC brain as a separate module. Paste the structure from the code above and ask WizardGenie to connect the text box to talkToNpc, show the reply in a speech bubble and apply only actions from the allowed list.
  3. Keep scripted behavior scripted. Ask for a simple state machine for movement (idle, wander, go home at night). The language model only handles words.
  4. Add a goal the game can check. “If Mara’s mood reaches 3, the north gate opens and the level ends.” Now conversation is gameplay.
  5. Iterate on personality in plain English. Change the persona text, replay, compare.

WizardGenie drives every leading AI coding model, and you can switch between them freely with your own API key. It runs in the browser with nothing to install, and as a Windows desktop app with an auto-updater that gives native file access and longer agent sessions, which helps once a project grows past a single scene. The WizardGenie overview covers the engine in more detail, and this walkthrough of building a playable browser game shows the describe-play-refine rhythm on a smaller project. If you are new to building this way, the idea is close to what is called vibe coding: you steer with descriptions and play-testing rather than typing every line.

One thing to plan for: the language model your NPCs talk through at runtime is separate from the coding model WizardGenie uses to build the game. Your finished game still needs its own server endpoint and key for NPC dialogue.

Giving your NPCs a face and a voice

A talking character feels far more alive with art and sound. Auto-Sprite v2 creates game-ready 2D sprites, characters included, in any art style, so each NPC can have its own animated look. Sound Studio covers music, SFX and text-to-speech with lifelike AI voices, useful for a voiced greeting line per character. If you want WizardGenie or another coding agent to generate assets on its own while it builds, the Sorceress API gives it one key for sprites, 3D models, rigs, animation, music and SFX. The full tools guide lists everything else.

Common mistakes and trade-offs

MistakeWhat goes wrongFix
Letting the model change game state directlyPlayers talk NPCs into giving away items or skipping questsFixed action list, validated by game code
API key in the browserAnyone can copy it and run up your billProxy all calls through your own server
Unlimited memorySlower, pricier replies that drift off-characterKeep the last few turns plus a short facts list
No fallback lineA failed request freezes the conversationAlways have a scripted reply ready
Chat with no goalNovelty wears off in minutesTie conversation to something the game can check
Every NPC is model-drivenHigh cost and lots of waitingUse language models for a few key characters; script the crowd

The biggest trade-off is control versus surprise. The more freedom you give a language-model NPC, the more memorable moments you get, and the more often it says something off-tone. A tight persona, a short memory and a strict action list keep that balance where you want it. Also plan for players who type nonsense or try to break the character: test with hostile input before anyone else does.

Finally, think about who pays. Every conversation in a game with AI NPCs has a running cost. Rate limits per player, a small model for idle chatter, and scripted lines for common questions all keep it manageable.

The workflow at a glance

  1. Decide what “AI NPC” means for your game: scripted behavior, language-model conversation, or both.
  2. Build the playable loop first with scripted movement and interaction.
  3. Add one talking NPC with a persona, short memory, world state and a fixed action list.
  4. Route model calls through your own server and validate every action in game code.
  5. Give the conversation a goal the game can check.
  6. Add art and voice, then play-test with players trying to break it.

Start with a single character in a single room. Once that one NPC feels alive, adding a second is mostly writing a new persona, and you can do all of it by describing what you want in WizardGenie and playing the result.

Frequently Asked Questions

Can you use AI in games?

Yes, and games always have. Enemy behavior, pathfinding and NPC schedules are all game AI, usually built from rules and state machines. Newer games also connect characters to language models so they can answer typed or spoken input. As a developer you can use both: rules for anything that must be reliable, like combat and quest logic, and a language model for open-ended conversation.

How to tell if a game uses AI NPCs?

Test the input. If you can only pick from a menu of dialogue options, the NPC is scripted. If you can type or speak anything and get a relevant, newly worded reply, a language model is almost certainly involved. Other signs: replies that reference what you said earlier, small delays before answers, and an online requirement for conversations. Store pages often mention generative AI in their disclosures.

What are some games that have AI interaction?

Classic examples of game AI include Pac-Man, whose ghosts each chase the player differently, the Elder Scrolls series with Bethesda’s Radiant AI, and Façade from 2005, which let players type to its characters. More recent releases, such as Where Winds Meet and inZOI, are marketed with NPCs that respond to free text, and community mods connect Skyrim NPCs to language models.

Are there free games with AI NPCs?

Some exist, but running a language model costs money per conversation, so free titles often limit chats, run a small local model, or ask you to bring your own API key. Many indie and game-jam projects with talking NPCs are free to play in the browser. If you want full control, building a small one yourself is practical: a single NPC with memory and a few actions is a weekend project.

Can I make a game with AI NPCs without coding?

Mostly, yes. With an AI game engine like WizardGenie you describe the game and the NPC behavior in plain English, and it writes, runs and iterates on the code. You still need to understand the moving parts: the character prompt, memory, allowed actions and a server-side proxy for your language model key. Knowing those lets you give precise instructions and fix problems quickly.

Sources

  1. Non-player character — Wikipedia
  2. Artificial intelligence in video games — Wikipedia
  3. Radiant AI — Wikipedia
  4. Vibe coding — Wikipedia
Written by Arron R.·2,242 words·9 min read

Related posts