Langton's Ant

The Langton’s Ant visualisation is produced using the simple set of rules devised by Chris Langton in 1986, in which an ant ‘walks’ on a two-dimensional grid of black and white cells. Within each move or iteration, the ant progresses one step.

  • When reaching a white square, the ant turns 90 degrees, flips the colour of the square to black and progresses one step
  • When reaching a black square, the ant turns 90 degrees in the opposite direction, flips the colour of the square to white, and progresses one step

It is believed that regardless of the direction that the ant starts in, the ant will always emerge onto a ‘highway’ pattern, which is shown in the image above. The concept has been further explored by mathematicians and computer scientists, who have added ant colonies(termites) to produce further complex patterns.

Code

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
boolean AntGrid[][] = new boolean[1080][720];
int AntGridColour[][] = new int[1080][720];
int iterations = 25000;
boolean computefinished;
void setup()
{
  size(1080, 720);
  background(0);
  colorMode(HSB, 360);
  compute();
}
void draw()
{
  if (computefinished == true) {
    for (int i=0; i < 1080; i++) {
      for (int j=0; j < 720; j++) {
        if (AntGrid[i][j] == true)
        {
          stroke(0 + AntGridColour[i][j] * 1.5, AntGridColour[i][j] * 20 + 220, 360);
          point(i, j);
        }
      }
    }
    save("langdon.tif");
  }
}
int x, y;
int Orientation = 1; // North - 1, East - 2, South - 3, West - 4
void compute()
{
  x = 540; 
  y = 360;
  for (int i = 0; i<iterations; i++)
  {
    if (AntGrid[x][y] == false) // Turn 90deg Anticlockwise
    {
      if (Orientation == 4) Orientation = 3;
      else if (Orientation == 1) Orientation = 4;
      else if (Orientation == 2) Orientation = 1;
      else if (Orientation == 3) Orientation = 2;
      AntGrid[x][y] = true;
      AntGridColour[x][y] += 1;
    } else // Turn 90deg Clockwise
    {
      if (Orientation == 1) Orientation = 2;
      else if (Orientation == 2) Orientation = 3;
      else if (Orientation == 4) Orientation = 1;
      else if (Orientation == 3) Orientation = 4;
      AntGrid[x][y] = false;
    }
    // Move forward one block
    if (Orientation == 1) y = y - 1; // Closer to Origin (Top-Left)
    if (Orientation == 2) x = x + 1;
    if (Orientation == 4) x = x - 1;
    if (Orientation == 3) y = y + 1;
  }
  computefinished = true;
}

References

http://mathworld.wolfram.com/LangtonsAnt.html https://en.wikipedia.org/wiki/Langton%27s_ant