Langton's ant is a cellular automaton that models an ant sitting on a plane of cells, all of which are white initially, the ant facing in one of four directions.

Each cell can either be black or white.

The ant moves according to the color of the cell it is currently sitting in, with the following rules:

   If the cell is black, it changes to white and the ant turns left;
   If the cell is white, it changes to black and the ant turns right;
   The ant then moves forward to the next cell, and repeat from step 1.

This rather simple ruleset leads to an initially chaotic movement pattern, and after about 10000 steps, a cycle appears where the ant moves steadily away from the starting location in a diagonal corridor about 10 cells wide.
Conceptually the ant can then walk infinitely far away.



Task

Start the ant near the center of a 100x100 field of cells, which is about big enough to contain the initial chaotic part of the movement.

Follow the movement rules for the ant, terminate when it moves out of the region, and show the cell colors it leaves behind.



The problem has received some analysis; for more details, please take a look at the Wikipedia article   (a link is below)..



See also

   Wikipedia:   Langton's ant.


Related task

   Rosetta Code:   Conway's Game of Life.


DEFINE DIRN="0"
DEFINE DIRE="1"
DEFINE DIRS="2"
DEFINE DIRW="3"
DEFINE BLACK="1"
DEFINE WHITE="2"
DEFINE MAXX="159"
DEFINE MAXY="95"
 
BYTE FUNC TurnLeft(BYTE dir)
  IF dir=DIRN THEN
    RETURN (DIRW)
  FI
RETURN (dir-1)
 
BYTE FUNC TurnRight(BYTE dir)
  IF dir=DIRW THEN
    RETURN (DIRN)
  FI
RETURN (dir+1)
 
PROC DrawAnt(INT x,y)
  BYTE c,dir
 
  dir=DIRN
 
  DO
    c=Locate(x,y)
 
    IF c=BLACK THEN
      Color=WHITE
      Plot(x,y)
      dir=TurnLeft(dir)
    ELSE
      Color=BLACK
      Plot(x,y)
      dir=TurnRight(dir)
    FI
    IF dir=DIRN THEN
      y==-1
      IF y<0 THEN EXIT FI
    ELSEIF dir=DIRE THEN
      x==+1
      IF X>MAXX THEN EXIT FI
    ELSEIF dir=DIRS THEN
      y==+1
      IF Y>MAXY THEN EXIT FI
    ELSE
      x==-1
      IF x<0 THEN EXIT FI
    FI
  OD
RETURN
 
PROC Main()
  BYTE CH=$02FC
  BYTE y
 
  Graphics(7+16)
  SetColor(0,0,2)
  SetColor(1,0,12)
  Color=2
  FOR y=0 TO MAXY
  DO
    Plot(0,y) DrawTo(MAXX,y)
  OD
 
  DrawAnt(80,48)
 
  DO UNTIL CH#$FF OD
  CH=$FF
RETURN