所以我试图在一个9x9的网格上规划一条路径,所以boardSize是9。while循环应该停止路径列表的长度是81或更多,那么当生物在7,5,目标在5,2,海拔为0时,为什么它可以达到3531的长度?是我的while循环出错了,还是你觉得它可能在别的地方?
def planPath(self, creature, goal, board):
print("in the path")
path = [board[creature.x][creature.y]]
while goal not in path or len(path) < self.boardSize ** 2:
print("path length")
print(len(path))
nextPossible = {}
for neighbor in path[-1].neighbors:
if type(neighbor) is not Land.Water:
nextPossible[neighbor] = abs(neighbor.location[0] - goal.location[0]) + abs(neighbor.location[1] - goal.location[1]) + abs(neighbor.elevation - goal.elevation)
path.append(min(nextPossible, key=nextPossible.get))
return path
发布于 2013-03-28 15:32:55
您希望在路径长度达到棋盘上的正方形数量时结束while
循环-在while循环中使用and
而不是or
,它将在以下两个表达式之一时结束:
goal not in path
或者这个表达式:
len(path) < self.boardSize ** 2
计算结果为False
。使用or
,只要其中一个表达式为真,循环就会继续运行。因此,您的修复代码将是:
def planPath(self, creature, goal, board):
print("in the path")
path = [board[creature.x][creature.y]]
while goal not in path and len(path) < self.boardSize ** 2:
print("path length")
print(len(path))
nextPossible = {}
for neighbor in path[-1].neighbors:
if type(neighbor) is not Land.Water:
nextPossible[neighbor] = abs(neighbor.location[0] - goal.location[0]) + abs(neighbor.location[1] - goal.location[1]) + abs(neighbor.elevation - goal.elevation)
path.append(min(nextPossible, key=nextPossible.get))
return path
https://stackoverflow.com/questions/15674410
复制相似问题