Rendering a Maze as an Image

Why should we render mazes as PNG images?

ASCII art is undeniably functional, but not necessarily attractive. Often, we want our products to have a bit more polish. Fortunately, APIs are available for most languages for either drawing directly to a view or (at the very least) rendering to an offscreen canvas and saving it as an image file. We’ll explore the latter of those techniques with a Ruby library called ChunkyPNG (we don't have to worry about installing it as it's already available on our platform), which will let us write our mazes as PNG images. (The concepts can be translated readily to other UI and graphics APIs.)

Just as we used the to_s method to render the textual representation of the maze, we’ll introduce a to_png method on Grid to give us a graphical representation. The first half of it is just setup, computing the dimensions of our image and instantiating our canvas. The second half is where the actual process takes place; it’s really not too different from what we did to write our maze to a terminal.

We'll go ahead and make changes to grid.rb. At the very top of the file, we'll add the following line to make sure the ChunkyPNG library gets loaded.

Get hands-on with 1400+ tech skills courses.