2019SZI-Projekt/UI/Apath.py

71 lines
2.0 KiB
Python
Raw Normal View History

2019-04-25 20:56:02 +02:00
import numpy as np
2019-04-15 12:54:29 +02:00
from heapq import * # pylint: disable=unused-wildcard-import
2019-04-15 12:19:26 +02:00
2019-04-25 20:56:02 +02:00
def heuristic(a, b):
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])
2019-04-25 20:56:02 +02:00
if x > y:
return 14*y + 10*(x - y)
2019-04-15 12:19:26 +02:00
else:
2019-04-25 20:56:02 +02:00
return 14*x + 10*(y - x)
2019-04-15 12:19:26 +02:00
2019-04-15 12:54:29 +02:00
2019-04-25 20:56:02 +02:00
def Astar(array, start, goal):
2019-04-15 12:19:26 +02:00
2019-04-25 20:56:02 +02:00
neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
2019-04-15 12:19:26 +02:00
came_from = {}
2019-04-15 12:54:29 +02:00
gscore = {start: 0}
2019-04-25 20:56:02 +02:00
fscore = {start: heuristic(start, goal)}
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
2019-04-25 20:56:02 +02:00
print("array current",array[current[0],current[1]])
array[current[0], current[1]]=2
2019-04-15 12:19:26 +02:00
for i, j in neighbors:
2019-04-15 12:54:29 +02:00
neighbor = current[0] + i, current[1] + j
2019-04-25 20:56:02 +02:00
tentative_g_score = gscore[current] + heuristic(current, neighbor)
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
2019-04-25 20:56:02 +02:00
fscore[neighbor] = tentative_g_score + heuristic(neighbor, goal)
2019-04-15 12:19:26 +02:00
heappush(oheap, (fscore[neighbor], neighbor))
return False