In Part 1 we rendered an empty grid, but for a more interesting game we need to initialise the board with a random selection of dead & alive cells (known as the seed).
The Random package is a bit different in Elm; while it is possible to generate values one at a time, it’s more common to use a generator to produce a command:
init : (Model, Cmd Msg) init = ([], Random.generate NewBoard (seedBoard)) seedBoard : Random.Generator Board seedBoard = Random.list 5 seedRow seedRow : Random.Generator Row seedRow = Random.list 5 seedCell seedCell : Random.Generator Cell seedCell = Random.map (\b -> if b then Dead else Alive) Random.bool
We now initialise our grid as an empty list, and await the result of a command generating 5 rows of 5 cells, randomly Dead or Alive (coin flip).
Our update function needs to handle the message:
type Msg = NewBoard Board | Tick update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of Tick -> (model, Cmd.none) NewBoard board -> (board, Cmd.none)
If you run the code, you should see a 5×5 grid with approx half the squares alive (filled in black) and half the squares dead (filled white).
In the next part we will actually begin to play the game.
2 thoughts on “Game of Life in Elm (Pt 2)”