Conway's Game of Life
In 1970 the mathematician John Conway invented a game with no players. The board is a grid of cells, and every cell is either alive or dead. From one generation to the next, every cell looks at its eight neighbours – up, down, left, right and the four diagonals – and only two rules decide its fate:
- A dead cell with exactly 3 live neighbours comes to life – it is born.
- A live cell with 2 or 3 live neighbours survives. With fewer it dies of loneliness, with more of overcrowding.
That's all. And yet from these rules come shapes that blink, stand still or walk across the board. As in a maze, a grid of strings will do: # is alive, . dead. Here are three famous shapes, side by side – transpose turns the list of three grids into a list of rows, each with one row of every grid, and tr swaps the characters for nicer ones:
blinker = [".....", "..#..", "..#..", "..#..", "....."]
block = [".....", ".##..", ".##..", ".....", "....."]
glider = [".#...", "..#..", "###..", ".....", "....."]
[blinker, block, glider].transpose.each do |rows|
puts rows.join(" ").tr("#.", "█·")
endWhich cells are the neighbours? Those whose row and column differ by −1, 0 or +1. product makes every pair of two lists – here all 9 combinations of row and column step. One of them is the cell itself, [0, 0], and that is no neighbour:
offsets = [-1, 0, 1].product([-1, 0, 1])
p offsets.length
offsets - [[0, 0]]At the edge of the board there are fewer neighbours: outside the board everything counts as dead. Careful – Ruby gives no error for a step off the board. A negative number counts from the other end, so a cell in the top row would count cells of the bottom row as its neighbours, and past the end there is nil:
p glider[-1] # no error: the last row
p glider[0][-1] # the last square of the first row
glider[0][5] # past the end: nilSo the method that counts first checks that the neighbour lies inside the board, and only then looks whether it lives. count with a block counts the offsets for which the block is true:
def live_neighbours(grid, row, col)
offsets = [-1, 0, 1].product([-1, 0, 1]) - [[0, 0]]
offsets.count do |dr, dc|
r = row + dr
c = col + dc
inside = r >= 0 && c >= 0 && r < grid.length && c < grid[r].length
inside && grid[r][c] == "#"
end
end
p live_neighbours(blinker, 2, 1)
live_neighbours(blinker, 2, 2)The middle of the blinker has 2 live neighbours, the cell to its left 3. Let's count every cell of the blinker at once and print the numbers in its shape:
blinker.length.times do |r|
width = blinker[r].length
puts width.times.map { |c| live_neighbours(blinker, r, c) }.join
endNow read the rules off the numbers. The two cells left and right of the middle have a 3 – they are born. The middle has 2 and lives on. The top and bottom ends have only 1 – they die. So the upright line becomes a lying one. One thing matters here: all cells change at the same time. The next generation is a new grid, counted in the old one – if you changed the old grid while counting, a freshly born cell would already count for its neighbours. In Ruby the two rules are a single line: n == 3 || (alive && n == 2). Here is the glider, four generations, side by side:
grid = glider
frames = [grid]
4.times do
grid = grid.length.times.map do |r|
grid[r].length.times.map do |c|
n = live_neighbours(grid, r, c)
alive = grid[r][c] == "#"
n == 3 || (alive && n == 2) ? "#" : "."
end.join
end
frames << grid
end
frames.transpose.each { |rows| puts rows.join(" ").tr("#.", "█·") }After four generations the glider has its shape back – one square further down and to the right. It walks! Change the first line to grid = blinker: the blinker flips between upright and lying, and grid = block stays exactly as it is. Shapes that repeat are called oscillators, shapes that never change still lifes, shapes that move spaceships. Conway's simple rules turn out to be powerful enough to build a whole computer out of gliders. The rule of thumb for every simulation of this kind: build the next state as a new grid from the old one, and never change the grid you are still counting in.
next_generation(grid): it returns the next generation of any grid of # and . as a new array of strings, and leaves the grid it gets unchanged. live_neighbours from above does the counting. The check tries the blinker, the block, the glider and a few cells at the edge.# def next_generation(grid)
# ... # a new grid: every cell by the rules, counted in the old grid
# end
# puts next_generation(blinker)
next_generation_wrapped(grid). The remainder % from lesson 2 does the wrapping: with 5 columns, (4 + 1) % 5 is 0, and in Ruby even -1 % 5 is 4. On a 5 × 5 doughnut the glider is back where it started after 20 generations.# def next_generation_wrapped(grid)
# ... # like a generation above, but the board wraps around:
# ... # off the right edge is the left edge, off the top the bottom
# end
# puts next_generation_wrapped(%w[....# ....# ....# ..... .....])