findPath method

List findPath(
  1. int startX,
  2. int startY,
  3. int endX,
  4. int endY,
  5. Grid grid,
)

Find and return the path. @return {Array.<number, number>} The path, including both start and end positions.

Implementation

List findPath(int startX, int startY, int endX, int endY, Grid grid) {
  var openList = this.openList = new Heap(_comparator);
  var startNode = this.startNode = grid.getNodeAt(startX, startY),
      endNode = this.endNode = grid.getNodeAt(endX, endY), node;

  this.grid = grid;


  // set the `g` and `f` value of the start node to be 0
  startNode.g = 0;
  startNode.f = 0;

  // push the start node into the open list
  openList.push(startNode);
  startNode.opened = true;

  // while the open list is not empty
  while (!openList.empty()) {
      // pop the position of node which has the minimum `f` value.
      node = openList.pop();
      node.closed = true;

      if (node == endNode) {
          return backtrace(endNode);
      }

      this._identifySuccessors(node);
  }

  // fail to find the path
  return [];
}