Skip to content
Tutorials Center
My learning

Topics

Lesson 124 of 132 ยท Projects

Project: Text Adventure Engine

Build a text adventure in Rust: model rooms, items and commands as enums, parse input safely, share behavior with a trait and drive the game with a small state machine.

Text adventures are a perfect first "real" program for Rust's type system. Everything in the game is a choice from a small, fixed list: a room, a direction, an item, a command, a phase of the game. That is exactly what enums are for. Where other languages use strings and if chains ("is the player in the string "hall"?"), Rust lets you list every possibility once and then makes the compiler check that you handled all of them.

In this project you build a small engine in three stages: the vocabulary (enums and a command parser), the world (rooms, items, a locked door) and the rules (a state machine that decides what each command does). Along the way you meet a trait for shared behavior, match on tuples, let ... else, and the "make illegal states unrepresentable" habit that Rust programmers lean on.

The plan

The world is four rooms. You start in the cellar, where a lamp lies on the floor. A key is hidden in the garden. The vault is behind a locked door, and it is dark inside. To win you must pick up both items, unlock the door with the key, light the lamp, and walk in.

flowchart LR
    Cellar["Cellar<br/>(lamp)"] -- north --> Hall["Hall<br/>(locked door)"]
    Hall -- south --> Cellar
    Hall -- east --> Garden["Garden<br/>(key)"]
    Garden -- west --> Hall
    Hall -- "north (needs key + light)" --> Vault["Vault<br/>(goal)"]

The map. Every arrow is a possible move, but the arrow into the vault has two conditions.

The program does not read from the keyboard, because the browser runner has no live terminal. Instead the main function feeds a script of commands to the game, which also makes every run identical and easy to test. Reading real input later only means replacing the script with std::io::stdin().lines().

Stage 1: the vocabulary

Start with the nouns and verbs. A Direction is one of four values. A Command is one of six verbs, and some carry data: Go carries the direction, Take and Use carry the item. Because the data lives inside the variant, you cannot build "go with no direction" at all.

Parsing is where untrusted text enters the program, so it returns a Result. The error type is also an enum, which lets the caller decide how to react and lets us write one Display implementation that produces friendly messages.

Rust Stage 1: directions, items, commands 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 io::stdin().read_line()), it gets the next line from this box.

Notice what the types buy you:

  • Command::Go(Direction) makes a half-formed command impossible. Later code never checks "did the player say where?", because a Go always has an answer.
  • Direction::parse(verb).unwrap() is safe here: the match arm only runs for the four one-letter words, and all four parse. When a guarantee lives in a different place than the call, a short comment is worth adding in real code.
  • ok_or and ok_or_else convert an Option to a Result. Use ok_or_else when building the error allocates, as to_string does, so the work only happens on failure. See Result and Option conversions if the pattern is new to you.
  • The ? operator at the top returns early with ParseError::Empty for a blank line, so the rest of the function can assume there is a verb.

Stage 2: the world and a trait

Now the places and the things in them. A Room is another plain enum, and the map is a method: exit(direction) returns Some(room) or None. Keeping the map as a match has a big advantage over a table of strings. If you add a room, the compiler flags every match that forgot it.

Rooms and items both have a name and a description, so we describe them through a trait. It has two required methods and one default method built from them:

Rust
trait Describe {
    fn name(&self) -> &'static str;
    fn describe(&self) -> String;

    fn label(&self) -> String {
        format!("[{}]", self.name())
    }
}

Any type that implements name and describe gets label for free. That is the same idea as the Account trait in the bank project. Read traits and trait objects if you want a refresher; here the trait is used with static dispatch, so there is no Box<dyn Describe> and no run-time cost.

Stage 3: the state machine

The game itself is a value with a few fields, and the most interesting field is the phase: Exploring, Won or Quit. The phase decides what is allowed. While exploring, commands change the world; once the game is won or quit, every command gets the same answer. Modeling that with an enum, instead of a bool called finished plus another called won, rules out the impossible combination "won but not finished".

stateDiagram-v2
    [*] --> Exploring
    Exploring --> Exploring: look, take, use, go
    Exploring --> Won: enter the vault
    Exploring --> Quit: quit
    Won --> [*]
    Quit --> [*]

Phases of the game. Only Exploring accepts moves; the other two are terminal.

There are two smaller state flags: the Door (locked or unlocked) and whether the lamp is lit. The door is an enum rather than a bool so that self.door == Door::Locked reads like English.

The method that does the work is step. It takes a Command, mutates the game and returns the text to print. Returning a String instead of printing inside the engine keeps the rules separate from the output: tests can compare strings, and a graphical front end could reuse the engine unchanged.

Rust Stage 3: the complete engine with a scripted playthrough

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

Read step and use_item slowly, because they carry the lessons of this project.

  • match (item, self.room) matches on a tuple, so one arm can talk about the item and the place together. The if after a pattern is a match guard: (Item::Key, Room::Hall) if self.door == Door::Locked only fires while the door is still locked, so using the key twice falls through to the next arm.
  • The compiler checks exhaustiveness. Delete the (Item::Lamp, _) arm and the program stops compiling with E0004: non-exhaustive patterns. In a string-based engine that bug would be a silent "nothing happens".
  • let Some(next) = ... else { return ... }; in go unwraps the exit or leaves early, so the happy path stays flat instead of nesting.
  • step begins with a phase check. Once the player has won, no command can move them again, and the guard needs only one place instead of one per command.
  • self.floor.remove(index) removes the item from the room and inventory.push(item) adds it to the player. Because Item is Copy, there is no clone and no move error; an item can never exist in two places because the vector holds the only record.

Try breaking it: add Room::Attic without touching exit or describe, and read the compiler error. The error lists the exact match expressions you must update, which is the main reason to model a world with enums.

Ideas to extend it

  1. Real input. Replace the script with for line in std::io::stdin().lines() and line.unwrap(). The engine does not change.
  2. Data-driven rooms. Store rooms in a HashMap<Room, RoomData> or load them from a text file, and parse errors become Result values with ?. See file I/O.
  3. A Describe for the game. Implement the trait for Game so look is self.describe().
  4. Undo. Keep a Vec<Game> of snapshots (derive Clone on the state) and add an undo command.
  5. More state. Replace lamp_lit: bool with enum Light { Off, On { turns_left: u32 } } so the lamp burns out. Enums with data express this better than two fields.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why is Command::Go(Direction) better than a struct with a verb string and an optional target string?

    The data lives inside the variant. A half-formed command cannot be built, so the compiler guarantees what the rest of the code may assume.
  2. 2. What happens if you add a new Room::Attic variant but forget to handle it in a match self without a wildcard arm?

    Exhaustiveness checking is a compile-time guarantee. Avoid a catch-all _ arm in matches where you want the compiler to flag new variants.
  3. 3. Why model the game's phase as enum Phase { Exploring, Won, Quit } instead of two booleans finished and won?

    Two booleans have four combinations, and some are meaningless. The enum has exactly the states the game can be in, which is called making illegal states unrepresentable.
  4. 4. In (Item::Key, Room::Hall) if self.door == Door::Locked => { ... }, what does the if self.door == Door::Locked part do?

    A guard adds a run-time condition to a pattern. When it is false, matching continues with the next arm, which is how a second use of the key reaches 'Nothing to unlock here.'
  5. 5. Why does Game::step return a String instead of calling println! itself?

    A function that returns its result can be asserted on in a test and rendered by any interface. Printing inside the engine ties it to the terminal.

Summary

  • Model the vocabulary of a program (directions, items, commands, phases) as enums; put data inside variants so invalid combinations cannot be built.
  • Parse text into those types once, at the edge, and return a Result with an error enum so callers can react and Display can explain.
  • Put the map and the rules in match expressions; the compiler's exhaustiveness check tells you everything that must change when the world grows.
  • A trait with required methods and default methods lets rooms and items share behavior without inheritance.
  • A state machine is an enum plus transitions in one method; guards (if) and tuple patterns keep each rule in one arm.
  • Return strings from the engine and print them at the edge, so the logic stays testable.

Next: Project: LRU Cache with Safe and Unsafe Variants