Skip to content
Tutorials Center
My learning

Topics

Lesson 125 of 134 ยท Projects

Project: A Text Adventure Engine

Build a text adventure engine in Ruby: describe rooms with a small DSL, parse commands with pattern matching, track state, and play a scripted game.

Text adventures ("go north", "take lamp") are a wonderful small project: they need a model of a world, a way to describe that world conveniently, a parser for commands and a game state that changes as you play. In this project we build an engine that is separate from the story. The story is written in a tiny domain-specific language (a DSL) that looks almost like a description, and the engine plays any story written in it.

The pieces are: Data objects for doors, instance_eval for the DSL, pattern matching for commands, and a small state machine for "playing", "won" and "quit". Because the game reads commands with gets, we can play it from a script and get the same output every time.

Step 1: the world as plain data

Before inventing a DSL, write the world by hand to see what a room needs: a description, exits (doors) leading to other rooms and items lying around. A door can require something the player carries, such as a lamp for a dark cellar.

Ruby Step 1: rooms as hashes

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

It works, but writing a whole story as nested hashes is noisy and easy to get wrong, and a mistyped key (:itmes) hides until runtime. We want to write a room the way we would explain it to a friend.

Step 2: a DSL with instance_eval

A DSL in Ruby is usually plain Ruby that reads like a small language. The trick that makes it possible is instance_eval: it runs a block with self set to another object, so a bare word like door in the block becomes a method call on that object. The World object collects rooms; every room call creates a Room and evaluates its block against that room.

Ruby Step 2: describing rooms with a DSL

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

Compare this with step 1. The story now reads as a description, and the engine classes validate nothing yet, but a typo such as itm "lamp" will raise a NoMethodError at once, because Room has no such method. That is a real advantage of a DSL built from methods over one built from hashes.

Choose DSL method names carefully. We call the method door, not exit, because exit already exists on every object (Kernel#exit stops the program). If a Room defined its own exit method it would work inside the block, but a bug in the block's neighbourhood could end up calling the wrong one, and anyone reading the code would be surprised. The same goes for puts, print, format and open.

Checking the story before the game starts

A story with a door to a room that does not exist would crash in the middle of a game. Better to validate right after building. The DSL makes this a simple loop over what was collected.

Ruby Validating a story

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

flat_map and filter_map turn "check every door of every room" into a single expression, and the message names the room, the direction and the missing target. The last line removes the attic from the world with Hash#except and counts the new problems: two doors now lead nowhere. In the final engine we call a validation like this once, before the first command.

Step 3: commands with pattern matching

Players type short sentences: go north, take lamp, inventory. Splitting the line into words gives an array, and case/in matches arrays by shape. That is exactly what a command parser needs.

Ruby Step 3: a 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 gets), it gets the next line from this box.

Several features of pattern matching are used here. "look" | "l" is an alternative: either string matches. => direction binds the matched value to a variable, and in the "north | south ..." pattern the whole alternative is bound. The pattern [verb, *rest] is a catch-all for any non-empty array, so every input gets a result and the method returns [:unknown, "dance", ["wildly", "now"]] instead of failing. The input "take" alone does not match ["take", item] (that needs two words), so it ends up as unknown with an empty rest; the game can then ask "take what?".

Order matters: patterns are tried from the top, and the first match wins. The catch-all must come last.

What happens without a catch-all

If no pattern matches, case/in raises NoMatchingPatternError. That is different from case/when, which quietly returns nil. It is a feature when you want unexpected input to be loud, and a bug when you forgot the final clause.

Ruby A case/in without a catch-all (fails on purpose)

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

The first call prints :look. The second ends the program with main.rb:2:in 'Object#parse': ["dance", "wildly"] (NoMatchingPatternError): the message is simply the value that nobody matched. Add in _ or in [verb, *] at the end, or a rescue NoMatchingPatternError, to handle it.

Step 4: game state and the loop

The game has a state: where the player is, what they carry and whether the game is still going. A tiny state machine keeps the last part simple: :playing becomes :won when the player reaches the goal room, or :quit when they quit. The loop runs while the state is :playing.

Each command is a method that returns the text to print. Returning strings instead of calling puts inside the engine has a big benefit: the engine can be tested without any input or output at all.

Step 5: the complete game

Here is everything together: the DSL classes, the story, the engine and the loop that reads scripted commands. The story: find a lamp, go down into the cellar, but you need the key from the library to open the vault.

Ruby The complete text 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 gets), it gets the next line from this box.

Follow the transcript. take lamp works only once, because room.items.delete(item) both removes the item from the room and tells us whether it was there (it returns nil otherwise). In the cellar, get key reports that there is no key here, and east is refused with the door's own message, because the player has no key yet. So the player walks up and north to the library, takes the key, and comes back. dance wildly is answered by the catch-all pattern. The second down and the final east now succeed, and entering the vault makes go set the state to :won, so the loop ends and the last look in the script is never read. The final line prints Final state: won.

The design has a nice property: nothing in Game knows about lamps or vaults. All of that is data in the story. Writing a second adventure means writing a second World.build block and nothing else.

Why handle returns strings

Because handle returns text and Game never prints, a test needs no stdin tricks:

Ruby
# read-only example: a Minitest test for the engine
game = Game.new(world, start: :hall)
assert_equal "Taken: lamp.", game.handle("take lamp")
assert_equal "There is no lamp here.", game.handle("take lamp")

This separation of logic and I/O is the single most useful habit for building interactive programs. See Testing with Minitest.

Ideas to extend it

  • Add use, examine and open verbs, or items with descriptions (item "lamp", "A brass lamp").
  • Give the Game a move counter and print a score when the player wins.
  • Add save and load commands that dump the state with JSON.
  • Add locked doors that consume the key, using @inventory.delete(door.needs).
  • Add a Hash#fetch-based synonym table, so grab and pick both mean take.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does instance_eval do in the World.build DSL?

    instance_eval changes the receiver (self) inside the block. That is why a bare room or door call reaches the builder's methods.
  2. 2. What happens when case/in finds no matching pattern and there is no else or catch-all?

    Unlike case/when, case/in raises NoMatchingPatternError. Put a catch-all such as in [verb, *] last.
  3. 3. Why does the pattern in [verb, *] have to come after the other patterns?

    The first matching pattern wins, so specific patterns must precede the catch-all.
  4. 4. Why does Game#handle return strings instead of printing?

    Separating logic from I/O makes the engine easy to test and lets the same engine run in a terminal, a web page or a script.
  5. 5. Why is door a better DSL method name than exit?

    Reusing a name that Kernel already defines is confusing and risky. Choose names that do not collide.

Summary

  • Separate the engine (rooms, game state, rules) from the story (data written in a DSL).
  • instance_eval makes a block call methods on another object, which is the basis of block-style DSLs. Avoid names that clash with Kernel methods such as exit, open and puts.
  • Validate a built world once, before play, so mistakes surface early and with a clear message.
  • case/in matches arrays by shape with alternatives (|), bindings (=> name) and splats (*rest); the first match wins, and an unmatched value raises NoMatchingPatternError.
  • Keep game logic returning strings, and let one small loop do the I/O. A state symbol (:playing, :won, :quit) is a simple state machine.

Next: Project: A Threaded Job Runner