利用Python写一个代码,要求随机生成障碍物的概率为0.3的20*20的地图,先生成地图,再利用Astar算法进行寻路
时间: 2024-02-03 22:14:03 浏览: 119
以下是一个示例代码,其中包含地图生成和A*算法的实现:
```python
import random
# 定义地图大小
MAP_SIZE = 20
# 定义障碍物概率
OBSTACLE_PROBABILITY = 0.3
# 定义地图中的符号
SYMBOL_EMPTY = '-'
SYMBOL_OBSTACLE = 'X'
SYMBOL_START = 'S'
SYMBOL_END = 'E'
SYMBOL_PATH = '*'
# 定义节点类
class Node:
def __init__(self, x, y):
self.x = x
self.y = y
self.parent = None
self.g = 0
self.h = 0
self.f = 0
def __eq__(self, other):
return self.x == other.x and self.y == other.y
# 定义A*算法函数
def astar(start, end, map):
open_list = [start]
closed_list = []
while len(open_list) > 0:
current_node = open_list[0]
current_index = 0
# 找到f值最小的节点
for index, node in enumerate(open_list):
if node.f < current_node.f:
current_node = node
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)
current = current.parent
return path[::-1]
# 获取当前节点的相邻节点
neighbors = []
for new_x, new_y in [(0, -1), (0, 1), (-1, 0), (1, 0)]:
node_x = current_node.x + new_x
node_y = current_node.y + new_y
if node_x < 0 or node_x >= MAP_SIZE or node_y < 0 or node_y >= MAP_SIZE:
continue
if map[node_x][node_y] == SYMBOL_OBSTACLE:
continue
new_node = Node(node_x, node_y)
new_node.g = current_node.g + 1
new_node.h = ((new_node.x - end.x) ** 2) + ((new_node.y - end.y) ** 2)
new_node.f = new_node.g + new_node.h
new_node.parent = current_node
neighbors.append(new_node)
# 处理相邻节点
for neighbor in neighbors:
if neighbor in closed_list:
continue
if neighbor.f > 1000000:
continue
if neighbor in open_list:
index = open_list.index(neighbor)
if open_list[index].g > neighbor.g:
open_list[index].g = neighbor.g
open_list[index].parent = current_node
else:
open_list.append(neighbor)
return None
# 生成地图
map = [[SYMBOL_EMPTY for x in range(MAP_SIZE)] for y in range(MAP_SIZE)]
for x in range(MAP_SIZE):
for y in range(MAP_SIZE):
if random.uniform(0, 1) < OBSTACLE_PROBABILITY:
map[x][y] = SYMBOL_OBSTACLE
# 随机选择起点和终点
start_x, start_y = random.randint(0, MAP_SIZE-1), random.randint(0, MAP_SIZE-1)
end_x, end_y = random.randint(0, MAP_SIZE-1), random.randint(0, MAP_SIZE-1)
while map[start_x][start_y] == SYMBOL_OBSTACLE or map[end_x][end_y] == SYMBOL_OBSTACLE:
start_x, start_y = random.randint(0, MAP_SIZE-1), random.randint(0, MAP_SIZE-1)
end_x, end_y = random.randint(0, MAP_SIZE-1), random.randint(0, MAP_SIZE-1)
# 标记起点和终点
map[start_x][start_y] = SYMBOL_START
map[end_x][end_y] = SYMBOL_END
# 输出地图
for row in map:
print(' '.join(row))
# 寻找最短路径
start_node = Node(start_x, start_y)
end_node = Node(end_x, end_y)
path = astar(start_node, end_node, map)
# 标记路径
if path is not None:
for node in path:
map[node.x][node.y] = SYMBOL_PATH
# 输出地图和路径
print('---')
for row in map:
print(' '.join(row))
```
该代码将生成一个20x20的地图,并随机在地图上放置障碍物。然后,代码会随机选择起点和终点,并使用A*算法寻找它们之间的最短路径。最后,代码会在地图上标记路径,并输出地图和路径。
阅读全文