Game Design & Development · Build a Classic

Text Adventure Builder: Make Your Own Zork

Parsers Rooms as a graph Inventory and flags Breadth-first search Spin-offs

There are no pictures and no buttons. The game describes a place, and you type what you want to do: take the lamp, go north, unlock door with key. The computer has to understand you, remember what you carry and what you have already done, and decide whether a door opens. That is a world model, and it is the same idea behind every game save file. In this lesson you build a whole text adventure in about 100 lines of JavaScript, check your map with a real search algorithm, and then write your own world: a haunted school, a space station, a voyage from the book of Acts, or somewhere nobody has explored yet.

1 · Why this game works

The site already has a choose-your-own-adventure tutorial, where you click one of two or three buttons. A text adventure is different: you can type anything, so the game has to keep a model of its whole world and work out what your words mean. Three ideas make that possible.

  • The world is a graph. Each room is a point, and each exit is a line to another room: { north: "hall" }. Moving is just following a line. Nothing about a map needs pictures.
  • A parser turns words into a command. It lowercases what you typed, drops little words like the and a, and splits the rest into a verb and a noun. A table of synonyms means get, take and grab all do the same thing.
  • State plus conditions makes puzzles. The game remembers which room you are in, your inventory, and a set of flags (door unlocked, lamp lit). An exit or action can need an item or a flag, and an action can set a flag. A locked door is just an exit with a condition.

The program is the same loop for every command you type:

…then wait for the next command. The whole game is a state machine: it is always in exactly one state (this room, these items, these flags), each command moves it to another state, and winning means reaching a particular state.

TRY IT FIRST

2 · The Adventure Lab: play it, then break it

This is the finished engine. Every room, exit, item, lock and ending lives in the config on the left. Pick a preset, press Run my game, and play. Type into the box under the story and press Enter. The ↑ key brings back your last command, and the Look, Inventory and Help buttons are there for when you don't know what to type. Then change something small in the config and run it again.

Reading the config. It is JSON: names in quotes, numbers without, lists in [ ], objects in { }. If something is wrong, the message under the config says what and where. Things to try:
  • "rooms" is the map. Each room has a "name", a "text" and "exits". An exit can be a room id ("north": "hallway") or a locked exit: { "to": "office", "needs": "keys", "locked": "The door is locked." }. Exit names can be any word, so "aft", "inland" and "sail" work too.
  • A need is an item id (you must be carrying it) or a flag name (it must be set). Put ! in front to mean "not": "!doors_open".
  • "items" are the things in the world. "words" lists other names the player might type. "fixed": true means scenery that can't be carried.
  • Each of the "actions" has a "verb", usually a "noun", maybe a "room", and "needs". When it works it shows "text" and can "set" flags, "give" or "remove" items, "place" an item in the room, or "goto" another room. "fail" is what it says when a need is missing. "once": true means it only happens one time.
  • A room with "dark" needs light: "dark": ["flashlight", "flashlight_on"]. "extra" lines appear only "if" their condition is true, so a room's description can change as the story moves on.
  • "win" says what winning means: a "room", some "needs", or both. Add "seed": 7 and the random background sounds repeat the same way every time.

The Paul's Voyage preset follows the shipwreck in Acts 27 and Acts 28. Every scene quotes or retells the text and gives the verse, so you can check it as you play.

BUILD IT

3 · Build the engine yourself in seven steps

The Lab above has extras (darkness, one-time actions, endings, background sounds). To understand it, first build the core: a four-room house with a locked door. Make a file called adventure.html, paste the page skeleton below, and then add each step inside its <script> tag in order. After every step, save, reload, and try it. Don't move on until the checkpoint is true.

Page skeleton

Step 1 · Draw the map as data

Before any logic, write down what the world is. Each room lists its exits, and each exit names another room, so the rooms and exits together form a graph. The locked door is an exit with a condition: it needs the flag "unlocked". The one thing to do in this world, unlocking the door, is data too.

Checkpoint: Open the browser console (F12) and type GAME.rooms.hall.exits. It should show {north: 'library', up: 'attic'}.

Step 2 · Track the state

The state is everything that changes while you play: where you are, what you carry, and which flags are set. Notice how small it is. Saving the game would only mean saving these few variables.

Step 3 · Small helpers

say() adds a line to the story, look() describes the current room, and has() answers one question that the whole game depends on: is this need met? A need is met if you carry an item with that id or a flag with that name is true.

Step 4 · The parser

This is the part that makes typing feel like talking. Lowercase the input and remove punctuation, split it into words, and throw away the, a and an. The first word is the verb and the rest is the noun. Then two shortcuts: the synonym table turns grab into take and n into north, and a direction on its own means "go that way".

Checkpoint: In the console, parse("Grab the brass key!") should give {verb: 'take', noun: 'brass key'}, and parse("n") should give {verb: 'go', noun: 'north'}. Try a few of your own. What does parse("") do?

Step 5 · Moving between rooms

An open exit is just a room name, so you move straight there. A locked exit is an object, so check its condition with has() first, and if the condition fails, show the locked message. That message is your chance to give a clue.

Checkpoint: In the console, go("up") should describe the attic, go("down") brings you back, and go("north"); go("north") should stop at the locked door.

Step 6 · Items and actions

Taking an item moves its id from the room's list to your inventory, and dropping moves it back. findItem() lets the player type just the last word, so key finds the brass key. act() looks through the data for an action with the right verb, noun and room, checks its condition, and sets its flag. Every puzzle in a text adventure is this one pattern.

Why actions are data. You could write if (verb === "unlock" && noun === "door") in the code, but then every new puzzle means new code. With actions in the data, a new puzzle is a new line in GAME.actions. The Lab works the same way, and so do real engines.

Step 7 · Run a command, and win

run() is the whole command loop from the diagram: echo what was typed, parse it, look it up, change the state, describe it. After every command, check for the win state: here, standing in the garden. Then connect the Enter key.

Checkpoint: Win the game by typing: read note, up, take key, down, north, unlock door, north. Then try nonsense (dance), a missing item (take sandwich) and the locked door without the key. Every one should get a sensible reply, not an error.
Show the complete program

Your adventure is a state machine (one room at a time, with rules for moving between them), and it can save progress. Here is how other engines name those two ideas:

THINK LIKE A COMPUTER SCIENTIST

4 · Check your map with an algorithm

Big text adventures have dozens of rooms and hundreds of exits, and it is easy to make a mistake: an exit that points to a room you misspelled, a room nobody can get to, a key in a place the player can never reach, or a puzzle that can't be solved. Playtesting finds some of these. An algorithm finds all of them, and the one we use is breadth-first search (BFS).

Breadth-first search in plain words

Think of dropping a pebble into a pond. The ripple reaches everything one step away, then everything two steps away, then three. BFS explores a map the same way, with a to-do list called a queue:

  1. Put the start room in the queue and mark it as seen.
  2. Take the room at the front of the queue.
  3. For each exit, if the room it leads to hasn't been seen, mark it seen and add it to the back of the queue.
  4. Repeat until the queue is empty. Any room never marked as seen can't be reached.

Because rooms are taken from the front and added at the back, BFS always finishes every room one step away before it looks at any room two steps away. So the first time it reaches a room, it has found the shortest route there. Here it is in JavaScript, using the map from step 1:

function reachable(rooms, start) {
  const seen = new Set([start]);
  const queue = [start];
  while (queue.length) {
    const here = queue.shift();                  // take from the front
    for (const exit of Object.values(rooms[here].exits)) {
      const next = typeof exit === "string" ? exit : exit.to;
      if (rooms[next] && !seen.has(next)) {
        seen.add(next);
        queue.push(next);                        // add to the back
      }
    }
  }
  return seen;                                   // every room you can get to
}

The bigger trick: search over situations, not rooms

A room list alone can't tell whether the game can be won. The principal's office in the Haunted School is "reachable" on the map, but only once you carry the keys, and the keys are in a basement you can only search with a working flashlight. So the checker runs BFS over situations: where you are, what you carry, which flags are set. Every command you could type (go somewhere, take something, do an action) is a line from one situation to another. If BFS can reach a situation that counts as a win, the game can be won, and the path it followed is the shortest walkthrough. The checker also runs the search backwards from every win to find dead ends: situations where the player can no longer win, however well they play.

The checker is honest about what it skips: it never drops items (dropping rarely solves anything), it ignores random background sounds, and it stops if a world has more than 20,000 situations. Real studios run tools like this on every build, because a puzzle that can't be solved is a bug players can't report until they're stuck.

YOUR TWIST

5 · Design your spin-off

A good spin-off keeps the structure (rooms joined by exits, items that open locks, flags that change the world, a winning state) and changes the world. Fill in the last column and you will notice that most of the work is writing.

Part of the gameHaunted SchoolSpace StationPaul's VoyageYour spin-off
The worldAn empty school at nightAn orbiting station with a broken antennaA grain ship in a storm, then Malta (Acts 27–28)?
Rooms778?
Win stateOutside, holding your projectThe flag called is setReaching Rome?
A lockOffice door needs the keysControl room needs the keycardThe shore needs a plank?
A flagdoors_opensuit_onanchored?
A clue before the lockThe custodian's noteThe commander's tabletThe centurion's order (27:44)?

Not sure where to start? Roll the idea dice.

Setting…
Goal (your win state)…
The twist…
Roll until something makes you curious, then put it in your design sheet below.

Twists that change the rules, not just the words

  • A light that runs out: the lamp has 40 turns of oil. Now every move costs something.
  • A character who talks: ask guard about key. The answer depends on your flags.
  • A carrying limit: only three items at once, so the player has to plan.
  • A room that changes: after an event, the flooded cellar drains and a new exit opens.
  • Two items that look alike: a brass key and an iron key. The parser has to ask "Which key do you mean?"
  • Points for discoveries: a score for every new flag, so exploring is rewarded.

Design sheet

When the sheet is done, put it in the Lab config (or into the GAME object of your own adventure.html), run it, and then run the map checker until it finds nothing wrong.

YOUR ART

6 · Art guide: what you need to draw

A text adventure works with no pictures at all, and the words always come first. But a picture for each room helps players remember the map, and an icon for each item makes the inventory easy to read. Make a list before you open a drawing tool. Draw every Must first (the game can ship with only those), then Should, then Bonus.

Title screen Must

1 picture · The game name over the first room. Leave a quiet area for the words.

Room illustrations Must

1 per room · Show what the text describes, including every exit, so the picture and the words agree.

Item icons Must

1 per item you can carry · Transparent background. They sit in a row as the inventory, so they must read clearly when small.

Win screen Must

1 picture · The reward for solving everything. Make it feel like arriving.

The map Should

1 picture · Boxes for rooms and lines for exits, the same graph as your data. Leave locked doors drawn as locked.

Character portraits Should

1 per character · Anyone the player can talk to or watch. One clear detail each.

Other endings Bonus

1 per extra ending · Only if your game has ways to lose. Warn the player before they happen.

Story frame Bonus

1 border · A frame around the text (a ship's log, a school notebook, a computer screen) that sets the mood.

How many pictures is your game?

Use the numbers from your design sheet.

  • Pick a palette first. Five to eight colours written down as hex codes, and every picture uses only those. This does the most to make student art look like one game.
  • One style, one viewpoint. Pixel art, ink or flat shapes: pick one. Draw every room from the doorway you usually enter by, so north is always the far wall.
  • The words win. If the picture shows a door the text doesn't mention, players will type open door and get confused. Change the picture or the text so they match.
  • Draw big, show small. Check each icon at half size. If you can't tell what it is, simplify it.
  • Only your own art. If you use something you didn't make, write down who made it and the license.
  • Real people, real places. If your story is about real history or scripture, draw people with respect, and draw what the source says rather than what a movie showed.

Put each picture's file name in the data next to the thing it shows, so the logic stays untouched: "art": "art/hallway.png" on a room, "icon": "art/key.png" on an item. The Lab ignores these fields, so they won't break anything. In your own adventure.html, show the room's picture inside look():

<img id="scene" alt="" width="480" height="270">

const pic = document.getElementById("scene");
pic.src = room.art;
pic.alt = room.name;      // describe it for screen readers

Where to draw: Web Studio Draw mode, or Pixel Art & Sprites. Paper is fine too: sketch the map first, because it is also your level design.

LEVEL UP

7 · Challenges

Pick one or two. They get harder as you go down the list.

  1. Save and load. Add save and load verbs that put here, inventory, flags and every room's item list into localStorage as one JSON string. The Menus, Saving & Shipping lesson explains how. Why do the room lists need saving too?
  2. Two-word nouns. Add an iron key next to the brass key. take brass key must take the right one, and take key should ask "Which key do you mean?" instead of guessing.
  3. A scoring system. Give points the first time each flag is set, and show "Score: 25 of 100" after every command. A score verb that lists what is still missing makes a good hint system.
  4. A light that runs out. The flashlight has 30 turns of battery. Count down every command while it is on, warn at 5, and make the dark rooms dark again at 0. How do you keep this from making the game unwinnable?
  5. Characters who talk. Add ask <person> about <topic>. Give each character a list of topics, and let some answers depend on flags, so the custodian only mentions the keys after you have seen the locked office.
  6. An auto-drawn map. Use the BFS from section 4 to give every room a distance from the start, then place rooms on a grid using their exit directions (north is one row up) and draw them on a <canvas>. Only draw rooms the player has visited.

8 · Where it came from, and designing with care

The first text adventure was Colossal Cave Adventure. Will Crowther, a programmer and caver, wrote it around 1976, basing its cave on part of Kentucky's Mammoth Cave system that he had explored. In 1977 Don Woods at Stanford found it, got Crowther's permission, and greatly expanded it. Players typed two-word commands like GET LAMP and GO NORTH, which is exactly the verb-and-noun parser you just built.

Between 1977 and 1979 a group of students at MIT wrote Zork, inspired by Adventure. Its parser understood whole sentences with more than one noun, such as put the coin in the box. Some of its authors went on to found the company Infocom, which sold Zork for home computers in the early 1980s. Every adventure game since, including the ones with pictures, comes from this family.

Those games were also famous for puzzles that were unfair. When you design yours:

  • Clue before lock. The player should be able to learn what a lock needs before (or at) the lock: a note, a sign, a character. The map checker shows which order the player meets things in, so read its walkthrough and ask "Would I know to do that?"
  • No dead ends without warning. If the player can make the game unwinnable (eat the only bread, drop the key down a well), warn them first or give them a way back. The checker's dead-end search exists for exactly this.
  • No "guess the verb". If the answer is press button, then push button and use button should work too. List the special verbs in help.
  • Respectful settings. A spooky school is fun when the ghost turns out to be the boiler. Don't make real people or real groups into monsters, and don't set a game in somewhere real to make fun of it.
  • Scripture and history. If you retell a true story, as Paul's Voyage does with Acts 27–28, keep the events in the text and give the verse for each scene. Your puzzles decide when the player sees each event, never what happened. Don't make up miracles, and don't turn prayer into a magic button.

9 · Show what you built

Hand in your adventure.html (or the file from the Lab), your design sheet and a screenshot of the map checker's report. Your teacher will look for:

CriterionMeets the goal when…
It worksYou can start it, play it, and win without errors. Nonsense input gets a friendly reply.
Data-drivenRooms, exits, items and actions live in one data object, and the code doesn't hard-code any of them.
A real parserArticles are ignored, at least three synonyms work, and the player can type the last word of a two-word item.
State and conditionsAt least one lock that needs an item and one that needs a flag, and the world changes when a flag is set.
Checked with BFSThe map checker finds no broken exits, no unreachable rooms, no lost items, no dead ends, and a win.
Fair and carefulEvery lock has a clue first, special verbs are listed in help, and the setting is treated with respect.

Next: plan your whole build in Game Jam Week, see how A* improves on BFS in Rescue Grid: The A* Mission, or build the other classics in Trail Game Builder, Lemonade Tycoon Builder and Roguelike Builder.