2019SZI-Projekt/UI/Apath.py

75 lines
2.2 KiB
Python
Raw Normal View History

2019-04-15 12:19:26 +02:00
import numpy
2019-04-15 12:54:29 +02:00
from heapq import * # pylint: disable=unused-wildcard-import
2019-04-15 12:19:26 +02:00
def heuristic(a, b, pathing):
2019-04-15 12:54:29 +02:00
2019-04-15 12:19:26 +02:00
x = abs(a[0]-b[0])
y = abs(a[1]-b[1])
if pathing == '*':
if x > y:
return 14*y + 10*(x - y)
else:
return 14*x + 10*(y - x)
else:
return 10*(x + y)
2019-04-15 12:54:29 +02:00
2019-04-15 12:19:26 +02:00
def astar(array, start, goal, pathing):
if pathing == '+':
2019-04-15 12:54:29 +02:00
neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0)]
2019-04-15 12:19:26 +02:00
else:
2019-04-15 12:54:29 +02:00
neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
neighbors = [(i, j)for i in range(-1, 2, 1) for j in range(2)]
2019-04-15 12:19:26 +02:00
came_from = {}
2019-04-15 12:54:29 +02:00
gscore = {start: 0}
fscore = {start: heuristic(start, goal, pathing)}
2019-04-15 12:19:26 +02:00
oheap = []
checked = []
heappush(oheap, (fscore[start], start))
2019-04-15 12:54:29 +02:00
2019-04-15 12:19:26 +02:00
while oheap:
current = heappop(oheap)[1]
checked.append(current)
if current == goal:
data = []
while current in came_from:
data.append(current)
current = came_from[current]
return list(reversed(data)), checked
array[current[0], current[1]] = 2
for i, j in neighbors:
2019-04-15 12:54:29 +02:00
neighbor = current[0] + i, current[1] + j
2019-04-15 12:19:26 +02:00
tentative_g_score = gscore[current] + heuristic(current, neighbor, pathing)
2019-04-15 12:54:29 +02:00
2019-04-15 12:19:26 +02:00
if 0 <= neighbor[0] < array.shape[0]:
if 0 <= neighbor[1] < array.shape[1]:
if array.flat[array.shape[1] * neighbor[0]+neighbor[1]] == 1:
continue
else:
# array bound y walls
continue
else:
# array bound x walls
continue
2019-04-15 12:54:29 +02:00
2019-04-15 12:19:26 +02:00
if array[neighbor[0]][neighbor[1]] == 2 and tentative_g_score >= gscore.get(neighbor, 0):
continue
2019-04-15 12:54:29 +02:00
if tentative_g_score < gscore.get(neighbor, 0) or neighbor not in [i[1]for i in oheap]:
2019-04-15 12:19:26 +02:00
came_from[neighbor] = current
gscore[neighbor] = tentative_g_score
fscore[neighbor] = tentative_g_score + heuristic(neighbor, goal, pathing)
heappush(oheap, (fscore[neighbor], neighbor))
return False