pyamaze迷宫将起点改左上终点改右下的代码修改方法
修改方案
你只需要修改现有代码的3处核心位置即可实现起点终点调换:
1. 修改UCS函数默认起点为左上角
找到UCS函数内的起点默认赋值逻辑,将原来的右下角坐标改成左上角坐标(1,1):
# 修改前 if start is None: start=(m.rows,m.cols) # 修改后 if start is None: start=(1,1)
2. 修改迷宫终点为右下角
调用CreateMaze方法时新增goal参数,指定终点为右下角坐标:
# 修改前 myMaze.CreateMaze(loadMaze='maze--2021-11-12--21-36-39.csv') # 修改后 myMaze.CreateMaze(loadMaze='maze--2021-11-12--21-36-39.csv', goal=(myMaze.rows, myMaze.cols))
3. 修改智能体初始位置为左上角
创建agent时显式指定起点坐标,让寻路动画从左上角开始展示:
# 修改前 a=agent(myMaze,color=COLOR.cyan,filled=True,footprints=True,) # 修改后 a=agent(myMaze, 1, 1, color=COLOR.cyan,filled=True,footprints=True)
完整修改后代码
from pyamaze import maze,agent,COLOR,textLabel from timeit import timeit def UCS(m,*h,start=None): if start is None: start=(1,1) hurdles=[(i.position,i.cost) for i in h] unvisited={n:float('inf') for n in m.grid} unvisited[start]=0 visited={} revPath={} while unvisited: currCell=min(unvisited,key=unvisited.get) visited[currCell]=unvisited[currCell] if currCell==m._goal: break for d in 'EWNS': if m.maze_map[currCell][d]==True: if d=='E': childCell=(currCell[0],currCell[1]+1) elif d=='W': childCell=(currCell[0],currCell[1]-1) elif d=='S': childCell=(currCell[0]+1,currCell[1]) elif d=='N': childCell=(currCell[0]-1,currCell[1]) if childCell in visited: continue tempDist= unvisited[currCell]+1 for hurdle in hurdles: if hurdle[0]==currCell: tempDist+=hurdle[1] if tempDist < unvisited[childCell]: unvisited[childCell]=tempDist revPath[childCell]=currCell unvisited.pop(currCell) fwdPath={} cell=m._goal while cell!=start: fwdPath[revPath[cell]]=cell cell=revPath[cell] return fwdPath,visited[m._goal] if __name__=='__main__': myMaze=maze(10,10) myMaze.CreateMaze(loadMaze='maze--2021-11-12--21-36-39.csv', goal=(myMaze.rows, myMaze.cols)) # myMaze.CreateMaze(loadMaze='dijkMaze.csv', goal=(myMaze.rows, myMaze.cols)) # h1=agent(myMaze,4,4,color=COLOR.red) # h2=agent(myMaze,4,6,color=COLOR.red) # h3=agent(myMaze,4,1,color=COLOR.red) # h4=agent(myMaze,4,2,color=COLOR.red) # h5=agent(myMaze,4,3,color=COLOR.red) # h1.cost=100 # h2.cost=100 # h3.cost=100 # h4.cost=100 # h5.cost=100 # path,c=dijstra(myMaze,h1,h2,h2,h3,h4,h5) # path,c=dijkstra(myMaze,h1,h2,h3,h4,h5,start=(6,1)) path,c=UCS(myMaze) textLabel(myMaze,'Total Cost',c) a=agent(myMaze,1,1,color=COLOR.cyan,filled=True,footprints=True) # a=agent(myMaze,6,1,color=COLOR.cyan,filled=True,footprints=True) myMaze.tracePath({a:path},delay=20) t1=timeit(stmt='UCS(myMaze)',number=100,globals=globals()) textLabel(myMaze,'UCS Time',t1) myMaze.run()
内容的提问来源于stack exchange,提问作者Promise89
相关产品推荐
相关产品推荐

