Skip to content
Tutorials Center
My learning

Topics

Lesson 173 of 182 ยท Projects

Project: Text Adventure Engine

Build a text adventure engine in C# in four stages: immutable game state with records, a list-pattern command parser, a pure step function with locked doors and darkness, then undo and tests.

Text adventures are one of the oldest kinds of computer game: you read a description, type a command such as take lamp or go north, and the game answers. They are also a wonderful programming exercise, because nearly every classic technique shows up in a small package: parsing free text into commands, a state machine that decides what each command does, data-driven design (the world is data, not code), and, as you will see, an undo that costs almost nothing when your state is immutable.

You build the engine in four stages, and each stage is a complete program. In stage 1 you model rooms, exits, items and the player's state with records and immutable collections. In stage 2 you write the parser, which turns lines like "pick up the brass lantern" into command objects, using list patterns. In stage 3 you write the engine as a pure function (state, command) -> (new state, messages), load the world from a small text format, and play a short game with locked doors, an inventory and a dark room. In stage 4 you add undo and write an automated test suite that includes a full walkthrough of the game.

The game is a tiny puzzle: you are on a beach, there is a lighthouse whose lamp has gone out, and you must light it. Everything here is original. The engine does not know anything about lighthouses, though; swap the world file and you have a different game.

The plan

Stage Question Tools
1 How do we represent the world and the player? records, with, immutable collections
2 How do we understand what the player typed? list patterns, switch expressions, pattern matching
3 How do we decide what happens? pure functions, pattern matching, raw strings
4 How do we undo, and how do we know it works? stacks, tests

In these examples the game reads its commands from the "Program input" box and prints each one after a >, as if you had typed it. On your own machine, replace the scripted lines with Console.ReadLine() from the keyboard and you can play interactively. Every program ends when the input does.

Stage 1: modelling the world and the player

Start by separating what never changes from what changes as you play.

  • The world is fixed: rooms with names and descriptions, exits between rooms, and the catalogue of items. We build it once and never modify it.
  • The game state changes with every command: the room you are in, where each item currently is, how many moves you have made.

The second part is the interesting one. If GameState is an immutable record, a command does not modify the state, it produces a new one. Records make that comfortable with with:

C#
var next = state with { Room = "path", Moves = state.Moves + 1 };

For the item locations we need a dictionary, and a normal Dictionary<,> is mutable: copying it for every move would be slow and awkward. System.Collections.Immutable solves exactly this. ImmutableDictionary.SetItem(key, value) returns a new dictionary that shares most of its internal structure with the old one (it is a persistent tree), so "changing" one entry costs a handful of allocations and leaves the original intact. We use a plain string as the location: either a room id or the special value @carried.

C# Stage 1: rooms, items and immutable state

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Points worth pausing on:

  • Why immutability pays off. afterMove and afterPickup were both derived from start, and start is still valid and unchanged. You never have to ask "who else holds a reference to this and will be surprised?". The same property gives you undo, saving, branching "what if" searches (an AI that tries moves), and safe use from several threads, all for free.
  • with copies, then changes. It creates a new record with the same values except the ones listed. It is a shallow copy, which is exactly right here because the members it copies (strings, an immutable dictionary) are themselves immutable.
  • Primary-constructor records for plain data. Each type is one line. Room and Item are never changed after creation; GameState is replaced, not edited.
  • Local functions capture variables. Describe and Names use rooms and items from the surrounding code. In stage 3 these will move into a class, but while exploring, local functions keep everything on one page.
  • Strings as locations are simple, but a string can hold a typo. In a larger engine you would use a small readonly record struct Location or a union of "in room" and "carried". The upside here is that JSON, tests and the text format all stay trivial.

A good question when designing a model is "what would I have to change to add a new feature?". Locked doors need a place to store which are open: one more member on GameState. A light source needs a list of lit items: another member. Because the state is one record, adding a member is a localized change, and with expressions elsewhere keep working.

Stage 2: understanding the player

Players type anything: go north, n, walk to the north, pick up the lamp, TAKE LAMP!!. A parser's job is to turn that mess into a small set of precise command objects, or to say politely that it didn't understand. The rest of the engine never sees strings, only commands such as Take("lamp"), which means the rules can be written (and tested) without caring how people phrase things.

The approach has three steps:

  1. Normalize. Lower-case the text, split it into words, drop punctuation and filler words (the, a, to, at), which carry no meaning for our simple grammar.
  2. Match the shape. Compare the words to patterns: one word that is a direction means "go there"; take followed by something means pick that up; and so on. C# list patterns express these shapes directly: ["go", var direction] or ["take", .. var what], where .. var what captures all remaining words as an array (list patterns).
  3. Fail helpfully. An unknown verb gives the message "I don't know how to 'dance'", and a known verb without an object gives "take what?". Those are better than a crash or a silent no-op.

Order matters in a switch expression: the first matching arm wins, so specific patterns come first and the catch-all last. The program below parses a list of typical inputs, including awkward ones, and prints what each becomes.

C# Stage 2: a list-pattern command parser

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

What to notice:

  • Normalize first, match second. Because the words are lower-cased, stripped of punctuation and filler, Walk to the west. and go west reach the switch as the same two words. The patterns stay short.
  • [var word] when Directions.TryGetValue(...) is a pattern with a guard: it matches any single word, and the when clause then checks that it is really a direction. Variables declared in a guard (direction) are scoped to their own arm, so reusing the name in the next arm is legal.
  • .. var what is the slice pattern: it matches zero or more elements and captures them. The extra when what.Length > 0 makes sure take alone does not match the "take something" arm.
  • ("take" or "get" ...) and var verb combines an or pattern with a capturing and. It lets one arm handle the whole family of "verb without an object" and use the verb in the message.
  • Output of records. The program prints commands directly, and records give you a readable ToString such as Take { Target = brass lantern } for free. That alone makes parsers pleasant to debug.
  • light lantern with matches becomes Light { Target = lantern }: with is a filler word, and TakeWhile(word => word != "matches") drops the trailing tool the player named. A real engine would parse "with" properly and keep the tool; our engine decides what lighting needs from the world data.
  • Everything unknown becomes Unknown(message), not an exception. Misunderstanding the player is normal, not exceptional, and the engine can print the message like any other.

This is a keyword parser. Commercial adventure games use grammars with nouns, adjectives and prepositions, but the architecture is the same: text in, command objects out. Replacing this parser with a smarter one would not change a line of the engine.

The order of arms in a switch expression is part of the logic. If you moved the final [var verb, ..] arm above the others, every command would be "unknown". The compiler helps: it reports an error for an arm that can never be reached because an earlier arm already covers it, so a mistake like that does not compile.

Stage 3: the engine as a pure function

Now the heart of the game. We express it as one function:

C#
Outcome Run(GameState state, Command command)   // Outcome = (GameState NewState, string[] Lines)

It never prints and never reads input. It takes the state and a command and returns the new state and the lines to show. A function like this is pure: the same inputs always give the same outputs, with no hidden effects. That is why the engine is trivial to test (give it a state and a command, check the result), why undo is trivial (keep old states), and why the same engine could run behind a web page or a bot.

The world as data

The world is long-lived, structured data, so we move it out of C# and into a small text format that a non-programmer can edit. One line per fact, fields separated by |:

TEXT
room | id | name | description | flags            (flag: dark)
exit | from-room | direction | to-room | flags | message    (flags: lock=<item-id> safe)
item | id | name | location | description | flags          (flags: portable, light=<needs>, wins)

A locked exit needs a named item to be unlocked. A safe exit can be used in the dark. An item that is lightable lists what the player must carry to light it (light=matches,oil), and the item that wins the game ends it when lit. The loader reads the lines with list patterns again, checks the whole file (every exit must lead to a room that exists, every item must be somewhere real) and reports the line number of the first problem. Validate at the boundary and the engine can trust its data.

The rules

The engine's switch maps each command to a small method:

  • Look describes the room. In a dark room it only says that it is dark, unless a lit item is carried or lying in the room.
  • Go checks that the exit exists, is not locked, and is usable (in the dark only safe exits work). Walking to a new room increases Moves and describes the room.
  • Unlock opens a locked exit of the current room if the player carries the required item. The opened exits are remembered in the state as room:direction strings.
  • Take/Drop move an item between the room and the inventory; scenery (not portable) cannot be taken.
  • Light requires the item to be present and all items in its light= list to be carried. A lit lantern lights up dark rooms. Lighting the wins item ends the game.
  • A command that doesn't change anything (a refused move, look, inventory) returns the same state object, which lets us define "did this command do something?" as !ReferenceEquals(before, after). The engine uses this to count moves; stage 4 uses it for undo.

The scripted game below solves the puzzle, with a few mistakes on the way, so you can watch each rule fire.

C# Stage 3: the engine, the world file and a scripted game

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Read the transcript with the code beside it:

  • Refusals do not count as moves. take driftwood (scenery), north through a locked door, up in the dark: all return the original state object, so Moves is not incremented. The rule "changed state means a move" lives in one place at the end of Run.
  • Darkness is a derived fact, not a stored flag. IsLit is computed from the room and the lit items every time, so it can never be out of date. When something can be calculated from the state, do not store it in the state.
  • Why Unlocked is a set of strings. A key such as path:North identifies one exit of one room. Unlocking adds it with Add, which returns a new immutable set; the old state still has the old set.
  • The loader validates in two passes. Exits are collected first and attached after all rooms are known, so the file may list rooms and exits in any order. All problems carry the line number. Try breaking the text (a misspelled room id) in the editor and read the message.
  • Say overloads. The params version lets you write Say(state, "one line"); the array version handles a string[] from Describe. A small convenience, but it keeps the rules readable.
  • Finding things by name. Matches accepts the id, the full name, or the last words of the name, so key, iron key and the iron key all work. Exact rules like this are where adventure games spend most of their polish.
  • The engine knows nothing about this game. It never mentions a lighthouse, a key or a lantern. Edit WorldText.Lighthouse and you play a different game with the same code.

The sandbox editor has no keyboard attached to the program, which is why the commands are fed in through the input box. Notice that the game also ends the loop by itself after you win (state.Phase == Phase.Playing in the while condition), so the extra look line at the end of the script is never read.

Stage 4: undo and tests

Because the state is immutable, undo is a stack of old states. Before applying a command that changes the state, push the current state; to undo, pop. There is no "reverse" logic to write for each command and no way to forget one, so the whole feature is a dozen lines in a Game wrapper around the engine. That is the payoff of the design you chose in stage 1.

Persistent collections make this cheap in memory too: the old and new ImmutableDictionary share most of their structure, so a hundred saved states do not mean a hundred copies of the whole world.

The last job is tests. A text adventure is easy to test because the engine is a pure function: build a state, apply a command, assert on the new state or the lines. The suite below has four kinds of test:

  1. Parser table tests: a list of (input, expected command). Record equality does the comparison.
  2. Rule tests: one test per rule, each starting from a short script of commands. They cover the locked door, the dark stairs and the "refusals are free" rule.
  3. Undo tests: undo restores the exact previous state; undo with nothing to undo is harmless.
  4. A walkthrough test: the full winning sequence, ending in Phase.Won with an exact move count. If someone edits the world file and makes the game unwinnable, this test fails.

There is also a test for the loader: a broken world must be rejected with the line number in the message.

C# Stage 4: undo, and a test suite with a full walkthrough

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

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A few things this stage teaches:

  • Undo without any undo code per command. Game.Input pushes the old state only when the engine returned a different state object. The test undo: restores the previous state exactly even checks ReferenceEquals(before, game.State): the very same object comes back, with no copying and no reconstruction. Compare with a mutable design, where each command would need a matching "reverse" operation.
  • Test the outcome, not the implementation. The walkthrough passes through the parser, the engine and the loader at once, and a rule test needs only a handful of commands. When the world file changes legitimately (a longer route), you update one number.
  • A test can document a design decision. The test "lighting needs the right items in hand" pins down that the matches must be carried, not merely in the room. If a designer changes the rule, the test fails and forces a conscious decision.
  • Edge case worth knowing. Because refusals return the same state object, Moves counts effective actions only. A with expression that changes nothing still creates a new object, so a rule that does that by accident would count as a move and add an undo step. Reference identity is a sharp tool, which is why the "refused commands cost no move" test exists.

Where to take it next

  1. More verbs. open and close for containers, put key in box, read note. Each needs a command record, a parser arm, an engine method and a test; nothing else changes.
  2. A better parser. Handle two-word targets with adjectives, pronouns (take it), and disambiguation ("Which key, the iron key or the brass key?"). Keep the output type, Command, unchanged.
  3. Saving and loading. Serialize GameState to JSON with System.Text.Json. ImmutableDictionary and ImmutableSortedSet<string> serialize as ordinary JSON objects and arrays, and a saved game is just the state plus the name of the world file (JSON).
  4. Non-player characters. Add a Characters section to the world file and a talk command with a small dialog tree stored as data.
  5. Timed events. Let Moves drive things: the lantern runs out of oil after twenty moves; a tide covers the beach. The pure engine makes this a function of the state.
  6. A web front end. Wrap Game in a minimal API with POST /command, keep one Game per session in a dictionary, and play from a browser.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is undo so simple in this engine?

    A command produces a new state instead of editing the old one, so the old state is still intact. Undo is just popping the previous state from a stack, with no per-command reverse logic.
  2. 2. What does the pattern ["take" or "get" or "grab", .. var what] when what.Length > 0 match?

    The slice pattern .. var what captures the remaining words (zero or more) and the guard requires at least one. So take alone does not match this arm.
  3. 3. Why does the engine's Run method return the same GameState object for a refused command?

    Returning the identical object is the signal for no change. The engine only increments Moves, and the Game wrapper only pushes onto the undo stack, when the returned state is a different object.
  4. 4. Why is darkness computed by IsLit instead of being stored as a flag in GameState?

    If a value can be derived from other state, storing it as well creates two sources of truth that can disagree. Deriving it each time keeps the state minimal and consistent.
  5. 5. What is the main benefit of loading the world from a text format instead of writing it in C#?

    Separating data from logic makes the engine reusable and lets non-programmers edit the content. The loader validates the data once so the engine can trust it.

Summary

  • Split the model into fixed world data and changing game state; make the state an immutable record and derive new states with with.
  • Use ImmutableDictionary and ImmutableSortedSet for state collections: "changing" them returns a new collection that shares structure with the old one.
  • A parser normalizes text, then matches shapes with list patterns (["take", .. var what]), and returns command objects. Unknown input becomes an Unknown command, not an exception.
  • Write the engine as a pure function from (state, command) to (new state, messages); that makes it easy to test, to replay, and to run behind any front end.
  • Return the same state object for a no-op, and use that fact for move counting and undo.
  • Keep content in a validated text format; derive facts (like "is it lit?") instead of storing them; test with parser tables, small rule tests, and a full walkthrough.

Next: Project: Log Analyzer