2012-07-07 51 views
0

因此,我試圖更加熟練地使用Python,並決定製作一個迷宮將是一件有趣的事情,知道該怎麼做。我找到了this page,它可以幫你完成一些操作。Python中的DFS圖形生成

​​

現在,我已經得到了下面的代碼,雖然它沒有太多的東西在僞代碼中顯而易見。

class Cell: 
    top_wall = 0 
    bottom_wall = 0 
    left_wall = 0 
    right_wall = 0 
    def knock_down(self,wall): 
     if wall is 'top_wall' and self.top_wall is 0: 
      self.top_wall = 1 
     if wall is 'bottom_wall' and self.bottom_wall is 0: 
      self.bottom_wall = 1 
     if wall is 'left_wall' and self.left_wall is 0: 
      self.left_wall = 1 
     if wall is 'right_wall' and self.right_wall is 0: 
      self.right_wall = 1 
     else 
      return 'Error: Wall Already Gone' 

maze = [10][10] 
CellStack = []   # LIFO stack to hold list of cell locations 
TotalCells = 100  # Number of cells in grid 
VisitedCells = 0  # Cells that have been visited 
CurrentCell = 0   # The current cell 

while VisitedCells < TotalCells: 

我不知道這個類是做電池的最佳方式,但我沒有想到的另一種方式來做到這一點呢。但是,我檢查一個單元的鄰居遇到了一些問題。 find all neighbors of CurrentCell with all walls intact扔了我一個循環。

如何檢查單元格是否是鄰居?

回答

1

您可以給每個單元格一個位置,存儲爲兩個整數。然後,如果這些整數是鄰居,則兩個單元是鄰居。

def isCellNeighbor(c1, c2): 
    if abs(c1.x - c2.x) == 1: return True 
    if abs(c1.y - c2.y) == 1: return True 
    return False 

上面將兩個單元看作是鄰居,如果每個單元的至少一個角落接觸另一個。你可以調整它以適應你的需求。

PS:看看the amazing collection of maze algorithms

+0

我說,出現這種情況的答案:) – 2012-07-07 20:13:14

+0

對不起,我也許應該學會閱讀:) – senderle 2012-07-07 20:19:44