Skip to content
Tutorials Center
My learning

Topics

Lesson 137 of 146 ยท Projects

Project: A Text Adventure Engine

Build a complete text adventure in Swift step by step - enums for directions and commands, a command parser, a game state struct, locked doors, and a scripted playthrough from stdin.

Text adventures are one of the best small programs to write when you are learning a language. They have almost no user interface, yet they need every skill that matters: modeling a world with types, parsing messy human input, keeping state consistent, and deciding what each command is allowed to change. Classic games such as Zork were built from exactly these parts.

In this project you build a small adventure engine in four steps. First you model the world with enums and structs. Then you write a command parser. Then you build a Game struct whose handle method is a state machine: it takes the current state and a command, and produces new state plus text to show. Finally you drive the whole thing with scripted input, so the program is deterministic and can run in the browser. If you need a refresher, see enumerations, structs and pattern matching.

The plan

The game world has four rooms: a cellar, a hall, a library and a garden. You start in the cellar. The library is dark, so you need the lamp to see anything there. The garden is behind a locked door in the hall, and the key is in the library. Reaching the garden wins the game.

Design before coding. A good adventure engine keeps three things apart:

  • Data: rooms, exits, items. This is plain values.
  • Input: turning a line of text into a typed Command.
  • Rules: what a command does to the state, and what the player is told.

Keeping those apart is what lets you test the rules without typing anything, and change the wording of commands without touching the rules.

Step 1: model the world

Directions are a closed set, so they are an enum. Giving it a String raw value lets you build a direction from text for free, and CaseIterable lists them all. An exit leads to another room and may be locked until the player uses a particular item.

Swift Step 1: directions, exits and rooms

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 readLine()), it gets the next line from this box.

The memberwise initializer gives Exit(to: .cellar) for free, because requires is an optional var and so defaults to nil. Notice sorted() before printing: a dictionary's key order is randomized per run, so any output you want to be stable must be sorted first.

Step 2: parse commands

The player types free text; the engine wants a closed set of choices. That is again an enum, this time with associated values. Each case is one thing the player can do, and the unknown case keeps the original text so the game can answer politely instead of crashing.

Swift Step 2: a command enum and a 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 readLine()), it gets the next line from this box.

Three techniques are worth noticing. The switch is over a tuple (verb, noun), so a single pattern can say "the verb is take and the noun is anything non-empty". A where clause refines a pattern, which is how take alone falls through to unknown. And direction(from: place).map(Command.go) uses Optional.map with the enum case itself as a function: Command.go has type (Direction) -> Command, so a missing direction stays nil and ?? .unknown(line) supplies the fallback.

Keep the parser a pure function from String to Command. It has no state and no printing, so you can test it with a table of inputs, exactly as the loop above does.

Step 3: the game state and its rules

Now the heart of the engine. Game is a struct holding everything that can change: the rooms (items move, doors unlock), where the player is, what they carry, whether the game is over, and how many moves they have made. Its public interface is a single mutating method, handle(_:), which returns the lines to display.

Marking the stored properties private(set) lets outside code read them but only the game's own methods change them. That is a small design choice with a large payoff: no other code can put the game into an impossible state.

Swift Step 3: the Game state machine with a scripted run

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 readLine()), it gets the next line from this box.

The run prints a transcript like this (the middle of it shown here):

TEXT
> go north
  The way north is locked. Perhaps a key would help.
> use key
  You do not have a key.
> go east
  The Library
  Dusty shelves reach the ceiling.
  You see: key, book.
  Exits: west.

Study what the engine did. The first go north reaches the hall. The second finds the oak door locked, and the message names the item that would help. use key fails because the key is still in the library. After the player walks east into the dark library, canSee is true only because the lamp is in the inventory, so the room is described and the key can be taken. The moves counter is 2, because only successful moves are counted: blocked attempts change nothing.

Three design ideas hold this together:

  1. One entry point. All changes go through handle. A command is a value, the result is [String], and the engine never calls print. That is why the script above could call it directly.
  2. Computed properties as views. room is a computed property with a getter and setter that point into the dictionary, so room.items.remove(at: index) edits the current room in place. canSee is derived from state rather than stored, so it can never go out of date.
  3. Derived rules, not flags. The door has no isLocked boolean. It has requires: String?, and use clears it. One field answers both "is it locked?" and "what opens it?".

The force unwrap in rooms[location]! is deliberate and documented: init creates a room for every RoomID, and nothing can remove one. A trap here would mean a programming bug, which is exactly what a force unwrap should signal. For data that comes from outside, never do this. See optionals in depth for the trade-offs.

Step 4: the complete game with scripted input

The last step connects the parser to the engine and reads commands from standard input. In a browser demo you cannot type interactively, so the TryIt presets the input with input="...", one command per line. Because readLine() returns nil at the end of the input, while ... let line = readLine() ends the loop naturally, and the program also stops as soon as the game status is no longer playing.

This version adds the commands that were missing: drop, help and a friendly answer for commands the parser does not understand.

Swift Step 4: the complete adventure

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 readLine()), it gets the next line from this box.

Run it and you get the whole story: the player takes the lamp, tries a nonsense command, is blocked at the locked door, collects the key and the book from the library, drops the book, returns to the hall, unlocks the door and wins. The last lines are:

TEXT
> n
The Garden
Sunlight, roses and a singing bird.
Exits: south.
You win in 4 moves!

The nonsense command prints I do not understand "dance wildly". Type help for a list of commands. and changes nothing. Once the status is won, the loop condition game.status == .playing is false, so any remaining input lines are never read.

Notice the shape of the final loop. It does no game logic at all: it reads a line, calls parse, calls handle and prints. If you later wanted a graphical front end, a web socket or a unit test, only these six lines would change.

Making it testable

Because handle is a plain function from state and command to state and text, a test does not need stdin at all. A test could create a Game, feed it [Command] values, and assert on game.status, game.location and the returned lines. The private(set) properties are readable from a test, which is what you want: tests read state but cannot cheat by setting it. The testing lesson shows how to write such tests with a small harness.

Ideas for extending the game

  • More rooms from data. Move the world into a JSON string and decode it with Codable, as in the Codable lesson. Designers could then edit rooms without recompiling.
  • Synonyms and articles. Strip words such as the and a in the parser so that take the lamp works.
  • A save game. Make Game conform to Codable and encode it. Because it is a struct of value types, the save is a single JSONEncoder call.
  • Items with behavior. Replace the String item names with an Item struct that has a name, a description and flags such as isTakeable.
  • Timed events. Add a turn counter to the state, and let rooms react after a number of moves.

Pitfalls and lessons

  • Stringly typed items. The game uses plain strings for item names. That is quick, but a typo in "key" becomes a silent bug. An Item enum would turn that typo into a compile error.
  • Dictionary order. The exits are stored in a dictionary, so the code sorts the names before printing. If you forget, the output can change from run to run.
  • State in one place. Every mutation goes through Game. If you scattered var globals around the file instead, Swift 6 would also complain about shared mutable state. Keeping state in one value is both better design and the easiest way to satisfy the compiler.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does the parser return Command.unknown(line) instead of failing?

    A parser for human text must expect nonsense. Modeling failure as one more enum case keeps the function total and lets the engine decide what to say.
  2. 2. What does private(set) on status and inventory achieve?

    The getter keeps its normal access level while the setter is limited to the declaring type, so outside code cannot put the game into an invalid state.
  3. 3. Why is handle(_:) marked mutating?

    A method on a value type needs mutating to assign to self's properties. The caller must also hold the game in a var.
  4. 4. How is a locked door modeled in this engine?

    A single optional both says whether the exit is locked and which item opens it, so the two facts cannot disagree.
  5. 5. Why do the exits print through .sorted()?

    Swift randomizes hash order per run on purpose. Sort before you print whenever the output should be repeatable.

Summary

  • Model closed sets (directions, rooms, commands, status) as enums; use associated values for commands that carry data.
  • Keep the parser a pure function from text to a typed command, with an unknown case for bad input.
  • Put all state in one struct with private(set) properties and a single mutating func handle(_:) that returns the text to show.
  • Derive facts such as "can the player see" from state instead of storing them, and let an optional (requires) carry both the lock and the key.
  • Separate input and output from rules so the engine can be driven by stdin, scripts or tests.
  • Sort dictionary keys before printing, and prefer enums over strings once an idea has a fixed set of values.

Next: Project: An Async Pipeline