Lesson 20. Capstone: A slice of life

 

For this challenge, you will build a simulation of underpopulation, overpopulation, and reproduction called Conway’s Game of Life (see mng.bz/xOyY). The simulation is played out on a two-dimensional grid of cells. As such, this challenge focuses on slices.

Each cell has eight adjacent cells in the horizontal, vertical, and diagonal directions. In each generation, cells live or die based on the number of living neighbors.

20.1. A new universe

For your first implementation of the Game of Life, limit the universe to a fixed size. Decide on the dimensions of the grid and define some constants:

const (
    width  = 80
    height = 15
)

Next, define a Universe type to hold a two-dimensional field of cells. With a Boolean type, each cell will be either dead (false) or alive (true):

type Universe [][]bool

Uses slices rather than arrays so that a universe can be shared with, and modified by, functions or methods.

Note

Lesson 26 introduces pointers, an alternative that allows you to directly share arrays with functions and methods.

Write a NewUniverse function that uses make to allocate and return a Universe with height rows and width columns per row:

func NewUniverse() Universe

Freshly allocated slices will default to the zero value, which is false, so the universe begins empty.

20.1.1. Looking at the universe

20.2. Implementing the game rules

20.3. Parallel universe