13. Running and drawing
The rules work. Now let's run the game for many generations, and draw the board so that you can see it move.
Many generations
generation(Live, K, Result) takes K steps from Live.
generation(Live, 0, Live).
generation(Live, K, Result) :-
K > 0,
step(Live, Next),
K1 is K - 1,
generation(Next, K1, Result).It is the same pattern as the accumulators of chapter 7. The board so far is passed down to the next call.
Drawing the board
show(Live, Width, Height) draws the area from 0-0 to (Width-1)-(Height-1). It writes # for a living cell and . for a dead one.
show(Live, Width, Height) :-
MaxX is Width - 1,
MaxY is Height - 1,
forall(between(0, MaxY, Y),
( forall(between(0, MaxX, X),
( memberchk(X-Y, Live) -> write('#') ; write('.') )),
nl )).This is the square of chapter 10, with an if then else from chapter 9 for each cell.
The glider
The glider is the most famous shape of the game. Every four generations, it moves one cell to the right and one cell down. Run the box below, and watch it move across the board.
run/4 computes each generation from the start again, which is simple but slow. It is fine for a few generations.
The glider, as data
Because the board is a plain list, you can also check facts about it with a query. After four generations, the glider is the same shape, one cell to the right and one cell down.
The answer true means that four steps of the game give the same board as moving the glider by one cell. The query checks it for you, so you don't have to compare the drawings.
What you built
In about 40 lines, you wrote a Game of Life with no limit on the size of the board. Look back at what each part used.
neighbor/2generates the neighbors by backtracking (chapter 8).alive_next/2writes the rules as clauses, and uses negation as failure for dead cells (chapters 3 and 9).step/2collects the cells withfindall/3andsort/2(chapter 10).show/3draws withforall/2and if then else (chapters 9 and 10).
Try it
- Draw the blinker for four generations.
- The "toad" is
[1-1, 2-1, 3-1, 0-2, 1-2, 2-2]. Draw it, and find how many generations it takes to come back. - Make
run/4faster. Write a version that keeps the current board and callsstep/2once per generation, instead of callinggeneration/3from the start.