Solution: Shuffled 2D Mazes
Understand the solution to the “Shuffled 2D Mazes” challenge.
We'll cover the following...
We'll cover the following...
Solution
Let's execute the following solution code and see how it works:
Press + to interact
C++
require 'grid'require 'recursive_backtracker'BACKGROUND = ChunkyPNG::Color::WHITEWALL = ChunkyPNG::Color::BLACKCOLORS = %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 * 2img_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.shufflecolors = COLORS.shufflegrid.rows.times do |row|y = gap + positions[row] * (cell_size + gap)# big circle on the left showing the color of this rowcolor = colors[positions[row]]img.circle(gap + cell_size / 2, y + cell_size / 2, cell_size * 0.3, color, color)# the rectangle outlining this rowimg.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_sizecell = grid[row, col]x0 = x + cell_size * 0.5y0 = y + cell_size * 0.25r = cell_size * 0.1# draw a wall to the east if the cell isn't linked to its eastern# neighborif cell.east && !cell.linked?(cell.east)img.line(x + cell_size, y+1, x + cell_size, y + cell_size-1, WALL)endif cell.linked?(cell.north)target = colors[positions[cell.north.row]]img.circle(x0, y0, r, target, target)y0 += cell_size * 0.5endif cell.linked?(cell.south)target = colors[positions[cell.south.row]]img.circle(x0, y0, r, target, target)endendendimgendgrid = 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