js寻路代码
答:一个可用于实现寻路功能的JavaScript代码如下:
// Create a grid of nodes for our pathfinding algorithm.
var grid = [];
for (var x = 0; x < 10; x++) {
var row = [];
for (var y = 0; y < 10; y++) {
row.push(new Node(x,y));
}
grid.push(row);
}
// Find the shortest path between two nodes using A* algorithm.
function findPath(startX, startY, endX, endY) {
// Create start and end node objects.
var startNode = grid[startX][startY];
var endNode = grid[endX][endY];
// Set of currently open nodes that we haven't checked yet.
var openSet = [startNode];
// Set of already-checked nodes that we don't need to revisit again.
var closedSet = [];
// Keep looping until all the nodes have been checked or the shortest path has been found.
while (openSet.length > 0) {
// Find the node with the lowest cost in the open set and switch it to the closed set. var currentNodeIndex = getLowestCostIndex(openSet); var currentNode = openSet[currentNodeIndex]; closedSet.push(currentNode); openSet.splice(currentNodeIndex, 1); if (currentNode === endNode) { return reconstructPath(closedSet); } // Generate an array of all possible neighbors of this node that aren't already in either set and add them to the open set if they're not obstacles or walls.. for (var i=0; i<grid[currentNode].neighbors().length; i++) { if (!inClosedOrOpenSets(grid[currentNode].neighbors()[i], closedSet, openSet)) { if (!grid[currentNode].neighbors()[i].isObstacle()) { openSet.push(grid[currentNodes].neighbors()[i]); } } } } return null; };
免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。