我很难跟踪由getAdjacentTiles(..)
. 我在下面确定了我的 A* 实现的性能问题是我没有跟踪以前看到的图块,每次调用都getAdjacentTiles
返回新图块(Node
's)而不是openSet
or中的任何图块closedSet
。我决定使用 Node 对象列表作为迄今为止创建的所有图块,并将其传递给它getAdjacentTiles
以确定它生成的图块是否已经被访问过。
我的问题是,我似乎无法正确跟踪这些图块。每当我的 A* 需要采取超过 4 次以上的动作才能到达end
它的位置时。我确信这与我如何尝试跟踪瓷砖(再次Node
被访问过的瓷砖).apped(tile)
有关getAdjacentTiles(...)
当循环通过allTiles
集合?
产生的错误(有时,仅当 A* 路径长于大约 3 步时..)
File "P3.py", line 67, in aStar
openSet.remove(curNode)
KeyError: <__main__.Node instance at 0xa39edcc>
资源
#Perform an A* search to find the best path to the dirt
def aStar(self, current, end):
openSet = set()
openHeap = []
closedSet = set()
allTiles = set()
curNode = Node(0, current, self.manHatDist(current, end))
openSet.add(curNode)
allTiles.add(curNode)
openHeap.append((curNode.cost,curNode))
while openSet:
curNode = heapq.heappop(openHeap)[1]
if curNode.pos == end:
return self.getDirections(curNode)
openSet.remove(curNode)
closedSet.add(curNode)
adjNodes = self.getAdjacentNodes(curNode.pos, allTiles)
for tile in adjNodes:
t = tile
if t not in closedSet:
cost = (curNode.cost - self.manHatDist(curNode.pos, end)
+ self.euclidDist(curNode.pos, current)
+ self.manHatDist(t.pos, end))
if t not in openSet or cost < t.cost:
t.parent = curNode
t.cost = cost
openSet.add(t)
heapq.heappush(openHeap, (cost,t))
allTiles.add(t)
return []
#Get the moves made to get to this endNode
def getDirections(self, endNode):
moves = []
tmpNode = endNode
while tmpNode.parent is not None:
moves.append(tmpNode.value)
tmpNode = tmpNode.parent
moves.reverse()
return moves
#Return all possible moves from given tile as Node objects
def getAdjacentNodes(self, curPos, allTiles):
allMoves = ['North','South','East','West']
posMoves = []
for direction in allMoves:
if(self.canMove(direction, curPos)):
posMoves.append(Node(direction, self.getLocIfMove(curPos, direction)))
retNodes = []
for posLocNode in posMoves:
set = False
for tile in allTiles:
if(posLocNode.pos == tile.pos):
set = True
retNodes.append(tile)
if(not set):
retNodes.append(posLocNode)
return retNodes