C ++基于文本的游戏 - “地图”实现

时间:2014-10-29 09:48:01

标签: c++ data-structures linked-list

我试图创建一个基于文本的冒险游戏。我想我希望地图由不同的节点表示,其中每个节点对应一个不同的位置,并且具有应该指向相应方向上的另一个节点的节点指针变量(左,前和右)。我试图将它实现为链表,但是使用这种数据结构,我只能将每个节点指向另一个节点。我希望每个节点指向其他三个节点。我可以使用哪种数据结构来实现这一点,还是可以实现?

2 个答案:

答案 0 :(得分:2)

链接数据结构可以很好地完成您想要的任务:

示例:

class location
{
    std::string loc_name;
    std::vector<std::pair<std::string,location*>> connections;
    std::string description;
public:
    bool add_link(location* loc, std::string dicription_to, std::string dicription_from);
    //other parameters + functions to manage class
}

这将允许您创建以下位置:

location* loc = new location("graveyard");
loc->description = "A spooky graveyard on a hill, a cool mist floats amongst the gravestones and monuments";
loc->add_link(crypt /*previously defined*/, 
              "An imposing mausoleum with an open door, steps inside lead down into darkness", 
              "Moonlight filters down from the top of some steps, a way out?");
loc.add_link(spooky_house /*previously defined*/, 
              "The North gate of the graveyard", 
              "The entrance to the house's spooky graveyard");

我建议你创建一个你可以阅读的地图文件。可能使用这样的模板:

位置文件:

/*locations, format = "name; description"*/
Spooky House; house_description
Crypt;        crypt_description
Graveyard;    A spooky graveyard on a hill, a cool mist floats amongst the gravestones and monuments

链接文件:

/*links, format = "index # (from); index # (to); description (from->to); description (to->from)"*/
3;2;An imposing mausoleum with an open door, steps inside lead down into darkness; Moonlight filters down from the top of some steps, a way out?
3;1;The North gate of the graveyard;The entrance to the house's spooky graveyard;

加载地图就像在所有位置读取并将它们推入矢量进行存储一样简单,然后添加链接以连接它们。

答案 1 :(得分:1)

您可以在地图上实现具有链接位置的自定义链接数据结构,如下所示:

struct Map_Node{
    Map_Node *left;
    Map_Node *right;
    Map_Node *forward;
    /* other needed field*/
};

然后,您需要自己进行内存管理。例如,通过使用智能指针。

std::shared_ptr<Map_Node> entry{ new MapNode };
std::shared_ptr<Map_Node> hallway{ new MapNode };
entry->forward = &*hallway;
//and so on

获取下一个文件更简单但效率更低的是std :: map。如果每个职位 有其唯一的ID,例如一个字符串,您可以存储相邻字段的ID,并使用ID在地图上自由移动。

struct Map_Node{
    std::string name;
    std::string left;
    std::string right;
    std::string forward;
    /* other needed field*/
};

std::map<std::string, Map_Node> map;
Map_Node entry;
entry.name = "entry";
map[entry.name] = entry; 

Map_Node hallway;
hallway.name = "hallway";
map[hallway.name] = hallway; 

//links between:
map["entry"].forward = "hallway";