-
-
Save Zippytwr/04d4423ef4ff96a03a15461084f63865 to your computer and use it in GitHub Desktop.
Algorithm A* in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class Node { | |
| constructor(position, g = 0, h = 0, parent = null) { | |
| this.position = position; | |
| this.g = g; | |
| this.h = h; | |
| this.f = g + h; | |
| this.parent = parent; | |
| } | |
| } | |
| function astar(grid, start, end) { | |
| const openList = []; | |
| const closedSet = new Set(); | |
| openList.push(new Node(start, 0, heuristic(start, end))); | |
| while (openList.length > 0) { | |
| openList.sort((a, b) => a.f - b.f); | |
| const current = openList.shift(); | |
| if (positionsEqual(current.position, end)) return reconstructPath(current); | |
| closedSet.add(posToString(current.position)); | |
| for (const neighbor of getNeighbors(current.position, grid)) { | |
| if (closedSet.has(posToString(neighbor))) continue; | |
| const g = current.g + 1; | |
| const h = heuristic(neighbor, end); | |
| const node = new Node(neighbor, g, h, current); | |
| if (!openList.some(n => positionsEqual(n.position, neighbor) && n.f <= node.f)) { | |
| openList.push(node); | |
| } | |
| } | |
| } | |
| return null; | |
| } | |
| function getNeighbors([x, y], grid) { | |
| const dirs = [[0,1],[1,0],[0,-1],[-1,0]]; | |
| return dirs | |
| .map(([dx, dy]) => [x + dx, y + dy]) | |
| .filter(([nx, ny]) => nx >= 0 && ny >= 0 && nx < grid.length && ny < grid[0].length && grid[nx][ny] === 0); | |
| } | |
| function heuristic([x1, y1], [x2, y2]) { | |
| return Math.hypot(x2 - x1, y2 - y1); | |
| } | |
| function reconstructPath(node) { | |
| const path = []; | |
| while (node) { | |
| path.push(node.position); | |
| node = node.parent; | |
| } | |
| return path.reverse(); | |
| } | |
| function positionsEqual(a, b) { | |
| return a[0] === b[0] && a[1] === b[1]; | |
| } | |
| function posToString([x, y]) { | |
| return `${x},${y}`; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment