ela

Tutorial, lesson 5 of 9

Lists from loops

The Game of Life is a board of cells, each alive or not. At each generation a live cell with two or three live neighbours lives on, an empty cell with three comes alive, and every other cell is empty. The board here is a list of six rows, each a list of six cells, 1 alive and 0 not; $board[$r][$c] is one cell.

A one-line for on the right of an = gives a list: each round adds the value after the ;. next_row makes a row that way, one cell for each cell of the old one. for c, cell in names the position as well as the item.

when, before the ;, keeps only the items its condition says yes to. neighbours walks the eight squares around a cell and keeps the ones on the board, so a cell at the edge has fewer; list.sum then adds the cells kept, and the live ones count 1 each.

next_cell is the rule, a one-line if that gives a value, as in the last lesson.

A for gives a list only as the whole value of an assignment, so one cannot sit inside another on the same line. The board is a for over its rows, each row from next_row: a proc for each level. Try board = for r in range($SIZE); for c in range($SIZE); 0 to see the error.

The glider moves one square down and to the right every four generations. Run more of them with range(14), and it reaches the bottom corner, where the edge breaks it up.

What it prints
generation 0
. # . . . .
. . # . . .
# # # . . .
. . . . . .
. . . . . .
. . . . . .
generation 1
. . . . . .
# . # . . .
. # # . . .
. # . . . .
. . . . . .
. . . . . .
generation 2
. . . . . .
. . # . . .
# . # . . .
. # # . . .
. . . . . .
. . . . . .
generation 3
. . . . . .
. # . . . .
. . # # . .
. # # . . .
. . . . . .
. . . . . .
generation 4
. . . . . .
. . # . . .
. . . # . .
. # # # . .
. . . . . .
. . . . . .