【发布时间】:2011-05-08 17:49:56
【问题描述】:
我编写了我的第一个稍微复杂的算法,即A Star Pathfinding 算法的实现。我在实现图表时遵循了一些Python.org advice,因此字典包含每个节点也链接的所有节点。现在,由于这一切都是为了游戏,每个节点实际上只是节点网格中的一个图块,因此我正在制定启发式方法并偶尔引用它们。
感谢 timeit,我知道我可以每秒成功运行此功能一百多次。可以理解的是,这让我有点不安,因为没有任何其他“游戏内容”,比如图形或计算游戏逻辑。所以我很想看看你们中是否有人可以加快我的算法,我完全不熟悉 Cython 或它的亲戚,我不会编写一行 C。
废话不多说,这是我的A Star函数。
def aStar(self, graph, current, end):
openList = []
closedList = []
path = []
def retracePath(c):
path.insert(0,c)
if c.parent == None:
return
retracePath(c.parent)
openList.append(current)
while len(openList) is not 0:
current = min(openList, key=lambda inst:inst.H)
if current == end:
return retracePath(current)
openList.remove(current)
closedList.append(current)
for tile in graph[current]:
if tile not in closedList:
tile.H = (abs(end.x-tile.x)+abs(end.y-tile.y))*10
if tile not in openList:
openList.append(tile)
tile.parent = current
return path
【问题讨论】:
-
while len(openList) is not 0:让我畏缩......while openlist:也一样。 -
return retracePath(current)这行不正确(我认为),你应该调用retracePath(current),然后return path当前如果找到结束节点,它返回None
标签: python algorithm performance a-star