Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why use a tree data structure to represent data in a text adventure game?

As an assignment for my C++ module, I have to build a text-adventure game. The problem I'm facing is a conceptual one; everyone is saying I should use a tree data structure to represent my game. What I don't get is why.

Let's say I have a house of 4 rooms. We can imagine this as an 2x2 array. In each room I have two objects. I want to display this data in such a way that I can easily move my character from 0x0 to 0x1 either way (directly – 1 step, or indirectly – 3 steps), while carrying one object with me.

Why is it better to use a tree to hold all data and how will my character move form one node to another? Or is the character a node as well? Shouldn't my character be an object with a list as its inventory?

I'm a little confused about this. I'm not looking for any code, just a better understanding of data representation and manipulation.

The suggestion was for maps. But then I don't understand how my character will "navigate" a map, either.

like image 940
Adrian Avatar asked Mar 11 '12 17:03

Adrian


1 Answers

If your "house" is a grid and you can move from any grid cell to any other grid cell, an array is fine. I'm guessing what your peers are hinting at is that you may not want to be able to move from any room to any adjacent room (and also NOT be able to move from say 0,0 to 42,13).

However, with a tree structure, you still cannot represent an arbitrary set of transitions between rooms.

A more flexible approach would be an Adjacency List, which is a specialized type of graph. Think of each room as a node, and give each node a list of other rooms that can be transitioned to. With that structure, you can even allow for one-way transitions (think one-way door from many adventure games).

pseudocode

class Room
{
    string Name;
    string Description
    List<Room> ConnectedRooms;
}

Then when representing the character

class Character
{
    string Name;
    Room CurrentRoom;
}

To see where a given character is able to move to:

List<Room> availableRooms = myCharacter.CurrentRoom.ConnectedRooms;
like image 87
Eric J. Avatar answered Oct 07 '22 05:10

Eric J.