hoschi@gfuzz:~$

Conway's Game Of Life (C/OpenGL)

Not the board game

A couple of years ago, when I first heard about Game of Life, all I could think of was the board game. When I ran the program for the first time - probably an ASCII version under FreeBSD, somewhere around 2003 - , I did not understand at all what all these moving, blinking and vanishing pixels meant. In an interview with the original author, Conway states that he is pretty tired of being “reduced” to Game of Life and that it is not very interesting.

However, I think there cannot be enough implementations of the program out there :-)

Rules

Actually, it is quite easy to describe: Imagine a grid of cells (pixels) of the size y*x, each cell has two states: DEAD or ALIVE.

Initially, the states of the cells are set randomly, after that, you alter the grid by the following (original) rules:

  • Any live cell with fewer than two live neighbours dies, as if caused by underpopulation.
  • Any live cell with two or three live neighbours lives on to the next generation.
  • Any live cell with more than three live neighbours dies, as if by overpopulation
  • Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

And that’s it! With the rules above you form a grid of a new generation of cells, doing this over and over again you will see all the funny forms, variations and movements.

Implementation

The main logic of my program can be split into two parts:

  • Count the neighbors of the cell
  • OpenGL display I’m pretty sure there is a more efficient way of counting the adjacent cells, but this one seems as the most straight forward to me:
static int
get_neighbors(int y, int x)
{
  int n = 0;

  if(cells[y-1][x] == ALIVE)
    n++;
  if(cells[y+1][x] == ALIVE)
    n++;
  if(cells[y][x-1] == ALIVE)
    n++;
  if(cells[y][x+1] == ALIVE)
    n++;

  if(cells[y+1][x+1] == ALIVE)
    n++;
  if(cells[y+1][x-1] == ALIVE)
    n++;
  if(cells[y-1][x+1] == ALIVE)
    n++;
  if(cells[y-1][x-1] == ALIVE)
    n++;

  return n;
}

Almost everything of the OpenGL part is initialization, the rest is to deceide how to display the state of the cell. glVertex2f() allows you to draw 2d polygon verticles, by setting glBegin() to the GL_POINTS constant, the function draws a single pixel at the given coordinate.

 if(cells[y][x] == ALIVE)
    glColor3f(0.0, 0.6, 0.7);
  else
    glColor3f(0.0, 0.0, 0.0);
  glBegin(GL_POINTS);
  glVertex2f(x, y);
  glEnd();

Example

Game of Life

The source code can be found here: https://gogs.gfuzz.de/oliver.peter/GameOfLife

(You can press ‘q’ to exit the program; hold to randomly redeem dead cells)

Lessons learned

  • The program shows that even with very few and simple rules, the outcome of cellular automaton is pretty unpredictable
  • OpenGL is a mess
  • vokoscreen is a very handy tool in case you want to record something on your desktop