javascript實現A星尋路算法javascript
簡化搜索區域:java
2.創建起點和終點座標,用於尋路git
維護open和close列表算法
搜索路徑canvas
如何尋路呢,首先咱們引入3個量數組
接下來是尋路具體實現函數
對於curr相鄰點,都有如下步驟spa
JS實現的具體方案code
首先創建一個Sopt的類,它裏面包含如下信息blog
創建尋路流程
尋路遞歸函數
創建一個curr表明當前點初始爲null,和currIndex序列號初始爲0
let currIndex = 0; let curr = null; for(let i = 0; i < openList.length; i++) { if(openList[i].f < openList[currIndex].f) { currIndex = i; } } curr = openList[currIndex]; if(curr === endSopt) { drawPath(curr); return true; } removeFromArray(openList, curr); closedList.push(curr);
3.遍歷curr的neighbors,將合適點的parent設爲curr
for(let i = 0; i < curr.neighbors.length; i++) { let neighbor = curr.neighbors[i]; if(!closedList.includes(neighbor) && !neighbor.wall) { let tmpF = curr.g + getG(curr, neighbor) + getH(neighbor); let newPath = false; // 是不是更好的路線 if(openList.includes(neighbor)) { if(tmpF <= neighbor.f) { neighbor.f = tmpF; newPath = true; } } else { neighbor.g = curr.g + getG(curr, neighbor); neighbor.h = getH(neighbor); neighbor.f = neighbor.g + neighbor.h; newPath = true; openList.push(neighbor); } if(newPath) { neighbor.parent = curr; } } } 4.遞歸這個函數,當點和終點一致時,返回這個點,而後遞歸它的parent屬性,則能找到路線
最後附上案例地址:a星算法