Implementing the Binary Tree Algorithm

Let’s start with the Binary Tree algorithm. As you’ll recall from The Binary Tree Algorithm, it works simply by visiting each cell in the grid and choosing to carve a passage either north or east.

The following code does just that. We’re going to put it in its own class so that we can easily reuse this code whenever we want. Save it to a file named binary_tree.rb, and make sure it’s in the same directory as the cell.rb and grid.rb files we created earlier.

binary_tree.rb
Line 1 
class​ BinaryTree
def​ self.on(grid)
grid.each_cell ​do​ |cell|
neighbors = []
neighbors << cell.north ​if​ cell.north
neighbors << cell.east ​if​ cell.east
index = rand(neighbors.length)
10 
neighbor ...

Get Mazes for Programmers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.