Coloring Our Mazes

Learn how to create colored mazes.

Introducing colors to our grids

It turns out that coloring mazes in a particular way acts like an X-ray machine, letting us peer inside and get a much clearer view of the structure of a maze and the algorithm that generated it. Dijkstra’s algorithm is ideal for this because of the matrix of numbers it generates. Every cell with the same distance value has one thing in common: they all are equidistant from the starting cell. This just needs a paint-by-number exercise.

The easiest way to do this is to treat each number as an intensity value relative to the length of the longest path. It works even better if we invert the logic too, treating the cells with the largest distance values as the darkest and the cell that we started with (which has a distance of zero) as the lightest.

To make this work, we’ll need to visit our Grid class again, tweaking the to_png implementation to support coloring the cells. We’ll do what we did for to_s and generalize it a bit. We’ll add a background_color_for(cell) method, which will return a color value and to_png will call that for each cell. Subclasses may override background_color_for to implement their own coloring rules.

We’ll make the following changes, starting with adding our new background_color_for(cell) method in grid.rb. We'll put it just after the contents_of method since the two have similar responsibilities.

Get hands-on with 1200+ tech skills courses.