50 lines
1.7 KiB
Python
50 lines
1.7 KiB
Python
from collections import deque
|
|
import heapq
|
|
|
|
class AStar:
|
|
def __init__(self, cells):
|
|
self.cells = cells
|
|
|
|
def heuristic(self, current, target):
|
|
# Euclidean distance heuristic
|
|
dx = abs(current[0] - target[0])
|
|
dy = abs(current[1] - target[1])
|
|
return dx + dy
|
|
|
|
def get_neighbors(self, cell):
|
|
neighbors = []
|
|
x, y = cell[0], cell[1]
|
|
if x > 0 and not self.cells[x - 1][y].blocking_movement:
|
|
neighbors.append((x - 1, y))
|
|
if x < len(self.cells) - 1 and not self.cells[x + 1][y].blocking_movement:
|
|
neighbors.append((x + 1, y))
|
|
if y > 0 and not self.cells[x][y - 1].blocking_movement:
|
|
neighbors.append((x, y - 1))
|
|
if y < len(self.cells[x]) - 1 and not self.cells[x][y + 1].blocking_movement:
|
|
neighbors.append((x, y + 1))
|
|
return neighbors
|
|
|
|
def astar(self, start, target):
|
|
open_list = [(0, start)]
|
|
came_from = {}
|
|
g_score = {start: 0}
|
|
|
|
while open_list:
|
|
_, current = heapq.heappop(open_list)
|
|
if current == target:
|
|
path = []
|
|
while current in came_from:
|
|
path.append(current)
|
|
current = came_from[current]
|
|
return path[::-1]
|
|
|
|
for neighbor in self.get_neighbors(current):
|
|
tentative_g_score = g_score[current] + 1
|
|
if tentative_g_score < g_score.get(neighbor, float('inf')):
|
|
came_from[neighbor] = current
|
|
g_score[neighbor] = tentative_g_score
|
|
f_score = tentative_g_score + self.heuristic(neighbor, target)
|
|
heapq.heappush(open_list, (f_score, neighbor))
|
|
|
|
return []
|