Skip to content
Tutorials Center
My learning

Topics

Lesson 126 of 134 ยท Projects

Project: A Text Adventure Engine

Build a text adventure in Kotlin - describe the world with a type-safe DSL, parse sealed commands, move through a pure state machine and play it with scripted input in your browser.

Text adventures are among the oldest computer games: you read a description, type go north or take lamp, and the story answers. They are also a wonderful programming exercise, because a small engine already feels like a real program. You need a model of the world, a way to understand the player's words, and rules for what happens next.

This project builds an engine (reusable code) and a game (a small world described with a DSL). You will use enum classes, sealed interfaces, type-safe builders, data classes and collections. It follows the inventory project and is followed by the coroutine pipeline.

The design: a state machine

The central idea is a state machine: the game has a state (where is the player, what do they carry, what lies in each room), and each command moves it to a new state. The key design choice is to write the rule as a pure function:

TEXT
step(world, state, command) -> (new state, message)

A pure function does not print, read input or change anything outside. It takes a state and returns a new one. That makes the engine easy to test (feed it commands, check the results), easy to replay, and easy to reuse with a different front end such as a web page.

The pieces:

  1. World, built with a DSL: rooms, exits, items. It never changes during play.
  2. GameState, an immutable data class: it changes by copy().
  3. Command, a sealed interface produced by a parser.
  4. step, the rules.
  5. The loop in main: read a line, parse, step, print.

Step 1: describing the world with a DSL

We could build rooms with plain constructors, but a world is mostly data with structure: rooms containing exits and items. A type-safe builder (see type-safe builders and DSLs) makes the world look like what it is.

Kotlin Step 1 - a world 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 readln()), it gets the next line from this box.

Some things happen here that deserve explanation:

  • @DslMarker limits implicit receivers. Inside room("porch") { ... } you can call item(...) and exit(...), but not room(...) of the outer builder by accident. Step 4 shows the exact error.
  • Validation at build time. build() checks that every exit leads to an existing room. A typo in a room name is reported while the world is built, not in the middle of a game when the player walks through a door. This "fail early" habit is worth copying.
  • requires lets an exit need an item. The cellar stairs need a key. Locks are data, not code, so a designer can add them without touching the engine.
  • entries is the modern replacement of values() for enums (enum classes).
  • The builder classes keep mutable collections private and hand out immutable copies. After build() the world is read-only.

Step 2: understanding the player

The player types words. We turn them into a sealed Command, so that every later piece works with types and not strings. Synonyms are handled once, here: get, grab and take are all Take.

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

Direction.parse(verb)?.let { return Command.Go(it) } is a compact pattern: if the first word is a direction, return right away; otherwise carry on. The return inside the lambda is allowed because let is inline (inline functions).

Even an unrecognized input becomes a Command (Unknown), carrying a hint for the player. The parser never throws on bad input, since typos are normal in a game. Because everything is a value, the rules in the next step need no try/catch.

Step 3: the rules and the game loop

Here is the whole engine. step is a pure function over the immutable GameState. main is a thin shell around it.

Kotlin Step 3 - the complete 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 readln()), it gets the next line from this box.

Read the transcript from top to bottom and match each line to the rules:

  • go down before getting the key is refused because the exit has requires = "key".
  • Entering the cellar without the lantern describes darkness only if you did not pick it up. In our scripted run we carry the lantern, so we see the crown.
  • Taking the crown sets finished, and the loop ends. The rest of the input is never read.
  • The last two commands, fly and quit, are never read because the crown ends the game first. Move fly earlier in the input and you get the hint from the parser.

Why is this style pleasant? Look at Command.Take. It builds a new state with copy, and roomItems + (room.id to (here - command.item)) creates a new map with one entry replaced. Nothing is mutated, so the old state is still intact. That gives you undo almost for free: keep the previous states in a list and pop one.

The Pair return value

Returning Pair<GameState, String> is simple, and state to "message" reads nicely. For a larger engine, a small data class Turn(state, message) documents itself better (pairs, triples and destructuring).

To test the engine, you do not need stdin at all: call step with a list of commands in a loop and compare the final state. Pure functions are the easiest code to test.

Step 4: what @DslMarker protects you from

Without @DslMarker, a nested lambda can call functions of every outer builder. In our world, that would let you write room("x") { ... } inside another room, quietly adding a room to the wrong place. The marker makes that a compile error. This example fails on purpose.

Kotlin A room inside a room (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 readln()), it gets the next line from this box.

The compiler complains that room cannot be called in this context by an implicit receiver, and suggests the explicit one if you really mean it. Remove the nested room and the program compiles and prints the structure. If you ever truly need the outer builder, write [email protected](...) explicitly, which makes the intent visible.

Ideas to extend the game

  1. More verbs: use key, open chest, give. Each is a new sealed subtype, and the compiler will point to every when that needs updating.
  2. Characters: a troll who blocks a door until you drop the lantern. Store characters in the world and let step consult them.
  3. Score and turn limit: add fields to GameState, and finish with finished = moves > 50.
  4. Save and load: serialize GameState as lines of text (see the to-do project).
  5. Replay: store the list of commands. Since step is pure, commands.fold(initialState) { s, c -> step(world, s, c).first } rebuilds any moment of the game.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is the main advantage of writing the rules as a pure function step(world, state, command)?

    A pure function depends only on its arguments and returns a result, so tests can simply call it with commands and check the states.
  2. 2. What does @DslMarker do in the world builder?

    With the marker, an inner lambda sees only its own receiver implicitly, so a nested room(...) call becomes a compile error.
  3. 3. Why does WorldBuilder.build() check that every exit leads to an existing room?

    Validating data when it is built fails early, with a clear message, instead of crashing when the player walks through the door.
  4. 4. How does state.copy(inventory = state.inventory + command.item) treat the old state?

    copy creates a new object. Because nothing is mutated, earlier states stay valid, which makes undo and replay easy.
  5. 5. Why does the parser return Command.Unknown instead of throwing an exception for a typo?

    Mistyped words happen all the time in a game. Treating them as ordinary data keeps the control flow simple.

Summary

  • A game is a state machine: immutable state plus a pure step(state, command) function.
  • A type-safe DSL with @DslMarker makes data such as a world readable, and validation in build() fails early.
  • Parse text into a sealed Command once; handle synonyms and mistakes in the parser, not in the rules.
  • Update immutable state with copy() and the +/- operators on collections.
  • Keep input and output in a thin loop around the pure engine, so the engine can be tested and reused.

Next: Project: A Coroutine Pipeline