69 lines
2.4 KiB
TypeScript
69 lines
2.4 KiB
TypeScript
type Position = { x: number; y: number }
|
|
export type Node = Position & { parent?: Node; g: number; h: number; f: number }
|
|
|
|
export class AStar {
|
|
private static readonly DIRECTIONS = [
|
|
{ x: 0, y: -1 }, // Up
|
|
{ x: 0, y: 1 }, // Down
|
|
{ x: -1, y: 0 }, // Left
|
|
{ x: 1, y: 0 }, // Right
|
|
{ x: -1, y: -1 },
|
|
{ x: -1, y: 1 },
|
|
{ x: 1, y: -1 },
|
|
{ x: 1, y: 1 }
|
|
]
|
|
|
|
static findPath(start: Position, end: Position, grid: number[][], allowDiagonal = false): Node[] {
|
|
const openList: Node[] = [{ ...start, g: 0, h: 0, f: 0 }]
|
|
const closedSet = new Set<string>()
|
|
const getKey = (p: Position) => `${p.x},${p.y}`
|
|
|
|
while (openList.length > 0) {
|
|
const current = openList.reduce((min, node) => (node.f < min.f ? node : min))
|
|
if (current.x === end.x && current.y === end.y) return this.reconstructPath(current)
|
|
|
|
openList.splice(openList.indexOf(current), 1)
|
|
closedSet.add(getKey(current))
|
|
|
|
const neighbors = this.DIRECTIONS.slice(0, allowDiagonal ? 8 : 4)
|
|
.map((dir) => ({ x: current.x + dir.x, y: current.y + dir.y }))
|
|
.filter((pos) => this.isValidPosition(pos, grid, end))
|
|
|
|
for (const neighbor of neighbors) {
|
|
if (closedSet.has(getKey(neighbor))) continue
|
|
|
|
const g = current.g + this.getDistance(current, neighbor)
|
|
const existing = openList.find((node) => node.x === neighbor.x && node.y === neighbor.y)
|
|
|
|
if (!existing || g < existing.g) {
|
|
const h = this.getDistance(neighbor, end)
|
|
const node: Node = { ...neighbor, g, h, f: g + h, parent: current }
|
|
if (!existing) openList.push(node)
|
|
else Object.assign(existing, node)
|
|
}
|
|
}
|
|
}
|
|
|
|
return [] // No path found
|
|
}
|
|
|
|
private static isValidPosition(pos: Position, grid: number[][], end: Position): boolean {
|
|
return pos.x >= 0 && pos.y >= 0 && pos.x < grid[0].length && pos.y < grid.length && (grid[pos.y][pos.x] === 0 || (pos.x === end.x && pos.y === end.y))
|
|
}
|
|
|
|
private static getDistance(a: Position, b: Position): number {
|
|
const dx = Math.abs(a.x - b.x),
|
|
dy = Math.abs(a.y - b.y)
|
|
// Manhattan distance for straight paths, then Euclidean for diagonals
|
|
return dx + dy + (Math.sqrt(2) - 2) * Math.min(dx, dy)
|
|
}
|
|
|
|
private static reconstructPath(endNode: Node): Node[] {
|
|
const path: Node[] = []
|
|
for (let current: Node | undefined = endNode; current; current = current.parent) {
|
|
path.unshift(current)
|
|
}
|
|
return path
|
|
}
|
|
}
|