gpt4 book ai didi

python - 寻路算法无法正常工作

转载 作者:太空宇宙 更新时间:2023-11-03 21:21:08 26 4
gpt4 key购买 nike

对于大学的一个项目,我想编写一个探路者程序,使用 a-star 来找到从终点到目标的最佳可能方法。对于几乎直线,该算法工作得很好。当创建障碍并且路径必须转弯时,算法会遇到问题,程序将无法找到路径。我想尝试使左侧显示的场景起作用,但到目前为止我还没有找到令人满意的解决方案。

有关算法和 GUI,您还可以访问 https://github.com/NiklasB1337/PathFinder1.1

左侧显示问题发生的位置: https://i.gyazo.com/4488e22ad5610c81061e682514524ed2.png

# Astar
def astar(self, maze, start, end):

"""Returns a list of tuples as a path from the given start to the given end in the given maze"""

# 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 open and closed list
open_list = []
closed_list = []

# Add the start node
open_list.append(start_node)

# Loop until the end is found
while len(open_list) > 0:

# 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)

# finding 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])

# make sure the node is 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 the terrain is walkable
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)

# loop through children
for child in children:

# child is on the closed list
for closed_child in closed_list:
if child == closed_child:
continue

#cCreate 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)

最佳答案

仅看图像,起点或终点似乎位于障碍物上且无法到达。如果它是左上角的起始 block ,则第一次扫描邻居将不会返回任何内容。 ?

关于python - 寻路算法无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54240793/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com