Flying memes

A Game of Life

Everybody knows the popular Game of Life created by Jhon Conway and becamed famous after been published by Martin Gardner on Scientific American in 1970. It is essentially a cellular automation algorithm with a very few simple rules that determinate how to grow a pool of one-pixel-shaped organisms layed upon a 2D matrix.

Here’s the rules:

  • if the organism has more than 3 or fewer than 2 neighbours it dies;
  • if the organism has 2 or 3 neighbours it survives;
  • if a white cell in the matrix is sorrounded by exactly 3 neighbours it became a living organism.

I’ve implemented this Game Of Life using Processing language and trying to push all of the game logic within the organism class in order to really simulate a cellular behavior, here’s the class:

class Spot{
  int[]   rgb, rgb_next;
  int     x,y;
  Spot[]  neighbours;

  Spot(int gx, int gy, int[] c){
    rgb      = c;
    rgb_next = new int[3];
    x       = gx;
    y       = gy;

  void set_neighbors(Spot[][] grid){
    int xp = (x+1 == grid.length ? 0 : x+1);
    int xm = (x-1 == -1 ? grid.length - 1 : x-1);
    int yp = (y+1 == grid[0].length ? 0 : y+1);
    int ym = (y-1 == -1 ? grid[0].length - 1 : y-1);

    neighbours = new Spot[] {  grid[xm][ym], grid[xm][y ], grid[xm][yp],
                               grid[x ][ym],               grid[x ][yp],
                               grid[xp][ym], grid[xp][y ], grid[xp][yp]

  void compute(){
    int black_neighbours = 0;
    for(int z=0; z < neighbours.length; z++)
      if(neighbours[z].rgb == black)
        black_neighbours ++;  

      case 0:
      case 1:
      case 4:
      case 5:
      case 6:
      case 7:
      case 8:
      case 2:
      case 3:

  void advance(){
    rgb = rgb_next;
    rgb_next = new int[3];

  void draw(int bw,int bh){

  void to_color(int[] c){ rgb_next = c; }

There are three methods that worth a look:

  • set_neighbors:
    which determinates the sourronding neighbors (as the method name states) by creating an array of pointer to the closest organisms using the matrix passed as parameter as a reference. The first four lines are needed in order to eliminate the boundaries by linking each edge of the matrix to the opposite one.
  • compute:
    which implements the real logic of the Game, it is divided into two steps, the first part calculates the number of alive neighbors sorrounding the organism and the second one applies the rules stated above.
  • advance:
    due the fact that all of the organisms need to be processed before each of them can switch to the new state, the Spot class record the result of the ‘compute’ method inside a different variable and then, when advance is invoked, it moves this result to the ‘live’ variable.

Here’s a short video of my script in action, the source code is, as usually, available on my github account:

Tags: , ,