GameGrid: Game programming with Java

Research project PHBern  
HomePrintJava-Online

Langton's Ant simulation


Christopher Langton is a co-founder of the research area "artificial live", which deals with the simulation of living creatures. His ant simulation is a perfect example to show that a chaotic system can lead to a well-structured one.

The system follows this algorithm:
An ant is on a white grid and moves upward. As soon as it hits a new cell the following rules apply:

  • if the cell is white, the ant colors it black and rotates 90 degrees to the right
  • if the cell is black, the ant colors it white and rotates 90 degrees to the left

After that, the ant moves to the next cell according to its new direction.

 

Run this example

Edit this example in the Online-Editor

 

Program code

// Langton.java

import ch.aplu.jgamegrid.*;
import java.awt.Color;

public class Langton extends GameGrid
{
  private final Actor ant = new Actor(true"sprites/ant.gif");
  private final String title = "JGameGrid - Langton's Ant. # Steps: ";

  public Langton()
  {
    super(1001006new Color(240240240)true);
    setSimulationPeriod(10);
    setBgColor(Color.white);
    addActor(ant, new Location(5050)-90);
    reset();
    show();
  }
  
  public void reset()
  {
    getBg().clear();
    setTitle(title + getNbCycles());
  }

  public void act()
  {
    setTitle(title + (getNbCycles() + 1));
    Location loc = ant.getLocation();
    GGBackground bg = getBg();
    Color c = bg.getColor(loc);
    if (c.equals(Color.white))
    {
      bg.fillCell(loc, Color.black, false);
      ant.setDirection(ant.getDirection() + 90);
    }
    else
    {
      bg.fillCell(loc, Color.white, false);
      ant.setDirection(ant.getDirection() - 90);
    }
    ant.move(1);
    if (ant.isNearBorder())
      doPause();
  }

  public static void main(String[] args)
  {
    new Langton();
  }
}