Skip to content

Instantly share code, notes, and snippets.

@hhenrichsen
Last active November 14, 2020 00:33
Show Gist options
  • Save hhenrichsen/0c2e3d3936f80af7abac0d0c9ce92464 to your computer and use it in GitHub Desktop.
Save hhenrichsen/0c2e3d3936f80af7abac0d0c9ce92464 to your computer and use it in GitHub Desktop.

Hunter's Introduction to the Game of Life

Cells

The game of life is made up of cells. These are either alive or dead. Cells are normally represented within a 2D list, and look like this:

Rules

The cells also have rules that allow us to simulate them. They're normally defined as follows:

  • If a cell has less than 2 neighbors, it dies.
  • If a cell has 2 or 3 neighbors and is alive, it stays alive.
  • If a cell has 3 neighbors and is dead, it becomes alive.
  • If a cell has more than 3 neighbors, it dies.

Simulation

We need to break this down into a couple steps to simulate this correctly. First, we need a way to figure out how many living neighbors a cell has. To do this, I assign every cell with an x and y coordinate, so our updated picture looks like this:

As a note, the x and y coordinate also match the array indices.

How do we know how many living neighbors a cell has? Let's look at cell (2,1). The cells around that are (1,2), (2,2), (3,2), (1,1), (3,1), (1,0), (2,0), and (3,0). Doing some math, we can turn these into a set of offsets. So given an (x,y) pair, we can go from (x-1,y-1) to (x+1,y+1).

With this information, we can make a new completely empty board, and start filing in cells based on the rules above. If we write a function that tells us how many neighbors a cell has, this turns into a simple set of ifs and else ifs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment