Kamel Ghabte · Course · Free

Cellular Automata

Simulate Conway's Game of Life in p5.js.

The concept

A cellular automaton is a grid where each cell changes state based on neighbors. Game of Life (Conway, 1970): a live cell with 2-3 neighbors survives, a dead cell with exactly 3 is born. These simple rules produce spectacular emergent complexity — gliders, oscillators, guns.

The code

// Game of Life
let grid, next, cols, rows, sz = 6;
function setup() {
  createCanvas(400, 280); cols=floor(width/sz); rows=floor(height/sz);
  grid=Array.from({length:rows},()=>Array.from({length:cols},()=>random()>0.7?1:0));
  next=Array.from({length:rows},()=>new Array(cols).fill(0));
  frameRate(10);
}
function draw() {
  background(11,15,20);
  for(let j=0;j<rows;j++) for(let i=0;i<cols;i++){
    if(grid[j][i]){noStroke();fill(55,227,195);rect(i*sz,j*sz,sz-1,sz-1);}
    let n=0; for(let dj=-1;dj<=1;dj++) for(let di=-1;di<=1;di++){if(!dj&&!di)continue;let ni=(i+di+cols)%cols,nj=(j+dj+rows)%rows;n+=grid[nj][ni];}
    next[j][i]=grid[j][i]?(n==2||n==3?1:0):(n==3?1:0);
  }
  [grid,next]=[next,grid];
}

Going further

Explore other free courses on the Learn page, or book a call to discuss your project.

Want to go further?

Book a discovery call →