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/2 generates the neighbors by backtracking (chapter 8).
  • alive_next/2 writes the rules as clauses, and uses negation as failure for dead cells (chapters 3 and 9).
  • step/2 collects the cells with findall/3 and sort/2 (chapter 10).
  • show/3 draws with forall/2 and if then else (chapters 9 and 10).

Try it

  1. Draw the blinker for four generations.
  2. 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.
  3. Make run/4 faster. Write a version that keeps the current board and calls step/2 once per generation, instead of calling generation/3 from the start.
An unhandled error has occurred. Reload 🗙