Ants
This week was invested in a small automaton: Langton's ant, a Turing machine in code.
The idea of the script is simple:
if the square next to the ant is the same colour as the background, do something. If the square is not the same colour, do something else.
These two rules produce very complex outcomes.
Concept
The original Langton's ant can choose between "rotate left", "rotate right", "paint white" or "paint black" before moving onto the next square in its path. The arrangement is:
- If square is black, then paint white and rotate to the right ( W, R )
- If square is white, then paint black and rotate to the left ( B, L )
The ant always moves forward.
Our ant is a little bit special. It can interpret "rotate left", "rotate right", "forward", "back", "pen up" and "pen down", both from programs stored within the code or from commands from the user.
Our ant has the ability to use a set of instructions. There is one set for "equals" and another set for "not equals" - whether the square is the same colour as the background (EQ) or a different one (NEQ) will trigger two different "programs".
The trail left by the ant is the same colour as the ant itself -which can be any of the 16 basic HTML colours- when the "pen" is active. If the "pen" is inactive the trail is the same colour of the canvas, therefore erasing an existing colour tile.
The user interface is quite simple: an array of controls to send instructions to the ant, a button for clearing the screen and another button for saving the contents of the canvas into a PNG file.
The JavaScript code is annotated and most options can be reconfigured - ideally the configuration options should be read and updated from the HTML DOM via Bootstrap, but I will leave this part to your own preferences if you want to extend the code.
Tools
The script uses Bootstrap for visuals, icons and user interface elements, and P5js for the heavy lifting: the code itself, the animation loop and the drawing. I could have used any other JavaScript friendly 2D graphic library, but P5js is good for the job. It also plays nice with both the HTML DOM and with Bootstrap.
This script is released under a [GNU Public License](https://www.gnu.org/licenses/gpl-3.0.html)
"Elegant code does not exist: it either solves a problem or it does not."