Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 32 ยท Projects

Project: A Text Adventure State Machine

Build a text adventure in Lua: rooms as tables, a pattern-based command parser, a state machine and coroutines for conversations, with a JavaScript stand-in to run.

Text adventures are the classic way to learn how a program can be a state machine. At any moment the game is in exactly one state (which room you are in, what you carry, whether you are exploring or in the middle of a conversation), and every line you type moves it to the next state. Lua suits this well: tables describe the world, patterns read the player's words, and coroutines let a conversation pause in the middle and wait for the player to answer.

In this project you build a four-room game. You will model rooms as nested tables, parse commands with a Lua pattern, keep the game state in one table, and write a dialogue as a coroutine that yields a question and resumes with the player's reply. Real Lua code is shown read-only; the runnable examples are JavaScript stand-ins (generators play the part of coroutines). Review string patterns and coroutines first if you need to.

One state, many commands

World Rooms are tables with exits and items.
State Room, bag and mode live in one table.
Parser A pattern splits verb and noun.
Dialogue A coroutine pauses for the reply.

Every typed line moves the state forward.

1 / 2

The world as data

A room has a description, exits that name other rooms, and a list of items lying on the floor. The whole map is one table keyed by room name.

LUA
local rooms = {
  hall = {
    desc  = "A dusty hall. Doors lead north and east.",
    exits = { north = "library", east = "kitchen" },
    items = { "lamp" },
  },
  kitchen = {
    desc  = "A cold kitchen that smells of apples.",
    exits = { west = "hall" },
    items = { "apple" },
  },
  library = {
    desc  = "Tall shelves. A grey owl watches you. A heavy door leads north.",
    exits = { south = "hall", north = "vault" },
    items = {},
  },
  vault = {
    desc  = "Gold glitters everywhere. You made it!",
    exits = { south = "library" },
    items = {},
  },
}

-- Entering a room can require an item.
local locks = { vault = "key" }

Using names (strings) for exits instead of direct references to other room tables keeps the data easy to read and avoids circular tables. The locks table is a second, tiny piece of data: to enter vault you need a key.

The state

Everything that can change during play goes into one table. Anything not in it is fixed data.

LUA
local state = {
  room = "hall",
  bag = {},          -- a set: bag.lamp = true
  mode = "playing",  -- "playing" | "talking" | "won"
  dialogue = nil,    -- the active coroutine while talking
}

The bag is a set (names as keys, true as values), which makes "do I have the key?" a single lookup: state.bag.key. When you need the contents in a stable order, collect the keys and table.sort them, because pairs order is not defined.

Step 1: parse what the player typed

Players type go north, n, TAKE lamp or take the lamp. A single pattern captures a verb and the rest, and a few lines of normalizing turn all these forms into a verb and a noun.

LUA
local aliases = { n = "north", s = "south", e = "east", w = "west" }
local directions = { north = true, south = true, east = true, west = true }

local function parse(line)
  local verb, noun = line:lower():match("^%s*(%a+)%s*(.-)%s*$")
  if not verb then
    return nil
  end
  verb = aliases[verb] or verb
  if directions[verb] then      -- a bare direction means "go there"
    return "go", verb
  end
  noun = noun:gsub("^the%s+", "")  -- drop a leading "the"
  noun = aliases[noun] or noun
  return verb, noun
end

The pattern ^%s*(%a+)%s*(.-)%s*$ reads: optional spaces, a word of letters (captured), optional spaces, then the lazy .- capture followed by optional spaces and the end. The lazy .- takes as little as possible, so trailing spaces fall into the final %s* and are not part of the noun. One more thing to know: gsub returns two values (the string and a count), but a plain assignment noun = noun:gsub(...) keeps only the first.

The first stand-in tests the same parser with a JavaScript regular expression (\s and \w for Lua's %s and %a; .*? is the lazy counterpart of .-).

JS Stand-in: the command parser

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Notice that look returns an empty noun, which is fine for commands that take no argument, while "" and "!!!" give nil because the pattern needs at least one letter. The game will answer those with "I did not understand that".

Step 2: commands as a table

As in the to-do project, each verb is a function in a table. Each returns the text to show. A helper describes the current room, including the items and exits.

LUA
local function describe()
  local room = rooms[state.room]
  local exits = {}
  for dir in pairs(room.exits) do
    exits[#exits + 1] = dir
  end
  table.sort(exits)
  local text = room.desc
  if #room.items > 0 then
    text = text .. " You see: " .. table.concat(room.items, ", ") .. "."
  end
  return text .. " Exits: " .. table.concat(exits, ", ") .. "."
end

local commands = {}

function commands.look()
  return describe()
end

function commands.go(dir)
  local target = rooms[state.room].exits[dir]
  if not target then
    return "You can't go that way."
  end
  local needed = locks[target]
  if needed and not state.bag[needed] then
    return "The door is locked. You need the " .. needed .. "."
  end
  state.room = target
  if target == "vault" then
    state.mode = "won"
    return describe() .. "\n*** You win! ***"
  end
  return describe()
end

function commands.take(item)
  local items = rooms[state.room].items
  for i, name in ipairs(items) do
    if name == item then
      table.remove(items, i)
      state.bag[item] = true
      return "Taken: " .. item .. "."
    end
  end
  return "There is no " .. item .. " here."
end

Add a command that shows the bag, with the keys sorted:

LUA
function commands.bag()
  local names = {}
  for name in pairs(state.bag) do
    names[#names + 1] = name
  end
  table.sort(names)
  return "You carry: " .. (#names > 0 and table.concat(names, ", ") or "nothing") .. "."
end

Notice that pairs(room.exits) gives the directions in no particular order, so we collect them and sort before printing. Without the sort, the game's output could change between runs. Notice also that take removes the item from the room's list and adds it to the bag: moving something from one place to another is the essence of a text adventure.

Step 3: a conversation as a coroutine

A conversation is a sequence: the owl asks, you answer, the owl reacts. Written with ordinary functions this becomes a tangle of "which question are we on?" flags. A coroutine keeps its place for you: coroutine.yield hands a line of text to the game and pauses, and the next coroutine.resume delivers the player's answer as the return value of yield.

LUA
local function owlTalk()
  local answer = coroutine.yield("The owl asks: what has keys but opens no door?")
  if answer == "piano" then
    state.bag.key = true
    return "The owl nods and drops a key. 'Clever.'"
  end
  answer = coroutine.yield("'Wrong.' The owl tilts its head. 'One more try?'")
  if answer == "piano" then
    state.bag.key = true
    return "The owl sighs and drops a key."
  end
  return "The owl turns away. Maybe you should read more."
end

function commands.talk()
  if state.room ~= "library" then
    return "There is nobody to talk to."
  end
  if state.bag.key then
    return "The owl has nothing more to say."
  end
  state.dialogue = coroutine.create(owlTalk)
  state.mode = "talking"
  local _, line = coroutine.resume(state.dialogue)
  return line
end

While the mode is talking, the game does not parse commands. It simply passes the raw line to the coroutine and checks whether it has finished:

LUA
local function step(line)
  if state.mode == "talking" then
    local _, reply = coroutine.resume(state.dialogue, line:lower():match("^%s*(.-)%s*$"))
    if coroutine.status(state.dialogue) == "dead" then
      state.dialogue = nil
      state.mode = "playing"
    end
    return reply
  end

  local verb, noun = parse(line)
  if not verb then
    return "I did not understand that."
  end
  local handler = commands[verb]
  if not handler then
    return "I don't know how to " .. verb .. "."
  end
  return handler(noun)
end

The coroutine's two possible endings (a returned line after success, or after the second failure) are both delivered through the same resume, and coroutine.status tells us that the conversation is over. Inside the dialogue, state is an upvalue: a coroutine is an ordinary function body and can read and change anything in scope, which is how the owl can hand over the key.

stateDiagram-v2
  [*] --> playing
  playing --> talking: talk in the library
  talking --> talking: answer is wrong the first time
  talking --> playing: dialogue ends
  playing --> won: enter the vault
  won --> [*]

Three modes: commands go to the parser while playing and to the coroutine while talking.

The complete game

The final stand-in joins all the pieces. JavaScript generators work like coroutines here: yield pauses and next(value) resumes, passing the value back in. One difference: next() is first called without a value (its argument on the first call is ignored), which matches how the first coroutine.resume in Lua starts the function. The script of player inputs is fixed, so the output is the same on every run.

JS Stand-in: the whole adventure

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Follow the transcript: the first go north from the library is refused because the door is locked, talk starts the conversation, and a harp is wrong so the owl yields a second question. After two wrong answers the owl gives up, the coroutine returns, and the mode flips back to playing, so bag shows only what we took. A second talk restarts the riddle from the top (a finished coroutine cannot be resumed, so the game creates a new one), piano earns the key, and the last go north opens the vault and ends the game.

Try editing the play list: answer piano on the first question, or try go north before talking. Each state is reachable only through the commands that lead to it.

Ideas to extend it

  • Add a drop command and a lamp requirement for a dark cellar (a room whose description changes when state.bag.lamp is missing).
  • Give every room an on_enter function in the table, so rooms can run custom code such as a trap.
  • Add save and load by serializing state with a small function that walks the table.
  • Put the dialogue text in data: a table of { prompt = ..., accept = "piano" } steps that one generic coroutine walks through.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In the pattern ^%s*(%a+)%s*(.-)%s*$, why is the noun captured with .- instead of .*?

    A greedy .* would swallow the trailing spaces. The lazy .- matches as little as possible, leaving them for the closing %s*.
  2. 2. What does the value on the right of local answer = coroutine.yield(...) contain after the game calls coroutine.resume(co, line)?

    Arguments given to resume become the return values of the yield that paused the coroutine. That is how the player's reply gets into the dialogue.
  3. 3. Why does describe() collect the exits into a list and call table.sort on it?

    The order in which pairs visits a table's keys is not specified, so a stable display needs an explicit sort.
  4. 4. How does the game know a conversation is finished?

    When the coroutine body returns, its status becomes dead. The game checks that after each resume and goes back to playing mode.

Summary

  • A text adventure is a state machine: one state table plus commands that transform it.
  • Model the world as nested tables and refer to rooms by name.
  • A set (bag.key = true) makes inventory checks one lookup; sort keys before printing because pairs has no defined order.
  • ^%s*(%a+)%s*(.-)%s*$ splits a verb from its noun, and a table of functions dispatches commands.
  • A coroutine can pause in the middle of a conversation: yield sends a line out, resume brings the answer in, and status tells you when it is dead.
  • Route input by mode so the same typed line means different things in different states.

Next: Project: A Tiny Event Emitter and Scheduler