mornie.org

Generating Maze using Python

Do you like mazes?

eriol@mornie:~$ python maze.py
+--+--+--+--+--+--+--+--+--+--+
|  |           |        |     |
+  +  +  +--+  +  +--+  +  +  +
|  |  |  |     |     |     |  |
+  +  +  +--+--+--+  +--+--+  +
|  |  |     |        |     |  |
+  +  +--+  +  +--+--+  +  +  +
|  |  |  |              |  |  |
+  +  +  +--+--+--+--+--+--+  +
|  |     |     |              |
+  +--+--+  +  +  +--+--+--+  +
|           |     |           |
+--+--+--+--+--+--+--+--+--+--+

After reading this good article, I decided to wrote some code to generate perfect maze. :D

The result is here: maze.py.

As you can see, Depth-First Search is not a complex algorithm:

def create(self):
    cell_stack = []
    while self.visited_cells < self.total_cells:
        neighbors = self.find_neighbors_with_walls(self.current_cell)
        if neighbors:
            new_cell = random.choice(neighbors)
            self.current_cell.destroy_wall(cell=new_cell)
            cell_stack.append(self.current_cell)
            self.current_cell = new_cell
            self.visited_cells += 1
        else:
            self.current_cell = cell_stack.pop()

Comments

comments powered by Disqus