Skip to content
Tutorials Center
My learning

Topics

Lesson 38 of 40 ยท Projects and Practice

Project: A Text Adventure Game

Build a text adventure in Prolog. Model rooms and items as facts, keep the game state in the dynamic database, write commands as predicates, and parse typed input with a DCG.

Text adventures are a classic Prolog project, and for good reason: the world is a set of facts, the rules of the game are rules, and the player's state is exactly what the dynamic database is for. In this project you build a small game with rooms, items, a locked door and a treasure, then add a command parser so the player can type ordinary words.

Prolog is not available on this site, so the program runs on the stand-in interpreter (a Python program that supports facts, rules, the cut, negation, forall/2, assertz/1 and retract/1). The Prolog is ordinary SWI-Prolog; only the interactive loop is shown read-only, because a browser example cannot read a keyboard.

Design: static world, dynamic state

Split the program into two kinds of facts:

  • Static facts that never change: the map (path/3) and room descriptions (describe/2).
  • Dynamic facts that change as you play: where the player is (here/1), where each item lies (at/2) and what the player holds (holding/1).
PROLOG
:- dynamic here/1, at/2, holding/1.

here(cellar).
at(lamp, cellar).  at(key, library).  at(treasure, tower).

path(cellar, north, hall).    path(hall, south, cellar).
path(hall, east, library).    path(library, west, hall).
path(hall, up, tower).        path(tower, down, hall).

describe(cellar,  'A damp cellar. Stairs lead north.').
describe(hall,    'A great hall. Doors east, a spiral stair up.').
describe(library, 'Dusty shelves line the walls.').
describe(tower,   'A cold tower room at the top.').
flowchart LR
  cellar -- north --> hall
  hall -- east --> library
  hall -- "up (locked)" --> tower

The map. The tower door opens only when the player holds the key.

Actions are predicates

Each command is a predicate that checks its preconditions, changes the state with retract and assertz, and prints a message.

PROLOG
look :-
    here(P), describe(P, D), write(D), nl,
    forall(at(I, P),       ( write('  You see: '), write(I), nl )),
    forall(path(P, Dir, _), ( write('  Exit: '), write(Dir), nl )).

go(Dir) :- here(P), path(P, Dir, Q), blocked(Q), !,
           write('The door is locked.'), nl.
go(Dir) :- here(P), path(P, Dir, Q), !,
           retract(here(P)), assertz(here(Q)), look.
go(_)   :- write('You cannot go that way.'), nl.

take(I) :- here(P), at(I, P), !,
           retract(at(I, P)), assertz(holding(I)),
           write('Taken: '), write(I), nl, check_win(I).
take(_) :- write('Nothing like that here.'), nl.

blocked(tower) :- \+ holding(key).

check_win(treasure) :- !, write('You found the treasure. You win!'), nl.
check_win(_).

inventory :-
    write('You carry:'), nl,
    forall(holding(I), ( write('  '), write(I), nl )).

Several patterns appear here, all from earlier lessons:

  • Ordered clauses with cuts act as a case analysis for go/1: locked, allowed, or no exit. The first two clauses are red cuts that rely on the order. See The Cut.
  • Failure-driven output with forall/2 lists every item and exit without writing a loop. See Negation, If-Then-Else and Loops.
  • blocked/1 uses negation as failure: the tower is blocked as long as the player does not hold the key.
  • State changes use retract/1 followed by assertz/1 so the player is in exactly one place. See The Dynamic Database.

The next demo plays a scripted walkthrough through the stand-in interpreter. The run/1 predicate takes a list of commands, prints each one and calls it.

Python A scripted playthrough (Python stand-in interpreter)

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

Notice that go(up) first prints "The door is locked." and succeeds the second time, after take(key). Nothing in go/1 mentions the key: the rule in blocked/1 carries that knowledge, so you can add a locked door elsewhere with one more clause.

The interactive loop

A real game reads commands from the player. The usual driver combines repeat with read/1, so each typed term (ending with a full stop) is called as a goal:

PROLOG
play :-
    look,
    repeat,
    write('> '), read(Command),
    (   Command == quit
    ->  !
    ;   catch(Command, _, (write('I do not understand.'), nl)),
        fail
    ).

The failure after the command sends Prolog back to repeat for the next round, and the cut inside the quit branch ends the loop. (Calling whatever the player types is fine for a toy, but never do it in a program that accepts input from strangers.)

Parsing English with a DCG

Typing go(north). is not much of a game. Read a line, split it into words, and let a DCG (DCG Grammars and Parsing) turn the words into a command term:

PROLOG
parse(Line, Command) :-
    split_string(Line, " ", "", Parts),
    maplist(atom_string, Words, Parts),
    phrase(command(Command), Words).

command(look)         --> [look].
command(inventory)    --> [inventory].
command(go(Dir))      --> [go], [Dir].
command(go(Dir))      --> [Dir], { direction(Dir) }.
command(take(Item))   --> [take], [Item].
command(take(Item))   --> [take], [the], [Item].

direction(north). direction(south). direction(east). direction(west).
direction(up).    direction(down).

With this grammar "go north", "north", "take key" and "take the key" all work. Adding vocabulary means adding one clause.

Python A command parser (Python stand-in interpreter)

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

Extensions

  1. Light. Make the cellar dark: look prints "It is pitch black." unless the player holds the lamp.
  2. Drop and use. Add drop(Item) (the reverse of take/1) and use(key).
  3. Score and moves. Keep a moves/1 counter with retract/assertz and print it when the player wins.
  4. More rooms and puzzles. A guard who accepts a coin, a rope that must be tied somewhere.
  5. Save and load. Write the dynamic facts to a file with listing/1 or portray_clause/2 and read them back with consult/1.
  6. Better input. Use read_line_to_string(user_input, Line) and parse/2, and print "I do not understand" when parse/2 fails.

Common mistakes

  • Writing state as arguments of one huge term and passing it everywhere when facts would be simpler. For games, the database is the natural store.
  • Forgetting to retract the old location before asserting the new one, which leaves the player in two places.
  • Relying on the order of the go/1 clauses without a cut, so the "cannot go" message prints as well as success.
  • Using write/1 on strings and atoms mixed with variables and getting _123 in the output; check that variables are bound before printing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which facts in the adventure should be declared dynamic?

    Only the state that changes during play (player location, item locations, inventory) needs to be dynamic.
  2. 2. Why is the order of the go/1 clauses important?

    The clauses are tried top to bottom; the cuts make the first applicable one final.
  3. 3. How is the player moved from one room to another?

    Variables cannot change, so the old fact is removed and a new one added.
  4. 4. What does the DCG command(take(Item)) --> [take], [the], [Item]. accept?

    The body lists three terminals in order: take, the, then the item word.

Summary

  • Separate static facts (map, descriptions) from dynamic facts (location, items, inventory).
  • Each command is a predicate: check the preconditions, update state with retract/assertz, print a message.
  • Cuts, negation as failure and forall/2 handle case analysis and output.
  • A DCG turns typed words into command terms, so adding vocabulary is adding a clause.

Next: Debugging, Testing and Style