1

所以我试图在 9x9 网格上规划一条路径,所以 boardSize 为 9。while 循环应该停止路径列表的长度为 81 或更多,所以为什么当生物在时它可以达到 3531 的长度7,5,目标是 5,2,海拔是 0?我的 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
4

1 回答 1

2

while当路径长度达到棋盘上的方块数时,您希望循环结束 - 使用and而不是or在您的 while 循环中,它将在以下任一表达式结束时结束:

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
于 2013-03-28T07:32:55.377 回答