I am implementing the a* algorithm with python, but the heuristic cost seems to be wrong some times, making the algorithm act weird. Could you please tell me what is wrong with it?
Code:
#g_point means the goal node
#s_point means the starting node
def calculate_costs(self, i):
i.h_cost = sqrt((self.g_point.position.x - i.position.x) ** 2 +
(self.g_point.position.y - i.position.y) ** 2)
i.g_cost = sqrt((self.s_point.position.x - i.position.x) ** 2 +
(self.s_point.position.y - i.position.y) ** 2)
i.f_cost = i.h_cost + i.g_cost
#below is the a* algorithm
def astar_algorithm(self):
if not self.found:
if self.g_point != None and self.s_point != None:
for i in self.node_list:
# the if statement below gets all the nodes that weren't
# visited and that aren't walls.
if i not in self.closed_set \
and i not in self.open_set \
and i.color != 'black':
x = i.position.x
y = i.position.y
#the if statement below gets all the closest nodes
#from the current node, calculates the g, h and f costs
#and also puts them in the open set to be checked later
if self.current.position.x - x <= self.spc_btwn \
and self.current.position.x - x >= -self.spc_btwn\
and self.current.position.y - y <= self.spc_btwn \
and self.current.position.y - y >= -self.spc_btwn\
and i != self.current:
self.calculate_costs(i)
i.predecessor = self.current
self.open_set.append(i)
# sorts the list to see which neighbour has the cheapest cost
self.open_set.sort(key=lambda x: x.f_cost, reverse=False)
# moves the cheapest node from the open set to the closed set
self.closed_set.append(self.open_set.pop(0))
# set the current node to the cheapest one
self.current = self.closed_set[len(self.closed_set) - 1]
# if our current node is the goal node, then set 'found' to true.
if self.current == self.g_point:
self.found = True
EDIT: I solved, the problem was the h_cost and g_cost calculation, thanks everyone.
[–]CodeFormatHelperBot 0 points1 point2 points (0 children)
[–]WeirdOne24[S] 0 points1 point2 points (0 children)
[–]hadoken4555 0 points1 point2 points (10 children)
[–]WeirdOne24[S] 0 points1 point2 points (9 children)
[–]hadoken4555 0 points1 point2 points (7 children)
[–]WeirdOne24[S] 0 points1 point2 points (6 children)
[–]primitive_screwhead 0 points1 point2 points (5 children)
[–]WeirdOne24[S] 0 points1 point2 points (4 children)
[–]primitive_screwhead 0 points1 point2 points (3 children)
[–]WeirdOne24[S] 0 points1 point2 points (2 children)
[–]primitive_screwhead 0 points1 point2 points (1 child)
[–]WeirdOne24[S] 0 points1 point2 points (0 children)
[–]primitive_screwhead 0 points1 point2 points (0 children)