0

我正在和几个朋友一起开发地牢游戏,并且正在寻找路径。游戏是基于图块的,我们计划实现的寻路是这样的:

类 PathMapper 生成每个瓦片与给定瓦片的距离网格

类 Monster 使用此网格前往给定的图块(现在,始终是玩家)

我们计划有 4 名玩家,但我们/我希望脚本支持动态数字。每个玩家都有一个整数形式的 ID。

每个玩家都需要一个由 PathMapper 生成的网格,并且所有怪物都可以共享它们(就像生成网格一样慢,对于所有怪物,每个玩家只做一次,似乎是一个不错的寻路解决方案)。

我有一个名为“PathMapper”的类,它生成瓦片与起始瓦片的距离网格。理论上,将创建其中的 4 个——每个玩家一个。对于一个敌人要找到玩家的路径,它会询问玩家的 ID,然后询问相应的格子网格,它将用于寻路。服务器使用“createMap(playerID, playerXPosition, playerYPosition)”更新这些网格。

所以每个网格都是一个向量向量,它映射到私有地图“pathMap”中的玩家ID,怪物可以通过“getLocalPath()”访问的值

问题是,虽然“createMap”编译得很好,但一旦尝试复制第一面墙(“pathMap[ID][x].push_back(9000);”)我得到“EXE_BAD_ACCESS”。我应该注意到,在尝试(并且失败)插入“9000”之前,它经历了大约十二次迭代,我确信地牢->宽度和地牢->高度是正确的(现在都是 20;对于真正的游戏),ID的“正确性”不应该影响代码的访问者,对吧?

我有点困惑,b / c我认为我正在做的是保留空间,循环通过它,并尝试访问我刚刚保留的内存:

reserve(20)
for(i=0; i<20; i++)
    reserve(20)
    for(j=0; j<20; j++)
        access(i,j) // error!?

这是代码:

class PathMapper{
public:
    PathMapper(Dungeon* d);
    void createMap(int ID, int x, int y);

    // returns values of the surrounding tiles (up, right, down, left)
    std::vector<int> getLocalPath(int ID, int x, int y);
private:
    Dungeon* dungeon;
    std::vector< std::vector<bool> > wallBitmap;
    std::map<int, std::vector< std::vector<int> > > pathMap;
}

PathMapper::PathMapper(Dungeon* d) {
    dungeon = d;
    wallBitmap = dungeon->getWalls(); // bools tell if there is a wall on a tile
}

void PathMapper::createMap(int ID, int x, int y) {
    pathMap[ID].reserve(dungeon->width());
    for(int x=0; x<dungeon->width(); x++) {
        pathMap[ID][x] = std::vector<int>();
        pathMap[ID][x].reserve(dungeon->height());
        for(int y=0; y<dungeon->height(); y++) {
            if(wallBitmap[x][y]) {
                pathMap[ID][x].push_back(9000); // error is here
            }
            else {
                pathMap[ID][x][y] = -1;
            }
        }
    }

    // code to calculate values here; shouldn't affect the code above

}
4

2 回答 2

2

Reserve不会改变向量的大小(只有容量),你需要resize

于 2014-04-08T00:02:16.843 回答
1

任何一个

使用resize

pathMap[ID].resize(dungeon->width());
...
pathMap[ID][x] = std::vector<int>();
pathMap[ID][x].resize(dungeon->height());

或者直接在构造函数中传递大小:

pathMap[ID].resize(dungeon->width());
...
pathMap[ID][x] = std::vector<int>(dungeon->height());
于 2014-04-08T00:15:16.470 回答