Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 57 ยท Real-world Haskell

Project: Text Adventure Engine

Build a text adventure in Haskell: the world as data, a command parser, a pure step function and a thin IO loop, with a runnable JavaScript model.

Text adventures ("You are in a dark room. Exits: north, east.") are a wonderful Haskell project because they are all about state transitions: a world, a command, and a new world. Games are usually written as tangled mutable objects; in Haskell the same idea becomes a single pure function, step :: Command -> World -> (World, String), wrapped in a tiny IO loop.

You will model rooms, items and the player as plain data, parse typed text into a Command, and write the rules as pure code. The payoff is that you can play whole games inside tests by feeding a list of lines to the engine and checking the output, with no terminal involved. This lesson uses algebraic data types, records, pattern matching and the basics of IO.

Real Haskell is read-only on this site. The runnable blocks are JavaScript stand-ins with the same design, so you can play with the engine and then write the Haskell yourself.

The engine in four pieces

World Rooms, items and the player as data.
Parser Text in, Command out.
step Pure rules from Command and World to World.
IO loop Read a line, print the reply, repeat.

Everything except the loop is pure.

1 / 2

Step 1: The world as data

Our little game has four rooms, two items and a puzzle. The lamp is in the library; the cellar is too dark to enter without it; the key is in the cellar; and the garden door needs the key. Reaching the garden wins.

HASKELL
data Room = Hall | Library | Cellar | Garden
  deriving (Show, Eq, Ord)

data Direction = North | South | East | West
  deriving (Show, Eq)

data Item = Lamp | Key
  deriving (Show, Eq)

data World = World
  { location  :: Room
  , inventory :: [Item]
  , floorItems :: Map.Map Room [Item]
  , moves     :: Int
  } deriving Show

Room derives Ord so it can be a key of a Data.Map (imported as qualified Data.Map as Map, see Essential Libraries). The map layout of the house is a function, not a data structure, which keeps it easy to read and extend:

HASKELL
exits :: Room -> Direction -> Maybe Room
exits Hall    East  = Just Library
exits Hall    South = Just Cellar
exits Hall    North = Just Garden
exits Library West  = Just Hall
exits Cellar  North = Just Hall
exits _       _     = Nothing

The last clause is the default: every other combination is "no exit". The starting world is a plain value:

HASKELL
initialWorld :: World
initialWorld = World
  { location   = Hall
  , inventory  = []
  , floorItems = Map.fromList [(Library, [Lamp]), (Cellar, [Key])]
  , moves      = 0
  }

Step 2: Commands and the parser

Everything a player can type becomes a constructor. Input that makes no sense becomes Unknown, so parsing is a total function and never crashes:

HASKELL
data Command
  = Go Direction
  | Take Item
  | Drop Item
  | Look
  | Inventory
  | Quit
  | Unknown String
  deriving (Show, Eq)

parseCommand :: String -> Command
parseCommand input = case words (map toLower input) of
  ["look"]              -> Look
  ["l"]                 -> Look
  ["inventory"]         -> Inventory
  ["i"]                 -> Inventory
  ["quit"]              -> Quit
  ["go", d]             -> maybe (Unknown input) Go (parseDirection d)
  [d] | Just dir <- parseDirection d -> Go dir
  ["take", name]        -> maybe (Unknown input) Take (parseItem name)
  ["drop", name]        -> maybe (Unknown input) Drop (parseItem name)
  _                     -> Unknown input

parseDirection :: String -> Maybe Direction
parseDirection "north" = Just North
parseDirection "n"     = Just North
parseDirection "south" = Just South
parseDirection "s"     = Just South
parseDirection "east"  = Just East
parseDirection "e"     = Just East
parseDirection "west"  = Just West
parseDirection "w"     = Just West
parseDirection _       = Nothing

parseItem :: String -> Maybe Item
parseItem "lamp" = Just Lamp
parseItem "key"  = Just Key
parseItem _      = Nothing

toLower comes from Data.Char. The case alternative [d] | Just dir <- parseDirection d -> Go dir uses a pattern guard: it matches a one-word command and then checks that the word is a direction, so typing just n works. Splitting with words ignores extra spaces for free.

JS The command parser in JavaScript

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Step 3: The pure step function

The rules of the game are one function. It never prints; it returns the new world and the text to show. Each command gets its own small helper, which keeps the code readable:

HASKELL
step :: Command -> World -> (World, String)
step Look world        = (world, describe world)
step Inventory world   = (world, showInventory (inventory world))
step (Go dir) world    = move dir world
step (Take item) world = takeItem item world
step (Drop item) world = dropItem item world
step Quit world        = (world, "Goodbye.")
step (Unknown _) world = (world, "I don't understand that.")

Movement carries the puzzle rules. exits returns a Maybe, and two guards check the requirements:

HASKELL
move :: Direction -> World -> (World, String)
move dir world = case exits (location world) dir of
  Nothing -> (world, "You can't go that way.")
  Just target
    | target == Cellar && Lamp `notElem` inventory world ->
        (world, "It is too dark to go down without a lamp.")
    | target == Garden && Key `notElem` inventory world ->
        (world, "The garden door is locked.")
    | otherwise ->
        let moved = world { location = target, moves = moves world + 1 }
        in (moved, describe moved)

describe :: World -> String
describe world = case location world of
  Garden  -> "You step into the sunny garden. You win in "
             ++ show (moves world) ++ " moves!"
  Hall    -> "The hall. Doors lead north, east and south." ++ here
  Library -> "A quiet library. The hall is to the west." ++ here
  Cellar  -> "A damp cellar. A staircase leads north." ++ here
  where
    here = case Map.findWithDefault [] (location world) (floorItems world) of
      [] -> ""
      xs -> " You see: " ++ unwords (map show xs) ++ "."

Picking up and dropping items shuffles an item between two places. Using Map.adjust and filter returns new values; nothing is mutated:

HASKELL
takeItem :: Item -> World -> (World, String)
takeItem item world
  | item `elem` here =
      ( world { inventory  = item : inventory world
              , floorItems = Map.adjust (filter (/= item)) (location world) (floorItems world) }
      , "Taken: " ++ show item ++ "." )
  | otherwise = (world, "There is no " ++ show item ++ " here.")
  where here = Map.findWithDefault [] (location world) (floorItems world)

dropItem :: Item -> World -> (World, String)
dropItem item world
  | item `elem` inventory world =
      ( world { inventory  = filter (/= item) (inventory world)
              , floorItems = Map.insertWith (++) (location world) [item] (floorItems world) }
      , "Dropped: " ++ show item ++ "." )
  | otherwise = (world, "You don't have the " ++ show item ++ ".")

showInventory :: [Item] -> String
showInventory [] = "You carry nothing."
showInventory xs = "You carry: " ++ unwords (map show xs) ++ "."

Step 4: Play whole games without IO

Because step is pure, a whole game is just a fold. mapAccumL from Data.List threads the world through a list of input lines and collects every reply:

HASKELL
import Data.List (mapAccumL)

playScript :: [String] -> [String]
playScript inputLines = snd (mapAccumL turn initialWorld inputLines)
  where
    turn world line = step (parseCommand line) world

Here turn has exactly the type acc -> x -> (acc, y) that mapAccumL wants, so the plumbing disappears. A test can now assert on a complete winning playthrough, or that going down without the lamp is refused, in a few lines.

JS The engine and a scripted playthrough

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Step 5: The thin IO loop

The only impure code reads a line, asks step what happens, prints the answer and repeats. isEOF makes the program quit cleanly when input ends (for example when it is piped from a file). See IO Basics for the pieces.

HASKELL
import System.IO

main :: IO ()
main = do
  hSetBuffering stdout NoBuffering
  putStrLn (describe initialWorld)
  loop initialWorld

loop :: World -> IO ()
loop world
  | location world == Garden = putStrLn "Thanks for playing!"
  | otherwise = do
      putStr "> "
      eof <- isEOF
      if eof
        then putStrLn "\nBye."
        else do
          line <- getLine
          case parseCommand line of
            Quit -> putStrLn "Goodbye."
            command -> do
              let (world', reply) = step command world
              putStrLn reply
              loop world'

The loop passes the new world to the next iteration; there is no variable to update. Winning is detected by looking at the state, not by a flag that some code might forget to set.

Making it your own

  • Add a use command, a locked chest, or a monster with hit points in World.
  • Describe rooms with a record (name, text, exits) stored in a Map Room RoomInfo, so adding a room needs no new function.
  • Save and load games by deriving Read and Show for World, or encode it as JSON (see JSON and Web Services).
  • Turn the loop into StateT World IO to avoid passing the world manually (see State, Reader, Writer and Monad Transformers).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the type of the game's rules function?

    step is pure: it returns the new world and the message to print, leaving the printing to the IO loop.
  2. 2. Why can the whole game be tested without a terminal?

    Pure functions depend only on their inputs, so a script of lines can be folded through step with mapAccumL.
  3. 3. What does the pattern guard [d] | Just dir <- parseDirection d do?

    The pattern matches one word, then the guard succeeds only if parseDirection returns Just.
  4. 4. How does the game avoid mutating the world when you take an item?

    world { inventory = ... } creates a new record; the old world is untouched and the loop continues with the new one.

Summary

  • Model rooms, items, directions and commands as algebraic data types; use records for the world.
  • Parse text into a Command with a total function; unknown input becomes Unknown.
  • Write all rules as one pure step :: Command -> World -> (World, String).
  • mapAccumL runs a scripted playthrough, which makes testing easy.
  • The IO loop only reads, prints and recurses with the new world.

Next: Practice: Functions, Lists and Recursion.