qcode
  • 创作工场专业版,一问多答!更智能、更完整、更原创
  • 这是一个超强内容创作平台,它会写文章、做设计、绘图、敲代码,有问必答!
🔥点击使用-免登录深度版🔥

js寻路代码

时间2023-05-06 10:34:08 提问来自 广东省揭阳市 的网友 分类创作 浏览335
答:一个可用于实现寻路功能的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; };

不满意?免费深度重写!

免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。

上一篇 求四个int类型数据的最大值的c程序 下一篇 电极丝有哪些方面的性能需要检测