2013-03-28 102 views
1

所以我想计划在9x9的网格中的路径,所以boardSize为9 while循环应停止路径列表中的81的长度以上,为什么是可能的,它可以得到一个的3531when生物长度为7,5和目标是在5,2和立面图是0?我的while循环是错误的还是你认为它可能在别处?无尽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 
+5

我认为你只需要在'while'语句中将'或'更改为'和'。 – Marius 2013-03-28 04:42:06

+1

* *号我怕这将是愚蠢的东西类似的,谢谢。 – EasilyBaffled 2013-03-28 04:51:59

+3

@Marius - 为什么不作为答案发布?与封闭的问题比问题都没有:) – mgilson 2013-03-28 05:48:21

回答

2

你想要的while循环结束的时候,路径长度达到了广场上的板级使用and在while循环会结束时,要么这个表达式的数量,而不是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