0

因此,我尝试更加精通 Python,并决定制作迷宫是一件有趣的事情,知道如何去做。我发现这个页面介绍了一些如何做到这一点。

   create a CellStack (LIFO) to hold a list of cell locations  
   set TotalCells = number of cells in grid  
   choose a cell at random and call it CurrentCell  
   set VisitedCells = 1  

    while VisitedCells < TotalCells 
        find all neighbors of CurrentCell with all walls intact   
        if one or more found 
            choose one at random  
            knock down the wall between it and CurrentCell  
            push CurrentCell location on the CellStack  
            make the new cell CurrentCell  
            add 1 to VisitedCells
        else 
            pop the most recent cell entry off the CellStack  
            make it CurrentCell
        endIf
    endWhile 

现在,我得到了以下代码,尽管它与伪代码中的明显内容相差无几。

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让我陷入了一个循环。

如何检查单元格是否为邻居?

4

1 回答 1

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:看看迷宫算法的惊人集合

于 2012-07-07T20:06:45.963 回答