Search⌘ K
AI Features

Solution: Zeta Mazes

Explore how to implement Zeta mazes by designing the ZetaCell and ZetaGrid classes to manage cell relationships and maze construction. Understand how to handle diagonal neighbor checks, link constraints, and visualize the maze through image generation. This lesson enables you to work with unique grid types and produce visual maze outputs.

We'll cover the following...

Solution

Let's execute the following solution code and see how it works:

C++
require "cell"
require "grid"
require "recursive_backtracker"
class ZetaCell < Cell
#Your code goes here
attr_accessor :nw, :ne, :sw, :se
def neighbors
super.tap do |list|
[ nw, ne, sw, se ].each do |neighbor|
list << neighbor if neighbor && can_link_to?(neighbor)
end
end
end
# this is where we check to see if the shared neighbors are already
# connected diagonally, in which case we disallow a link to the cell.
def can_link_to?(cell)
if north && cell.west == north
!north.linked?(north.se)
elsif north && cell.east == north
!north.linked?(north.sw)
elsif south && cell.west == south
!south.linked?(south.ne)
elsif south && cell.east == south
!south.linked?(south.nw)
else
true
end
end
end
class ZetaGrid < Grid
def prepare_grid
Array.new(rows) do |row|
Array.new(columns) do |col|
ZetaCell.new(row, col)
end
end
end
def configure_cells
each_cell do |cell|
row, col = cell.row, cell.column
cell.north = self[row - 1, col]
cell.south = self[row + 1, col]
cell.west = self[row, col - 1]
cell.east = self[row, col + 1]
cell.nw = self[row - 1, col - 1]
cell.ne = self[row - 1, col + 1]
cell.sw = self[row + 1, col - 1]
cell.se = self[row + 1, col + 1]
end
end
def to_png(cell_size: 10)
# add a margin around the maze, so the lines at the edges
# are easier to see
img_width = cell_size * (columns + 1)
img_height = cell_size * (rows + 1)
background = ChunkyPNG::Color::WHITE
passage = ChunkyPNG::Color::BLACK
img = ChunkyPNG::Image.new(img_width, img_height, background)
each_cell do |cell|
x = (cell.column + 1) * cell_size
y = (cell.row + 1) * cell_size
[ cell.ne, cell.east, cell.se, cell.south ].each do |neighbor|
if cell.linked?(neighbor)
x2 = (neighbor.column + 1) * cell_size
y2 = (neighbor.row + 1) * cell_size
# draw the passage between the two cells as a single line
img.line x, y, x2, y2, passage
end
end
end
img
end
end
grid = ZetaGrid.new(10, 10)
RecursiveBacktracker.on(grid)
img = grid.to_png
img.save "zeta.png"
filename="zeta.png"
grid.to_png.save("/usercode/output/"+filename)

Code explanation

Lines 5–32: We create the ZetaCell class to represent a cell in a grid to determine neighboring cells and to check if a link is allowed. ...