Langton's Ants - in Javascript

published on February 26th, 2012 · more from the blog →

Many people will have heard of Conway's Game of Life, a 2D simulation based upon a very simple algorithm that shows incredibly complex behaviour. Langton's Ants (wiki) runs along a similar line, however the rules each "Ant" follow are even simpler, and when combined with multiple Ants they create some impressive patterns.

Each Ant, represented in my version by a red square obeys only 2 rules...

1) At a black square, turn 90° right, flip the colour of the square, move forward one unit.
2) At a green square, turn 90° left, flip the colour of the square, move forward one unit.

These 2 rules on their own will exhibit an identical result each time which. Whilst starting off chaotic, it eventually mutates into a structured "Bridge" as pictured below.

The real amazing part comes when you put 2 or more together, the Ants interact, crossing each others paths and creating a crazy trail. You can even lock 2 or more ants together in a higher-order system that shows some seemingly intelligent behaviour.

What I find so amazing about Langton's Ants is there ability to produce organic looking structures from incredibly simple rules, and I think because you can follow 1 Ants progress you have a connection with the actions, unlike Conway's Game of Life where you are slightly disjointed from the sim.


Pull out the sidebar for some extra controls, its mesmerising to watch.

The Techy Bit

This example is made using Javascript and the Canvas API, pretty simple stuff, you can view source to steal the code should you wish, it's slightly over complicated because I wanted to add the control panel, a lot of it can be stripped down. It's topping out at about 90fps on my machine. Your results may vary, this wasn't really a test of speed because it pretty quickly results in a huge mess of pixels anyway. Just gaze in wonder at the pretty patterns such simple rules bring about.


Just noticed that some old-school browsers don't support some of the features used in this demo, like Range controls and Canvas - try it in Google Chrome / Safari.