我正在构建一个基于命令行的游戏,我想在其中定义两个节点之间的路径。
地图看起来像这样:
ooooooooooooooo
o o
o ooooooo ooooo //The gaps represent two nodes in the graph. I would like to get
o o o //the coordinates of the pathes between them.
ooooooooooooooo
我想从一个缝隙转到另一个缝隙。如您所见,只有一种方法可以到达那里:通过第二层。我们也可以从第一层开始,但是有一个障碍。当然,我需要检查这两种可能性。我真的不知道如何定义步骤的坐标,需要采取哪些步骤才能到达目的地。
目前我的代码看起来像这样。代码只处理那些不在同一级别的“差距”。
bool Game::recordSteps(int posDiff, int &coordToChange, node &step, std::vector<pos> &steps) {
if (posDiff > 0) {
--coordToChange;
} else if (posDiff < 0) {
++coordToChange;
}
if (map[ac.pos.x][ac.pos.y] != 'x') {
steps.push_back(ac.pos);
return true;
}
return false;
}
void Game::detectAdjacentNodesWithEdge(int i) {
for (int j = 0; j < graphNodes.size(); ++j) {
pos &srcNode = graphNodes.at(i).pos;
pos &destNode = graphNodes.at(j).pos;
int xPosdiff = srcNode.x - destNode.x;
int yPosdiff = srcNode.y - destNode.y;
if (abs(xPosdiff) <= 2 && i != j) {
node edgeTracker = graphNodes.at(i);
std::vector<pos> steps;
if (abs(xPosdiff) == 2) {
recordSteps(xPosdiff, edgeTracker.pos.x, edgeTracker, steps);
}
bool pathWithObstacles = false;
while (edgeTracker.pos.y != destNode.y) {
if (!recordSteps(yPosdiff, edgeTracker.pos.y, edgeTracker, steps)) {
pathWithObstacles = true;
break;
}
}
recordSteps(xPosdiff, edgeTracker.pos.x, edgeTracker, steps);
if (!pathWithObstacles) {
adjacentNodeInf adjNodeInf(j, abs(xPosdiff) + abs(yPosdiff), steps);
graphNodes.at(i).adjList.push_back(adjNodeInf);
}
}
}
}
我想,我已经把现有的实现复杂化了。任何帮助表示赞赏!