Hier ist mein Code:
Code: Alles auswählen
import numpy
from PIL import Image
from heapq import *
weiss = (255,255,255)
schwarz = (0,0,0)
grun = (0,48,0)
sehrgrun = (0,255,0)
rot = (48,0,0)
sehrrot = (255,0,0)
grau1 = (207,207,207)
grau2 = (43,43,43)
grau3 = (27,27,27)
grau4 = (23,23,23)
liste = []
walls = []
mph =1
c1 = 0
c2 = 0
rechlist = []
rotlist = []
start = []
reachable = False
s = 1
walls = []
bigwalls = []
Bild = Image.open('quax.png')
quaxerg = Bild.copy
w, h = Bild.size
Bildk = Bild.resize((int(w*0.5), int(h*0.5)),Image.BICUBIC)
Bildk.save('b.png')
w = w * 0.5
h = h * 0.5
w = int(w)
h = int(h)
for y in range(h):
for x in range(w):
if Bildk.getpixel((x,y)) == (grau1 or grau2 or grau3 or grau4):
walls.append(1)
#####################
liste = []
if Bildk.getpixel((x,y)) == rot:
c1 = x
c2 = y
walls.append(0)
rechlist.append(c1)
rechlist.append(c2)
rotlist.append(rechlist)
rechlist=[]
if Bildk.getpixel((x,y)) == grun:
start.append(x)
start.append(y)
walls.append(0)
if Bildk.getpixel((x,y)) == weiss:
walls.append(1)
#####################
liste = []
if Bildk.getpixel((x,y)) == schwarz:
walls.append(0)
walls = numpy.asarray(walls)
bigwalls.append(walls)
walls = []
bigwalls = numpy.asarray(bigwalls)
def heuristic(a, b):
return (b[0] - a[0]) ** 2 + (b[1] - a[1]) ** 2
def astar(array, start, goal, mph):
start = tuple(start)
goal = tuple(goal)
print (start,goal)
neighbors = [(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]
close_set = set()
came_from = {}
gscore = {start:0}
fscore = {start:heuristic(start, goal)}
oheap = []
heappush(oheap, (fscore[start], start))
while oheap:
mph = mph + 1
current = heappop(oheap)[1]
Bildk.putpixel(current,sehrgrun)
print (mph)
if mph == 20000:
Bildk.save('ENDlich_ENDe_2.png')
if current == goal:
data = []
while current in came_from:
Bildk.putpixel(current, sehrgrun)
data.append(current)
current = came_from[current]
return data
close_set.add(current)
for i, j in neighbors:
neighbor = current[0] + i, current[1] + j
tentative_g_score = gscore[current] + heuristic(current, neighbor)
if 0 <= neighbor[0] < h :
if 0 <= neighbor[1] < w:
if array[neighbor[0]][neighbor[1]] == 1:
continue
else:
# array bound y walls
continue
else:
# array bound x walls
continue
if neighbor in close_set and tentative_g_score >= gscore.get(neighbor, 0):
continue
if tentative_g_score < gscore.get(neighbor, 0) or neighbor not in [i[1]for i in oheap]:
came_from[neighbor] = current
gscore[neighbor] = tentative_g_score
fscore[neighbor] = tentative_g_score + heuristic(neighbor, goal)
heappush(oheap, (fscore[neighbor], neighbor))
Bildk.putpixel(rechlist, sehrrot)
return False
'''Here is an example of using my algo with a numpy array,
astar(array, start, destination)
astar function returns a list of points (shortest path)'''
nmap = bigwalls
print ('ich bin hier')
mph = 0
print (astar(nmap, (70,70),(500,500), mph))
Bildk.save ('ENDlich_ENDe_2.png')
Danke schonmal im Vorraus,
Bananasplit