a. 全局路径规划
# 使用 A* 算法示例
class Node:
def __init__(self, position, parent=None):
self.position = position
self.parent = parent
self.g = 0
self.h = 0
self.f = 0
def astar(start, end, grid):
open_list = []
closed_list = []
open_list.append(start)
while open_list:
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
open_list.pop(current_index)
closed_list.append(current_node)
if current_node == end:
path = []
current = current_node
while current is not None:
path.append(current.position)
current = current.parent
return path[::-1]
children = []
for new_position in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
node_position = (current_node.position[0] + new_position[0], current_node.position[1] + new_position[1])
if node_position[0] > (len(grid) - 1) or node_position[0] < 0 or node_position[1] > (len(grid[len(grid) - 1]) -1) or node_position[1] < 0:
continue
if grid[node_position[0]][node_position[1]] != 0:
continue
new_node = Node(node_position, current_node)
children.append(new_node)
for child in children:
if child in closed_list:
continue
child.g = current_node.g + 1
child.h = ((child.position[0] - end.position[0]) ** 2) + ((child.position[1] - end.position[1]) ** 2)
child.f = child.g + child.h
if child in open_list:
if child.g > open_list[open_list.index(child)].g:
continue
open_list.append(child)