Introduction
Interactive fiction is a fun way to learn to separate data from logic. The Game class knows how to move, take, drop, examine and use things, but the story — rooms, locks, puzzles — lives entirely in build_world(). Replace that function and you have a different game.
Problem statement
Objectives
- Represent a world as data with nested maps and vectors
- Write a tolerant command parser (verbs, multi-word objects, abbreviations)
- Track game state in a class
- Use std::set to remember one-time events
Features
- Rooms with descriptions, items and named exits
- Locked exits that need a key item
- Puzzles: using an item in a room reveals a hidden item
- Move counter and a win condition
Concepts demonstrated
- Data-driven design
- State machines
- Command parsing
- std::map / std::set
- Encapsulation
System architecture
World is pure data: a map of room ids to Room structs (title, description, exits by direction, items), plus uses (item + room → revealed item) and the hidden items themselves. Game holds the world, the current room, the inventory and a set of puzzle steps already done. command dispatches each verb to a member function. go checks Exit::needs against the inventory. main lower-cases the verb and joins the remaining words into the object name, so take rusty key works.
Folder structure
Complete source code
Makefile
What each file does
- src/main.cpp
- World data types,
build_world(the story), theGameengine with its verbs, and the input loop. - Makefile
- Build automation:
makebuilds./app,make testruns the sample session and compares it with the expected output,make cleanremoves build files.
How to run it
Build
Run
Test against the expected output
Expected output
Generated by running the project with tests/sample-input.txt. Your output should match tests/expected-output.txt exactly.
go north take straw bed take spoon examine spoon use spoon take rusty key inventory n dance take torch go west go north e e use torch use torch take gate key w w drop spoon n
Testing
- Compare
./app < tests/sample-input.txtwithtests/expected-output.txt: the scripted walkthrough escapes in 20 moves. - The cell door stays locked until the spoon reveals the rusty key; the gate needs the key revealed by the torch.
take straw bedfails because it isn't portable; using the torch a second time does nothing.
Common errors
"take rusty key" says there is no rusty
Join all remaining words into the object name instead of reading only one word.
Items vanish after dropping
Push the item into the current room's vector before erasing it from the inventory.
Possible improvements
- Load the world from a text file
- Add NPCs with simple dialogue
- Add save/load of the game state
Additional challenges
- 1Write a second world without changing the engine.
- 2Add a score for discovering secrets.
- 3Add a
mapcommand that prints visited rooms.
Built and tested it yourself? Mark it to update your dashboard.