使用python实现A*算法,要求可以自定义起点、终点,障碍物是随机生成的
时间: 2023-05-25 19:02:32 浏览: 92
以下是一个使用Python实现A*算法的示例程序,其中起点和终点可以自定义,障碍物是随机生成的:
```
import random
import heapq
# 定义节点类
class Node:
def __init__(self, x, y, g=0, h=0, parent=None):
self.x = x
self.y = y
self.g = g
self.h = h
self.f = g + h
self.parent = parent
def __lt__(self, other):
return self.f < other.f
def __eq__(self, other):
return self.x == other.x and self.y == other.y
def __str__(self):
return f"({self.x}, {self.y}): g={self.g}, h={self.h}, f={self.f}"
# 定义地图类
class Map:
def __init__(self, width, height, start, end, obstacles):
self.width = width
self.height = height
self.start = start
self.end = end
self.obstacles = obstacles
def get_neighbors(self, node):
neighbors = []
for dx, dy in [(0, 1), (1, 0), (0, -1), (-1, 0)]:
x, y = node.x + dx, node.y + dy
if 0 <= x < self.width and 0 <= y < self.height and (x, y) not in self.obstacles:
neighbors.append(Node(x, y))
return neighbors
def get_distance(self, node1, node2):
dx = abs(node1.x - node2.x)
dy = abs(node1.y - node2.y)
return dx + dy
def is_obstacle(self, node):
return (node.x, node.y) in self.obstacles
def is_goal(self, node):
return node == self.end
# 定义A*算法类
class AStar:
def __init__(self, map):
self.map = map
def search(self):
start = self.map.start
end = self.map.end
open_set = [Node(start[0], start[1], g=0, h=self.map.get_distance(start, end))]
closed_set = set()
while open_set:
current = heapq.heappop(open_set)
if self.map.is_goal(current):
path = []
while current.parent:
path.append(current)
current = current.parent
path.append(current)
path.reverse()
return path
closed_set.add(current)
for neighbor in self.map.get_neighbors(current):
if neighbor in closed_set or self.map.is_obstacle(neighbor):
continue
g = current.g + self.map.get_distance(current, neighbor)
h = self.map.get_distance(neighbor, end)
f = g + h
if neighbor.f > f or neighbor not in open_set:
neighbor.g = g
neighbor.h = h
neighbor.f = f
neighbor.parent = current
if neighbor not in open_set:
heapq.heappush(open_set, neighbor)
return None
# 随机生成障碍物
def generate_obstacles(width, height):
obstacles = set()
for i in range(int(width * height / 10)):
x = random.randint(0, width - 1)
y = random.randint(0, height - 1)
obstacles.add((x, y))
return obstacles
# 测试程序
width = 20
height = 20
start = (0, 0)
end = (width - 1, height - 1)
obstacles = generate_obstacles(width, height)
map = Map(width, height, Node(*start), Node(*end), obstacles)
search = AStar(map)
path = search.search()
if path:
for node in path:
print(node)
else:
print("No path found")
```
使用示例代码:
```
width = 20
height = 20
start = (0, 0)
end = (width - 1, height - 1)
obstacles = generate_obstacles(width, height)
map = Map(width, height, Node(*start), Node(*end), obstacles)
search = AStar(map)
path = search.search()
if path:
for node in path:
print(node)
else:
print("No path found")
```
该程序将生成一个具有随机障碍物的地图,并使用A *算法搜索从起点到终点的最短路径。如果找到路径,则输出每个节点的详细信息以及路径的总长度。如果找不到路径,则输出“No path found”。
阅读全文