Search⌘ K
AI Features

Drawing Polar Grids

Explore how to subclass a grid to design polar grids with Ruby, focusing on rendering circular maze structures. Learn to calculate radii and angles, determine cell coordinates, and draw grid lines to generate visually structured circular mazes.

The PolarGrid class

The to_png method we’ve used up to this point isn’t going to help us much with polar grids, so let’s just subclass Grid and rewrite to_png to be what we need it to be. We'll create a new file named polar_grid.rb. We’ll add the Grid subclass and to_png method to our file.

C++
require 'grid'
class PolarGrid < Grid
def to_png_v1(cell_size: 10)
img_size = 2 * @rows * cell_size
background = ChunkyPNG::Color::WHITE
wall = ChunkyPNG::Color::BLACK
img = ChunkyPNG::Image.new(img_size + 1, img_size + 1, background)
center = img_size / 2
each_cell do |cell|
theta = 2 * Math::PI / @grid[cell.row].length
inner_radius = cell.row * cell_size
outer_radius = (cell.row + 1) * cell_size
theta_ccw = cell.column * theta
theta_cw = (cell.column + 1) * theta
ax = center + (inner_radius * Math.cos(theta_ccw)).to_i
ay = center + (inner_radius * Math.sin(theta_ccw)).to_i
bx = center + (outer_radius * Math.cos(theta_ccw)).to_i
by = center + (outer_radius * Math.sin(theta_ccw)).to_i
cx = center + (inner_radius * Math.cos(theta_cw)).to_i
cy = center + (inner_radius * Math.sin(theta_cw)).to_i
dx = center + (outer_radius * Math.cos(theta_cw)).to_i
dy = center + (outer_radius * Math.sin(theta_cw)).to_i
img.line(ax, ay, cx, cy, wall) unless cell.linked?(cell.north)
img.line(cx, cy, dx, dy, wall) unless cell.linked?(cell.east)
end
img.circle(center, center, @rows * cell_size, wall)
img
end
end

Code explanation

Line 4: This new to_png method starts much like the old version, computing the size of our canvas.

Line 5: In this case, though, ...