11. The board
Now you have everything you need for the first goal, Conway's Game of Life.
The game
The Game of Life is played on a grid of cells. Each cell is alive or dead. The board changes in steps called generations. In each step, every cell looks at its eight neighbors, and these rules decide the next generation.
- A living cell with two or three living neighbors stays alive.
- A dead cell with exactly three living neighbors comes to life.
- Every other cell is dead in the next generation.
That is all. From these rules come shapes that blink, move, and even build other shapes. In the next three chapters, you write the game in Prolog.
- This chapter decides how to store the board, and finds the neighbors of a cell.
- Chapter 12 writes the rules and computes the next generation.
- Chapter 13 runs the game and draws it.
How to store the board
A JavaScript programmer might use a two dimensional array of booleans. That needs a fixed size, and most cells are dead anyway.
We store only the living cells, as a list of X-Y pairs. The board has no edges, so a shape can move as far as it likes.
% A "blinker", three cells in a row
[0-1, 1-1, 2-1]We also keep the list sorted with sort/2, so that the same board is always the same list.
The neighbors of a cell
A cell X-Y has eight neighbors. Each one is X+DX and Y+DY, where DX and DY are -1, 0, or 1, but not both 0.
neighbor/2 has no loop. The two member/2 goals generate the nine combinations by backtracking, and \+ drops the cell itself. It is the generate and test of chapter 8. The second query collects the eight neighbors with findall/3.
Counting living neighbors
To count the living neighbors of a cell, find the neighbors that are in the list of living cells, and count them.
On the blinker [0-1, 1-1, 2-1], the results are these.
- The center
1-1has two living neighbors, so it stays alive. - The cell
1-0above the center has three, so it comes to life. - The left end
0-1has only one, so it dies.
memberchk/2 is like member/2, but it stops at the first match. We only want to know whether the cell is in the list, so there is no reason to look for a second match.
Try it
- Find the living neighbors of
1-2on the blinker. - Write
dead_neighbor(Cell, Live, N), which gives each neighbor ofCellthat is not inLive. Use\+andmemberchk/2.