class randomMAP: def init(self,size,start,goal,p): self.size=size self.start=start self.goal=goal self.p=p def creatMAP(self): self.map=np.zeros(self.size,dtype='int') for i in range(self.map.shape[0]): for j in range(self.map.shape[1]): if((i!=self.start[0] or i!=self.start[1]) and (j!=self.goal[0] or j!=self.goal[1])) and random.random() <self.p: self.map[i][j] = 5 map1=randomMAP((20,20),(0,0),(19,19),0.3) map1.creatMAP() plt.matshow(map1.map) plt.show()在这个随机地图的基础上创建Point和Astar类,Point类里面定义初始化、g、h、f和拓展EXPAND函数,Astar类里面用A*算法,最终解决迷宫问题,最后生成可视化地图带有具体路径用红色的线标出
时间: 2024-02-05 16:12:19 浏览: 103
好的,我可以帮你完成这个任务。首先是Point类的实现:
```python
class Point:
def __init__(self, x, y, parent=None):
self.x = x
self.y = y
self.parent = parent
self.g = 0
self.h = 0
self.f = 0
def expand(self, map):
children = []
for dx, dy in [(0, 1), (0, -1), (1, 0), (-1, 0)]:
x2 = self.x + dx
y2 = self.y + dy
if x2 < 0 or x2 >= map.shape[0] or y2 < 0 or y2 >= map.shape[1]:
continue
if map[x2][y2] != 0:
continue
child = Point(x2, y2, self)
children.append(child)
return children
```
这里定义了一个Point类,用来表示地图上的一个点。包括它的坐标、父节点、g值、h值和f值,以及一个expand函数用来拓展这个点的子节点。
接下来是Astar类的实现:
```python
class Astar:
def __init__(self, map, start, goal):
self.map = map
self.start = Point(start[0], start[1])
self.goal = Point(goal[0], goal[1])
self.open = []
self.closed = []
def heuristic(self, p):
return abs(p.x - self.goal.x) + abs(p.y - self.goal.y)
def search(self):
self.open.append(self.start)
while len(self.open) > 0:
current = self.open[0]
if current.x == self.goal.x and current.y == self.goal.y:
path = []
while current.parent is not None:
path.append((current.x, current.y))
current = current.parent
path.append((self.start.x, self.start.y))
path.reverse()
return path
self.open.remove(current)
self.closed.append(current)
for child in current.expand(self.map):
if child in self.closed:
continue
g = current.g + 1
if child not in self.open:
self.open.append(child)
elif g >= child.g:
continue
child.g = g
child.h = self.heuristic(child)
child.f = child.g + child.h
child.parent = current
return None
```
这里定义了一个Astar类,用来实现A*算法。包括地图、起点、终点、open列表、closed列表,以及heuristic函数用来计算当前点到目标点的估价函数。search函数用来进行A*搜索,返回一条路径或者None。
最后是可视化地图的生成:
```python
import matplotlib.pyplot as plt
map1 = randomMAP((20,20),(0,0),(19,19),0.3)
map1.creatMAP()
astar = Astar(map1.map, (0, 0), (19, 19))
path = astar.search()
plt.matshow(map1.map)
if path is not None:
x = [p[0] for p in path]
y = [p[1] for p in path]
plt.plot(y, x, color='red')
plt.show()
```
这里首先生成一个随机地图,然后用Astar算法求解路径,并将路径用红线标出。最后将地图可视化输出。
阅读全文