Search⌘ K
AI Features

Displaying Colored Mazes

Explore how to subclass a Grid to create a ColoredGrid that uses Dijkstra's algorithm for coloring mazes. Understand how to assign colors based on cell distances to visually compare maze algorithms and reveal maze structures through color gradients.

The ColoredGrid class

Now we can subclass Grid and create a ColoredGrid class, which will implement our Dijkstra-based coloring rules. The code is shown below:

C++
require 'grid'
require 'chunky_png'
class ColoredGrid < Grid
def distances=(distances)
@distances = distances
farthest, @maximum = distances.max
end
def background_color_for(cell)
distance = @distances[cell] or return nil
intensity = (@maximum - distance).to_f / @maximum
dark = (255 * intensity).round
bright = 128 + (127 * intensity).round
ChunkyPNG::Color.rgb(dark, bright, dark)
end
end

Code explanation

Lines 5–8: Our subclass implements a writer method that we’ll call distances=(distances). The distances= method simply stores the distances mapping and caches the mapping’s largest distance value as @maximum.

Line 10: Our subclass also implements the method: background_color_for(cell).

Lines 12–14: ...