2016-03-30 32 views
0

所以我有一個astar算法,在迷宮中輸出路徑。但是我只想要節點(表示爲元組(行,列)),你在迷宮中實際轉向。如何只輸出迷宮路徑的轉折點

Ex。

path = [(10,0),(10,1),(9,1),(8,1),(8,2),(8,3),(7,3)] #given from astar alg 
path = [(10,0),(10,1),(8,1),(8,3),(7,3)] #desired output 

這裏是我的代碼的一部分:

for node in self.path: 
      direction1 = (self.path[node][0] - self.path[node+1][0], self.path[node][1] - self.path[node+1][1]) 
      direction2 = (self.path[node+1][0] - self.path[node+2][0], self.path[node+1][1] - self.path[node+2][1]) 
      if direction1 == direction2: 
       self.path.pop([node+1]) 
      elif direction1 == None: 
       pass 
      else: 
       pass 
+0

你得到一個錯誤?如果是這樣的錯誤是什麼? –

+0

實際上,我可以看到很多錯誤的代碼,你用'node'作爲指令,在迭代時彈出列表的元素,而且你不檢查你是否在列表尚未如此'self.path [node + 1]'可能會引發'IndexError'。 –

+0

是的,出於某種原因,它不會給我一個錯誤,但你是對的:我沒有考慮到這一點。 – Curious

回答

0

超過self.path使用索引來遍歷:

for node in range(len(self.path)): 

但因爲要停止月底前檢查2(SO該self.path[node+2]將始終有效)只需使用:

for node in range(0,len(self.path)-2): 

無論哪種方式,刪除該路徑的元素,你遍歷它可能會引起問題,所以我建議你再建設新路徑換舊人:

new_path = [self.path[0]] #keep the first element since it will always be needed 
for node in range(0,len(self.path)-2): 
    direction1 = (self.path[node][0] - self.path[node+1][0], self.path[node][1] - self.path[node+1][1]) 
    direction2 = (self.path[node+1][0] - self.path[node+2][0], self.path[node+1][1] - self.path[node+2][1]) 
    if direction1 != direction2: 
     new_path.append(self.path[node+1]) 
new_path.append(self.path[-1]) #add in the last element 
self.path = new_path 

但這也許更令人困惑,因爲你必須處理node+1更多的則node所以你可能想在1指數之開始和結束len(self.path)-1,因此會使用:

new_path = [self.path[0]] #keep the first element since it will always be needed 
for node in range(1,len(self.path)-1): 
    direction1 = (self.path[node-1][0] - self.path[node][0], self.path[node-1][1] - self.path[node][1]) 
    direction2 = (self.path[node][0] - self.path[node+1][0], self.path[node][1] - self.path[node+1][1]) 
    if direction1 != direction2: 
     new_path.append(self.path[node]) 
new_path.append(self.path[-1]) #add in the last element 
self.path = new_path 
+0

謝謝!這太棒了。 – Curious