...

/

Solution: Shuffled 2D Mazes

Solution: Shuffled 2D Mazes

Understand the solution to the “Shuffled 2D Mazes” challenge.

We'll cover the following...

Solution

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

Press + to interact
require 'grid'
require 'recursive_backtracker'
BACKGROUND = ChunkyPNG::Color::WHITE
WALL = ChunkyPNG::Color::BLACK
COLORS = %w( black gray red orange green blue lightblue purple )
.map { |name| ChunkyPNG::Color(name) }
def shuffle_render(grid, cell_size: 60, gap: 10)
img_width = cell_size * (grid.columns + 1) + gap * 2
img_height = cell_size * grid.rows + gap * (grid.rows + 1)
img = ChunkyPNG::Image.new(img_width + 1, img_height + 1, BACKGROUND)
# shuffle the row positions; positions[i] tells the actual vertical
# position of row i.
positions = (0...grid.rows).to_a.shuffle
colors = COLORS.shuffle
grid.rows.times do |row|
y = gap + positions[row] * (cell_size + gap)
# big circle on the left showing the color of this row
color = colors[positions[row]]
img.circle(gap + cell_size / 2, y + cell_size / 2, cell_size * 0.3, color, color)
# the rectangle outlining this row
img.rect(gap + cell_size, y, gap + cell_size * (grid.columns + 1), y + cell_size, WALL, BACKGROUND)
grid.columns.times do |col|
x = gap + (col + 1) * cell_size
cell = grid[row, col]
x0 = x + cell_size * 0.5
y0 = y + cell_size * 0.25
r = cell_size * 0.1
# draw a wall to the east if the cell isn't linked to its eastern
# neighbor
if cell.east && !cell.linked?(cell.east)
img.line(x + cell_size, y+1, x + cell_size, y + cell_size-1, WALL)
end
if cell.linked?(cell.north)
target = colors[positions[cell.north.row]]
img.circle(x0, y0, r, target, target)
y0 += cell_size * 0.5
end
if cell.linked?(cell.south)
target = colors[positions[cell.south.row]]
img.circle(x0, y0, r, target, target)
end
end
end
img
end
grid = Grid.new(5, 5)
RecursiveBacktracker.on(grid)
img = shuffle_render(grid)
img.save("/usercode/output/"+'1.png')
grid.to_png.save("/usercode/output/"+'2.png')

Code explanation

Line 17: We shuffle the row positions using the shuffle method and store the shuffled positions in the positions array. This determines the vertical position of each row in the image.

Line 21: We calculate the ...