The Buckblog

assorted ramblings by Jamis Buck

Mazes in CoffeeScript

9 February 2011 — The author introduces the code used to write the maze demos for the previous algorithm blog posts — 2-minute read

Several people have asked how I did the Javascript demos in my maze algorithm articles, and while I’ve answered them a couple of times in the comments, I thought it might be interesting enough to warrent its own post.

The demos are actually implemented in CoffeeScript, a really elegant little language that compiles to Javascript. CoffeeScript lets you ignore (most of) Javascript’s warts, while still enjoying all of Javascript’s strengths. I like.

So, the CoffeeScript sources for my maze demos are at https://github.com/jamis/csmazes.

I’ve tried to anticipate most questions about building, installation, and usage in the readme, but in a nutshell:

  1. You’ll need to install CoffeeScript if you want to do anything with the code.
  2. “cake build” will compile the sources to Javascript.
  3. “examples/index.html” has widgets for all the implemented algorithms for you to play with.
  4. “Maze.createWidget” is the quick-and-easy way to embed a maze somewhere.
  5. You can do it the hard way, too, if you need more control: instantiate a maze with the algorithm of your choice, then call Maze#step until the maze is generated (or Maze#generate to do it all at once).

Note that the implementations there are optimized for animating the algorithms; the source code is not a good place to learn how a typical maze implementation might look. Every algorithm is broken down so that it can be called piecewise, one step at a time. If you were going to implement any of these for any “serious” purpose, odds are you’d do it much more efficiently, and without all the ceremony that csMazes requires.

Still, if you just want to embed an animation of a maze algorithm on a web page, csMazes works quite well. Except for IE7. And probably other IE’s as well. (If you’re an IE guru, I’d appreciate patches, but please make sure your fixes don’t impact the animation performance on other browsers. I was able to make IE render the mazes okay, but then the animation performance on Chrome was abyssmal.)

The code is in the public domain, so do with it what you will. If you do something fun with it, let me know!

[Update 2015-01-10] I've updated the csMazes code to include a way to render the mazes using an HTML5 canvas. The older version, using HTML elements and CSS styling, is still supported, but I've updated all the demos on this site to use the new HTML5 canvas rendering instead. It's a lot less fragile!

Reader Comments

Thanks for this post. I was curious to check out your JavaScript for the mazes and I hadn’t been watching the comments to see how you had done it.

CoffeeScript looks pretty cool. I had heard of it before but I hadn’t looked into it until now. It shares a lot of features with Ruby. I’m excited to give it a try!