【问题标题】:why does my a star algorithm not work in javascript?为什么我的星算法在 javascript 中不起作用?
【发布时间】:2021-04-12 14:38:51
【问题描述】:
function algorithm(){
if(startPoint === true && endPoint === true){
//add the heuristic distance to the start position from the final position
startPosition.h = distance([startPosition.x, startPosition.y]);

let openList = []

openList.push(startPosition)
let closedList = []
  while (openList.length > 0){
    //print(openList)
    lowPos = 0;
    for(let i = 0; i < openList.length; i++){
      if(openList[i].f < openList[lowPos].f){
        lowPos = i;
      }
    }
    let currentPosition = openList[lowPos];
    //currentPosition.check()
    //if the currentPosition is the endPosition, retrace steps and find the path, then return this path
    if(currentPosition === endPosition){
      let curr = currentPosition;
      let ret = [];
      while(curr.parent != null){
        curr.path()
        ret.push(curr);
        curr = curr.parent;
      }
      endPosition.end()
      return ret.reverse();
    }
    openList.splice(lowPos, 1);
    closedList.push(currentPosition);
    let neighbours = neighbors(currentPosition);
    for(let i = 0; i < neighbours.length; i++){
      let neighbour = neighbours[i];
      if(closedList.includes(neighbour) || neighbour.colour == "black"){
        continue;
      }
      neighbour.check()
      let gScore = currentPosition.g + 1;
      let gScoreBest = false;
      if(openList.includes(neighbour) == false){
        gScoreBest = true;
        neighbour.h = distance([neighbour.x, neighbour.y]);
        openList.push(neighbour);
      }
      else if(gScore < neighbour.g){
        gScoreBest = true;
      }
      if(gScoreBest == true){
        neighbour.parent = currentPosition;
        neighbour.g = gScore;
        neighbour.f = neighbour.g + neighbour.h;
      }
    }
  }
}
 //meaning that either the path is not possible or the final node/initial node 
 has not yet been placed.
 return [];
}

这是我在 p5 中的星形算法,我正在尝试制作星形可视化项目,但由于某种原因,突出显示的块比预期的要多。 [: https://i.stack.imgur.com/ILlOr.png 实际上它应该是这样的::https://i.stack.imgur.com/nsF5r.png

第二张图片不是我的,是别人实现的:https://qiao.github.io/PathFinding.js/visual/ = 第二张图片的链接

我认为这与行的顺序有关:neighbour.check() 改变了块的颜色。

这是一个对角线的解决方案,你可以看到由于某种原因左上角有紫色,这是我的问题。不应该搜索左上角,但出于某种原因。

如果您需要更多我的代码,请告诉我。

【问题讨论】:

  • 根据提供的 2 个示例,您的目标是什么并不清楚。当前算法中两点之间的对角线连接似乎只是出租车路径,而它应该看起来的示例恰好是结果示例,当然结果是一条直线。您能否举例说明对角线情况的结果应该是什么?
  • @Trentium 我已经添加了需要的东西,并且还添加了对角线功能,但它仍然不起作用。

标签: javascript graph graphics p5.js a-star


【解决方案1】:

您似乎没有检查对角线。 这不是一个错误。你做得很好。

【讨论】:

  • 感谢您的称赞,但我的问题是,由于某种原因,左上角在不应该被检查的情况下被检查,应该有一条直接的路径而不是检查左上角,如果你可以帮助它将不胜感激
【解决方案2】:

我得到了修复,令人惊讶的是我的距离公式是错误的,我调用了错误的变量。

这就是它现在的样子! :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-08
    • 2011-10-31
    • 2023-03-31
    相关资源
    最近更新 更多