Tower of Hanoi

I figured I'd start with something classic.

If you don't see anything in the frame above, then either your browser doesn't support WebGL, or your graphics driver is not sufficient for initializing a WebGL context.

The source code is available on GitHub.

It works by generating the optimal solution using the common recursive algorithm. It then walks through each step in the solution sequence, shifting disks from peg to peg in order to give a human-friendly visual. It can generate the solution and display it for any number of starting disks. The number of disks to use is passed as an argument to the Hanoi() constructor.

The generated solution for three disks looks like this:

[[0, 2], [0, 1], [2, 1], [0, 2], [1, 0], [1, 2], [0, 2]]

It's organized into steps, where each array element consists of a source peg and destination peg. So the first step says to move the top-most disk of peg 0 to peg 2, and the second step says to move the top disk of peg 0 to peg 1, etc.. If all of the steps in the sequence were completed, then the disks would be left correctly stacked on top of peg 2.

If you run your browser's JavaScript console (Ctrl+Shift+K in Firefox, Ctrl+Shift+J in Chromium) and then refresh this page, you can inspect the generated solution array, which is logged after the algorithm completes and before the disks start visually shifting from peg to peg.

The graphics are provided by WebGL via IvanK.js and Tweener. IvanK.js is really nice because it abstracts a lot of entity management out of the way, providing lots of conveniences that the Flash API makes available without any of the proprietary garbage attached. Very fun and suitable for fast WebGL games and interactive prototypes!