Conway's Game of Life

Conway's Game of Life

Conway’s Game of Life is a so called zero-player game designed by the British mathematician John Horton Conway in 1970. It only has a initial configuration which can be set by the player and then evolves without any further interactions with the game.

The rules are rather simple. Here is an excerpt from wikipedia.org:

The universe of the Game of Life is an infinite, two-dimensional orthogonal grid of square cells, each of which is in one of two possible states, alive or dead, (or populated and unpopulated, respectively). Every cell interacts with its eight neighbors, which are the cells that are horizontally, vertically, or diagonally adjacent. At each step in time, the following transitions occur:

  1. Any live cell with fewer than two live neighbors dies, as if by underpopulation.
  2. Any live cell with two or three live neighbors lives on to the next generation.
  3. Any live cell with more than three live neighbors dies, as if by overpopulation.
  4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction.

The initial pattern constitutes the seed of the system. The first generation is created by applying the above rules simultaneously to every cell in the seed; births and deaths occur simultaneously, and the discrete moment at which this happens is sometimes called a tick. Each generation is a pure function of the preceding one. The rules continue to be applied repeatedly to create further generations.

In this post we will program the game in and look at a few results.

In principal, the grid should be infinite. Due to the limitations of our computers, this is not realizable, so we limit ourselves to finite dimensions. For our experiments, we choose rather small values for the number of cells on the orthogonal grid.

First, we need a function which initializes the grid. Each cell has a chance of 50% to be alive:

randInitWorld <- function(dimX, dimY) {
  matrix(sample(c(T,F), dimX * dimY, replace = T), dimY, dimX)
}

In the next step, it can be useful, to have a function which counts the live neighbors for each cell of the grid. What we have to do is, put a 3x3 box around each cell (on the edges the boxes are smaller) and sum up all cells in this 3x3 box which are alive (excluding the cell in the center, which is our target cell for which we count the neighbors):

countAliveNeighbors <- function(X) {
  d <- dim(X)
  C <- apply(merge(1:d[1], 1:d[2]), 1,
        function(i) sum(X[max(1,i[1]-1):min(d[1], i[1]+1), max(1,i[2]-1):min(d[2], i[2]+1)]) - X[i[1],i[2]]
  )
  matrix(C, d[1], d[2])
}

Now, we are ready to write a function which performs the transition from generation to the next. If we look carefully at the above rules for a transition, we can identify a simple instruction which specifies which cells will be alive in the next generation:

  1. All cells with exactly 3 neighbors or
  2. All live cells with exactly 2 live neighbors.

All other cells will be dead in the next generation. These two simple rules make it very easy to write a function which evolves the grid:

evolveNextGeneration <- function(XWorld) {
  XWorldCount <- countAliveNeighbors(XWorld)
  (XWorldCount == 3) | XWorld & (XWorldCount == 2)
}

And that’s basically it. We just need some additional functions which evolve the grid-world over many time steps and which plot the world after each transition. The whole code can be found on Github and is also listed in the appendix.

Example

Let us take a look at how a randomly initialized 100x100 grid evolves over time:

alt and id

Figure 1: Evolution of a 100x100 grid-world over time. After some time one can notice some (periodic) characteristic patterns which often arise in Conway’s game of life.

Depending on the initialization of the grid-world, many interesting patterns can be created. Many different patterns are discussed on wikipedia.org.

Usually, the population of live cells never dies out completely and converges to a certain number. The image below shows exemplarily for our 100x100 grid how the population develops over time for 20 different initial worlds. In the very beginning, around 50% of all cells are alive, but quickly die away in all runs. After 1000 iterations around 350 alive cells are left and then appears to stagnate from then on.

alt and id

Figure 2: Number of live cells on a 100x100 grid world. The black line depicts the mean out of 20 runs and the red ribbon indicates the 95% confidence interval for the mean.

Appendix

A1: Code

game-of-life.R view raw
#
# A implementation of the game of life world
#

DIM_X = 100 # 100
DIM_Y = 100 # 100
NUM_GENERATIONS = 2001

randInitWorld <- function(dimX, dimY) {
  matrix(sample(c(T,F), dimX * dimY, replace = T), dimY, dimX)
}

countAliveNeighbors <- function(X) {
  d <- dim(X)
  C <- apply(merge(1:d[1], 1:d[2]), 1, 
        function(i) sum(X[max(1,i[1]-1):min(d[1], i[1]+1), max(1,i[2]-1):min(d[2], i[2]+1)]) - X[i[1],i[2]]
  )
  matrix(C, d[1], d[2])
}

evolveNextGeneration <- function(XWorld) {
  XWorldCount <- countAliveNeighbors(XWorld)
  (XWorldCount == 3) | XWorld & (XWorldCount == 2)
}

countAliveCells <- function(XWorld) {
  sum(XWorld)
}

plotWorld <- function(XWorld) {
  p <- ggplot(melt(XWorld), aes(X2,X1, fill=value)) + 
    geom_raster() +
    guides(fill=FALSE) +
    theme(axis.line=element_blank(),
          axis.text.x=element_blank(),
          axis.text.y=element_blank(),
          axis.ticks=element_blank(),
          axis.title.x=element_blank(),
          axis.title.y=element_blank(),
          legend.position="none",
          panel.background=element_blank(),
          panel.border=element_blank(),
          panel.grid.major=element_blank(),
          panel.grid.minor=element_blank(),
          plot.background=element_blank()) +
    scale_fill_manual(values=c("white","black")) +
    scale_y_reverse( lim=c(dim(XWorld)[1],0)) # (0,0) should start top-left
  p
}

singleRun <- function(doPlot = F, svPlot = F) {
  XWorld <- randInitWorld(DIM_X, DIM_Y)
  if(doPlot) plot(plotWorld(XWorld))
  if(svPlot) ggsave(sprintf("png/gol%04d.png", 1), width=DIM_X/300.0*5,height=DIM_Y/300.0*5,plotWorld(XWorld))
  numAlive <- rep(0, NUM_GENERATIONS)
  for(i in 1:NUM_GENERATIONS) {
    numAlive[i] <- countAliveCells(XWorld)
    cat("Iteration:", i, "; Still alive:", numAlive[i], "\n") #track over time
    XWorld <- evolveNextGeneration(XWorld)
    if(doPlot) plot(plotWorld(XWorld))
    if(svPlot) ggsave(sprintf("png/gol%04d.png", i), width=DIM_X/30.0*5,height=DIM_Y/30.0*5,plotWorld(XWorld))
  }
  return (list(numAlive = numAlive, XWorld = XWorld))
}

# ffmpeg -i gol%03d.png output.gif
# convert -delay 10 -loop 0 *.png animation.gif
# xkcd plot
# how many generations? 400-500
singleRun(svPlot = T)

# Run many times

A2: Further Examples

Example 1

100x100 grid-world

Example 2

100x100 grid-world

Example 3

100x100 grid-world

Example 4

100x100 grid-world

Markus Thill

Markus Thill
I studied computer engineering (B.Sc.) and Automation & IT (M.Eng.). Generally, I am interested in machine learning (ML) approaches (in the broadest sense), but particularly in the fields of time series analysis, anomaly detection, Reinforcement Learning (e.g. for board games), Deep Learning (DL) and incremental (on-line) learning procedures.

Deriving a Closed-Form Solution of the Fibonacci Sequence using the Z-Transform

The Fibonacci sequence might be one of the most famous sequences in the field of mathmatics and computer science. Already high school stu...… Continue reading