Langton's Ant
Langton's Ant is a cellular automation invented by Christ Langton.
Langton's Ant is interesting because its very simple set of rules can lead to very complex emergent behavior. The simulation deals with computerized "ants" whose movements are controlled by a set of rules decided by the user
The rules
There's a grid and an ant. Each cell on the grid is either white or black.
At every step:
- If the ant is on a white cell: turn right, flip the cell to black, move forward.
- If the ant is on a black cell: turn left, flip the cell to white, move forward.
Generalising it
Give each cell a state from 0 to N. Assign each state a turn direction — left or right. At each step, turn according to the current cell's rule, increment the cell's state (wrapping back to 0 after N), and move forward.
So LR is the classic ant, and for ex. LRRL gives you four states. You can check out some cool rules on : https://langtonsant.es/db/rules.
The implementation
The grid state is stored as a flat Uint8Array — one byte per cell, value = current state index. It's simple and fast enough to run moderately sized simulations, for bigger, more efficient simulations, check out the link at langtonsant.es above.
const step = function(ant) {
const i = ant.y * WIDTH + ant.x;
const turn = rules[pixels[i]] === 'R' ? 1 : 3;
ant.dir = (ant.dir + turn) % 4;
pixels[i] = (pixels[i] + 1) % rules.length;
draw(ant.x, ant.y, pixels[i]);
if (ant.dir === 0) ant.y--;
else if (ant.dir === 1) ant.x++;
else if (ant.dir === 2) ant.y++;
else ant.x--;
}
Turning right is +1 mod 4, turning left is +3 mod 4. The cell state increments and wraps. That's the whole simulation.
Colours are assigned by evenly spacing hue values around the HSL wheel, or as a greyscale gradient from black to white depending on the mode.
Try it
You can play with it here. Change the rule string, however you want. LRRL, LLRR, RLLR are good starting points.