Astar寻路有时会停止工作



当我需要在迷宫(0和1的矩阵(中搜索路径时,我正在做一个项目,给定一个原点(位置元组(和一个目的地。 它可以工作,但有时它只是停止,进入 while 循环,在打开节点时,永远不会到达终端节点......我不知道为什么。 我在"中等"网站上找到了该算法。

'''

Def Astar(迷宫,开始,结束,奖金,exit_door(:

maze = [ [0 if x == 0 else 1 for x in y] for y in maze ]
x_end=end[0]
y_end=end[1]
maze[x_end][y_end]=0
if bonus:
x_bonus=bonus[0]
y_bonus=bonus[1]
maze[x_bonus][y_bonus]=0
if exit_door:
x_exit=exit_door[0]
y_exit=exit_door[1]
maze[x_exit][y_exit]=0


# Create start and end node
start_node = Node(None, start)
start_node.g = start_node.h = start_node.f = 0
end_node = Node(None, end)
end_node.g = end_node.h = end_node.f = 0
# Initialize both open and closed list
open_list = []
closed_list = []
# Add the start node
open_list.append(start_node)

# Loop until you find the end
while len(open_list) > 0 :
tempo=tempo+1
# Get the current node
current_node = open_list[0]
current_index = 0
for index, item in enumerate(open_list):
if item.f <= current_node.f:
current_node = item
current_index = index
# Pop current off open list, add to closed list
open_list.pop(current_index)
closed_list.append(current_node)
# Found the goal
if current_node == end_node:
path = []
current = current_node
while current is not None:
path.append(current.position)
current = current.parent
return path[::-1] # Return reversed path





# Generate children
children = []
####
for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0)]: # Adjacent squares
# Get node position
node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])
## vê cada quadrado adjacente ao nosso current
# Make sure within range
if node_position[0] > (len(maze) - 1) or node_position[0] < 0 or node_position[1] > (len(maze[len(maze)-1]) -1) or node_position[1] < 0:
continue
# Make sure walkable terrain
if maze[node_position[0]][node_position[1]] != 0:
continue
# Create new node
new_node = Node(current_node, node_position)
# Append
children.append(new_node)
## children apenas contém os nós que correspondem a quadrados para o quais o agente pode andar
# Loop through children
for child in children:
# Child is on the closed list
for closed_child in closed_list:
if child == closed_child:
continue
# Create the f, g, and h values
child.g = current_node.g + 1
child.h = ((child.position[0] - end_node.position[0]) ** 2) + ((child.position[1] - end_node.position[1]) ** 2)
child.f = child.g + child.h
# Child is already in the open list
for open_node in open_list:
if child == open_node and child.g > open_node.g:
continue
# Add the child to the open list
open_list.append(child)

'''

这是行不通的,因为你有 2 次失误

for closed_child in closed_list:
if child == closed_child:
continue

for open_node in open_list:
if child == open_node and child.g > open_node.g:
continue

操作员continue退出 INER。您应该对open_list和closed_list使用另一种类型。

最新更新