针对上面这个代码,我想实现可以自主输入起点、终点和路径障碍应该改进,请给出改进后的代码
时间: 2024-03-21 15:42:28 浏览: 16
好的,根据你的需求,我改进了一下代码,让它可以让用户自主输入起点、终点和路径障碍。请看下面的代码:
```
import heapq
class Node:
def __init__(self, position: tuple[int, int], parent=None):
self.position = position
self.parent = parent
self.g = 0
self.h = 0
self.f = 0
def __eq__(self, other):
return self.position == other.position
def __lt__(self, other):
return self.f < other.f
def astar(maze, start, end):
start_node = Node(start)
end_node = Node(end)
open_list = []
closed_list = set()
heapq.heappush(open_list, start_node)
while open_list:
current_node = heapq.heappop(open_list)
closed_list.add(current_node)
if current_node == end_node:
path = []
while current_node != start_node:
path.append(current_node.position)
current_node = current_node.parent
path.append(start_node.position)
return path[::-1]
neighbors = [(0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1)]
for neighbor in neighbors:
neighbor_position = (current_node.position[0] + neighbor[0], current_node.position[1] + neighbor[1])
if neighbor_position[0] > (len(maze) - 1) or neighbor_position[0] < 0 or neighbor_position[1] > (len(maze[len(maze)-1]) -1) or neighbor_position[1] < 0:
continue
if maze[neighbor_position[0]][neighbor_position[1]] != 0:
continue
neighbor_node = Node(neighbor_position, current_node)
if neighbor_node in closed_list:
continue
neighbor_node.g = current_node.g + 1
neighbor_node.h = ((neighbor_node.position[0] - end_node.position[0]) ** 2) + ((neighbor_node.position[1] - end_node.position[1]) ** 2)
neighbor_node.f = neighbor_node.g + neighbor_node.h
if add_to_open(open_list, neighbor_node):
heapq.heappush(open_list, neighbor_node)
return None
def add_to_open(open_list, neighbor_node):
for node in open_list:
if neighbor_node == node and neighbor_node.f >= node.f:
return False
return True
# 用户输入起点、终点和路径障碍
start_point = tuple(map(int, input("请输入起点坐标(如:1 1):").split()))
end_point = tuple(map(int, input("请输入终点坐标(如:5 5):").split()))
num_obstacles = int(input("请输入路径障碍的数量:"))
obstacles = []
for i in range(num_obstacles):
obstacle = tuple(map(int, input(f"请输入第{i+1}个路径障碍的坐标(如:3 4):").split()))
obstacles.append(obstacle)
# 生成地图
maze = [[0 for x in range(10)] for y in range(10)]
for obstacle in obstacles:
maze[obstacle[0]][obstacle[1]] = 1
# 进行A*搜索
path = astar(maze, start_point, end_point)
# 输出结果
if path is None:
print("没有找到路径")
else:
print("路径为:")
for pos in path:
print(pos)
```
改进后的代码中,通过 `input()` 函数让用户输入起点、终点和路径障碍的坐标,然后根据输入的坐标生成地图。在搜索时,程序会先判断障碍物是否为0,如果不为0则跳过,这样就能实现用户自主输入路径障碍。