Your Ad Here

Friday, April 24, 2009

pathfinding algorithm

I'm making a tower defense game in python similar to Desktop Tower Defense.
I've written a dijkstra pathfinding algorithm that should be run every time a tower is placed. it should be run for start to finish, as well as once for every creep on the map.
However, it takes far too long for only a 48 X 64 grid even for just a single path.
am i taking the wrong approach or if something is causing my algorithm to be inneficient can someone point out to me what it may be?

Code:
---------
dir_x = [ 0, 1, 1, 1, 0,-1,-1,-1]
dir_y = [-1,-1, 0, 1, 1, 1, 0,-1]
inf = float('inf')
sqrt2 = math.sqrt(2)
# find_path
# defines the path that the enemy should follow.
# returns list of nodes which is the shortest path from tuple coordinate xy to the closest end point.
# if no path exists then returns None
# map is a map object
# end is a list of tuple coordinates where the end spaces are
def find_path(map, end, xy):
grid = map.grid
y = len(grid)
x = len(grid[0])
startx,starty = xy[0],xy[1]
pq = []
dd = []
for i in range(y):
dd.append([])
for j in range(x):
dd[i].append(None)
dd[starty][startx] = Node((startx,starty))
dd[starty][startx].distance = 0.0
heappush(pq, dd[starty][startx])
try:
while pq[0] is not None:
curr = heappop(pq)
for i in range(8):
d = 0.0
u = curr.x + dir_x[i]
v = curr.y + dir_y[i]
if i%2 is 1:
d = sqrt2
else:
d = 1.0
if u < 0 or u >= x or v < 0 or v >= y:
continue
if grid[v][u] is 'x':
continue
next = Node((u,v))
next.distance = curr.distance + d
next.direction = i
next.prev = curr
try:
if dd[v][u] is None or next < dd[v][u]:
dd[v][u] = next
heappush(pq,next)
except ValueError:
pass
#end while
except IndexError:
pass
res = []
end.sort()
try:
next = dd[end[0][1]][end[0][0]]
if next is not None and next.distance is inf:
return None
else:
while next is not None and next.prev is not None:
res.append((next.x,next.y))
next = next.prev
except IndexError:
return None
res.sort()
return res
---------


Read More...
Your Ad Here

No comments: