Skip to content
Tutorials Center
My learning

Topics

Lesson 35 of 36 ยท Projects and Practice

Project: Text Adventure Engine

Build a small text adventure in Pascal using enumerations, sets, records, case statements and a command parser, plus a runnable C version driven by a scripted game.

Text adventures are a perfect Pascal project. Rooms are records, directions are an enumerated type, the available exits form a set, and the command interpreter is a case statement, three features that Pascal does especially well. The game logic is a state machine: the player is in exactly one room, and each command moves the state forward.

Compile the Pascal on your own machine; here it is read-only. The runnable C version plays a fixed script of commands, so the output is the same every time.

Design

The world is a small map. Every room has a name, a description, and up to four exits.

flowchart LR
  H["Hall"] -- north --> L["Library"]
  H -- east --> K["Kitchen"]
  L -- east --> S["Secret room"]
  K -- north --> S

The Secret room needs a key found in the Kitchen.

The state the game keeps is small: the current room, whether the player holds the key, and whether the game is over. Everything else is fixed data.

Types

Pascal lets you name the concepts:

PASCAL
type
  TDirection = (dNorth, dSouth, dEast, dWest);
  TDirections = set of TDirection;

  TRoomId = (rHall, rLibrary, rKitchen, rSecret);

  TRoom = record
    Name: string;
    Description: string;
    Exits: array[TDirection] of Integer;   // -1 means no exit
    HasKey: Boolean;
  end;

  TGame = record
    Rooms: array[TRoomId] of TRoom;
    Current: TRoomId;
    CarryingKey: Boolean;
    Finished: Boolean;
  end;

An enumeration is a list of names that the compiler numbers 0, 1, 2... and checks for you. array[TDirection] of ... is an array indexed directly by direction: no mapping code, and the compiler rejects an index of the wrong type. A set of TDirection is a bit set you can build with [dNorth, dEast] and test with in. Compare how you would do this in many languages: integer constants and manual range checks.

Filling the map:

PASCAL
procedure Link(var G: TGame; From: TRoomId; Dir: TDirection; Target: TRoomId);
begin
  G.Rooms[From].Exits[Dir] := Ord(Target);
end;

procedure BuildWorld(var G: TGame);
var
  R: TRoomId;
  D: TDirection;
begin
  for R := Low(TRoomId) to High(TRoomId) do
    for D := Low(TDirection) to High(TDirection) do
      G.Rooms[R].Exits[D] := -1;

  G.Rooms[rHall].Name := 'Hall';
  G.Rooms[rLibrary].Name := 'Library';
  G.Rooms[rKitchen].Name := 'Kitchen';
  G.Rooms[rKitchen].HasKey := True;
  G.Rooms[rSecret].Name := 'Secret room';

  Link(G, rHall, dNorth, rLibrary);
  Link(G, rHall, dEast, rKitchen);
  Link(G, rLibrary, dSouth, rHall);
  Link(G, rLibrary, dEast, rSecret);
  Link(G, rKitchen, dWest, rHall);
  Link(G, rKitchen, dNorth, rSecret);
  G.Current := rHall;
end;

The command interpreter

The player types a line such as go north or take key. The program splits it into a verb and a noun, and uses case on the verb. In modern Delphi you can case over strings by chaining if/SameText, or map the verb to an enumeration first, which is cleaner:

PASCAL
type
  TVerb = (vGo, vTake, vLook, vQuit, vUnknown);

function ParseVerb(const Word: string): TVerb;
begin
  if SameText(Word, 'go') then Result := vGo
  else if SameText(Word, 'take') then Result := vTake
  else if SameText(Word, 'look') then Result := vLook
  else if SameText(Word, 'quit') then Result := vQuit
  else Result := vUnknown;
end;

function ParseDirection(const Word: string; out Dir: TDirection): Boolean;
begin
  Result := True;
  if SameText(Word, 'north') then Dir := dNorth
  else if SameText(Word, 'south') then Dir := dSouth
  else if SameText(Word, 'east') then Dir := dEast
  else if SameText(Word, 'west') then Dir := dWest
  else Result := False;
end;

procedure Execute(var G: TGame; const Verb, Noun: string);
var
  Dir: TDirection;
  Target: Integer;
begin
  case ParseVerb(Verb) of
    vGo:
      if not ParseDirection(Noun, Dir) then
        WriteLn('Go where?')
      else
      begin
        Target := G.Rooms[G.Current].Exits[Dir];
        if Target < 0 then
          WriteLn('You cannot go that way.')
        else if (TRoomId(Target) = rSecret) and not G.CarryingKey then
          WriteLn('The door is locked. You need a key.')
        else
        begin
          G.Current := TRoomId(Target);
          WriteLn('You walk to the ', G.Rooms[G.Current].Name, '.');
          if G.Current = rSecret then
          begin
            WriteLn('You found the treasure. You win!');
            G.Finished := True;
          end;
        end;
      end;
    vTake:
      if SameText(Noun, 'key') and G.Rooms[G.Current].HasKey then
      begin
        G.Rooms[G.Current].HasKey := False;
        G.CarryingKey := True;
        WriteLn('You take the key.');
      end
      else
        WriteLn('There is nothing like that here.');
    vLook:
      WriteLn('You are in the ', G.Rooms[G.Current].Name, '.');
    vQuit:
      G.Finished := True;
  else
    WriteLn('I do not understand "', Verb, '".');
  end;
end;

The main loop reads a line with ReadLn, splits it with Pos/Copy (or TStringList with Delimiter = ' ', see text files and TStringList), and calls Execute until G.Finished. Keeping Execute separate from the input loop makes it testable: a unit test can call it with fixed strings.

The same engine in C

The runnable program mirrors the structure: an enum for directions, rooms in an array, a verb parser and a dispatch switch. A scripted list of commands replaces the keyboard.

C Stand-in: a scripted adventure with rooms, key and locked door

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 scanf or fgets), it gets the next line from this box.

Edit the script so that the player goes to the kitchen first, takes the key, then walks through the library. Both routes should win.

Extensions

  1. More verbs: inventory, drop, use. Turn the single CarryingKey flag into a set of items (set of TItem).
  2. Data-driven world: read rooms from a text file with TStringList instead of building them in code, so a friend can write new adventures without recompiling.
  3. Save the game (current room, items) with a typed file (typed files and streams).
  4. Objects: replace the record with a TRoom class and give each room a virtual Enter method, so special rooms behave differently (see inheritance and virtual methods).
  5. A VCL front end: a memo for output and an edit for input.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does array[TDirection] of Integer give you?

    Pascal arrays can use any ordinal type, including an enumeration, as the index type.
  2. 2. How do you test whether dNorth is part of a set of TDirection named Exits?

    The in operator tests membership of an element in a set.
  3. 3. Why is the game logic in Execute rather than in the input loop?

    Separating logic from input and output makes testing and reuse possible.
  4. 4. What kind of design is a game where each command changes which room you are in?

    The game holds a current state, and each command is a transition to a new state.

Summary

  • Enumerations name concepts; arrays can be indexed by them; sets hold combinations such as exits.
  • Records hold rooms and the game state; a case statement dispatches commands.
  • Map text commands to enumerations first, then case on the enumeration.
  • Keep game logic apart from input and output so you can test it.
  • Extend with items, data files, saved games and classes.

Next: Pascal Practice Set