2013-03-28 187 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