Creative Coding Blog

Maths, coding and art

Simple cellular automata

A cellular automata system consists if a grid of cells. Each cell has a particular state. The state is often simply a number, and in generative art the number usually controls the colour of the cell.

In a simple case, each cell can either have a value 0 (black) or 1 (white). Here is an example where the grid has 1 row of 10 columns:

The grid is often rectangular as shown, but you can use other geometries, for example hexagonal grids, 3 dimensional grids etc.

int scl = 4;
int[] rules = {0,1,0,1,1,0,1,0};
//int[] rules = {0,0,0,1,1,1,1,0};

int[][] cells;
int rows;
int cols;

void setup()
{
  size(600, 600);
  background(0);
}

void draw()
{
  rows = height/scl;
  cols = width/scl;
  cells = new int[rows][cols];
  for (int col = 0; col < cols; col++)
    cells[0][col] = 0;
  cells[0][cols/2] = 1;

  generate();
  show();
}

void generate() {
  for (int row = 1; row < rows; row++)
  {
    for (int col = 1; col < cols-1; col++)
    {
    cells[row][col] = executeRules(row, col);
    }
  }
}
  
void show()
{
  for (int row = 0; row < rows; row++)
  {
    for (int col = 0; col < cols; col++)
    {
      if (cells[row][col] == 1) {
        fill(255);
      } else { 
        fill(0);
      }
      noStroke();
      rect(col*scl, row*scl, scl, scl);
    }
  }
}

int executeRules (int row, int col)
{
  int a = cells[row-1][col-1];
  int b = cells[row-1][col];
  int c = cells[row-1][col+1];
  int rule = a*4 + b*2 + c;
  return rules[rule];
}