修改以下代码,使他避开障碍物:def Astar(Map): s = Point(Map.start, None, None) openlist = [s] closedlist = [] s.get_f(Map.goal) while openlist: n = openlist.pop(0) if n.position[0] == Map.goal[0] and n.position[1] == Map.goal[1]: return n else: closedlist.append(n) subp_list = Point.EXPAND(n, Map) for subp in subp_list: subp.get_f(Map.goal) for openp in openlist: if openp.position[0] == subp.position[0] and openp.position[1] == subp.position[1]: if subp.f < openp.f: openlist.remove(openp) openlist.append(subp) for closedp in closedlist: if closedp.position[0] == subp.position[0] and closedp.position[1] == subp.position[1]: if subp.f < closedp.f: closedlist.remove(closedp) openlist.append(subp) openlist.append(subp) openlist.sort(key= lambda x:x.f)
时间: 2024-01-22 09:17:28 浏览: 77
Sure, here's the modified code that avoids obstacles using A* algorithm:
```
def Astar(Map):
s = Point(Map.start, None, None)
openlist = [s]
closedlist = []
s.get_f(Map.goal)
while openlist:
n = openlist.pop(0)
if n.position[0] == Map.goal[0] and n.position[1] == Map.goal[1]:
return n
else:
closedlist.append(n)
subp_list = Point.EXPAND(n, Map)
for subp in subp_list:
if Map.is_obstacle(subp.position[0], subp.position[1]):
continue
subp.get_f(Map.goal)
for openp in openlist:
if openp.position[0] == subp.position[0] and openp.position[1] == subp.position[1]:
if subp.f < openp.f:
openlist.remove(openp)
openlist.append(subp)
break
else:
for closedp in closedlist:
if closedp.position[0] == subp.position[0] and closedp.position[1] == subp.position[1]:
if subp.f < closedp.f:
closedlist.remove(closedp)
openlist.append(subp)
break
else:
openlist.append(subp)
openlist.sort(key=lambda x: x.f)
```
The modification is done by adding a check for obstacles in the sub-points list and skipping those points, as well as updating the open and closed lists based on the new condition.
阅读全文