|
| 1 | +/* |
| 2 | +Toolbox Aid |
| 3 | +David Quesenberry |
| 4 | +03/22/2026 |
| 5 | +GridPathfinding.js |
| 6 | +*/ |
| 7 | +function getNodeKey(x, y) { |
| 8 | + return `${x},${y}`; |
| 9 | +} |
| 10 | + |
| 11 | +function heuristic(a, b) { |
| 12 | + return Math.abs(a.x - b.x) + Math.abs(a.y - b.y); |
| 13 | +} |
| 14 | + |
| 15 | +function isWalkable(grid, x, y) { |
| 16 | + return y >= 0 && y < grid.length && x >= 0 && x < grid[y].length && grid[y][x] === 0; |
| 17 | +} |
| 18 | + |
| 19 | +export function findGridPath(grid, start, goal) { |
| 20 | + if (!isWalkable(grid, start.x, start.y) || !isWalkable(grid, goal.x, goal.y)) { |
| 21 | + return []; |
| 22 | + } |
| 23 | + |
| 24 | + const open = [{ x: start.x, y: start.y, g: 0, f: heuristic(start, goal) }]; |
| 25 | + const cameFrom = new Map(); |
| 26 | + const costSoFar = new Map([[getNodeKey(start.x, start.y), 0]]); |
| 27 | + |
| 28 | + while (open.length > 0) { |
| 29 | + open.sort((a, b) => a.f - b.f); |
| 30 | + const current = open.shift(); |
| 31 | + |
| 32 | + if (current.x === goal.x && current.y === goal.y) { |
| 33 | + const path = [{ x: current.x, y: current.y }]; |
| 34 | + let key = getNodeKey(current.x, current.y); |
| 35 | + |
| 36 | + while (cameFrom.has(key)) { |
| 37 | + const previous = cameFrom.get(key); |
| 38 | + path.unshift(previous); |
| 39 | + key = getNodeKey(previous.x, previous.y); |
| 40 | + } |
| 41 | + |
| 42 | + return path; |
| 43 | + } |
| 44 | + |
| 45 | + const neighbors = [ |
| 46 | + { x: current.x + 1, y: current.y }, |
| 47 | + { x: current.x - 1, y: current.y }, |
| 48 | + { x: current.x, y: current.y + 1 }, |
| 49 | + { x: current.x, y: current.y - 1 }, |
| 50 | + ]; |
| 51 | + |
| 52 | + neighbors.forEach((neighbor) => { |
| 53 | + if (!isWalkable(grid, neighbor.x, neighbor.y)) { |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + const nextCost = current.g + 1; |
| 58 | + const key = getNodeKey(neighbor.x, neighbor.y); |
| 59 | + const previousCost = costSoFar.get(key); |
| 60 | + |
| 61 | + if (previousCost !== undefined && nextCost >= previousCost) { |
| 62 | + return; |
| 63 | + } |
| 64 | + |
| 65 | + costSoFar.set(key, nextCost); |
| 66 | + cameFrom.set(key, { x: current.x, y: current.y }); |
| 67 | + open.push({ |
| 68 | + x: neighbor.x, |
| 69 | + y: neighbor.y, |
| 70 | + g: nextCost, |
| 71 | + f: nextCost + heuristic(neighbor, goal), |
| 72 | + }); |
| 73 | + }); |
| 74 | + } |
| 75 | + |
| 76 | + return []; |
| 77 | +} |
0 commit comments