1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136
| class AStar { constructor(grid) { this.grid = grid; this.openList = new Map(); this.closedList = new Set(); this.cameFrom = new Map(); }
distance(nodeA, nodeB) { return Math.abs(nodeA.x - nodeB.x) + Math.abs(nodeA.y - nodeB.y); }
getNodeKey(node) { return `${node.x},${node.y}`; }
findPath(start, end) { start.g = 0; start.f = this.distance(start, end); this.openList.set(this.getNodeKey(start), start);
while (this.openList.size > 0) { const current = Array.from(this.openList.values()).reduce((min, node) => !min || node.f < min.f ? node : min );
if (current.x === end.x && current.y === end.y) { return this.reconstructPath(start, end); }
const currentKey = this.getNodeKey(current); this.openList.delete(currentKey); this.closedList.add(currentKey);
for (const neighbor of this.grid.getNeighbors(current)) { const neighborKey = this.getNodeKey(neighbor);
if (this.closedList.has(neighborKey)) { continue; }
const tentativeG = current.g + 1; neighbor.g = tentativeG; neighbor.f = neighbor.g + this.distance(neighbor, end); this.cameFrom.set(neighborKey, current); if (!this.openList.has(neighborKey)) { this.openList.set(neighborKey, neighbor); } } }
return null; }
reconstructPath(start, end) { const path = []; let current = end;
while (current) { path.unshift(current); const currentKey = this.getNodeKey(current); current = this.cameFrom.get(currentKey);
if (current && current.x === start.x && current.y === start.y) { path.unshift(start); break; } }
return path; } }
function testAStar() { const grid = new Grid(10, 10);
[ [2, 2], [2, 3], [2, 4], [5, 5], [5, 6], [5, 7], [7, 2], [7, 3], [7, 4], ].forEach(([x, y]) => grid.addObstacle(x, y));
const start = { x: 0, y: 0 }; const end = { x: 9, y: 9 };
const astar = new AStar(grid); const path = astar.findPath(start, end);
console.log("Grid with path:"); for (let y = 0; y < grid.height; y++) { let line = ""; for (let x = 0; x < grid.width; x++) { if (grid.obstacles.has(`${x},${y}`)) { line += "█ "; } else if (path && path.some((node) => node.x === x && node.y === y)) { line += "* "; } else { line += ". "; } } console.log(line); }
if (path) { console.log( "\nPath found:", path.map((node) => `(${node.x},${node.y})`).join(" -> ") ); } else { console.log("\nNo path found!"); } }
testAStar();
|