In Part 2 we seeded the board; next we need to start playing the game. We want to update on a timer, say once a second. This means we need to add a subscription to our program:
main = Html.program { init = init, view = view, update = update, subscriptions = subscriptions } subscriptions : Model -> Sub Msg subscriptions model = Time.every Time.second Tick
and handle those messages in our update function:
type Msg = NewBoard Board | Tick Time.Time update : Msg -> Model -> (Model, Cmd Msg) update msg model = case msg of Tick t -> (nextGeneration model, Cmd.none) NewBoard board -> (board, Cmd.none) nextGeneration : Board -> Board nextGeneration board = board
The heart of the game will be the nextGeneration function, which given the current state of the board should return the next version after following the rules of the game.
At this point, I realised my life would probably be easier if I used Arrays for the model, rather than Lists. These are very different to what most people think of as an array, as they are immutable and implemented as “relaxed radix balanced-trees“; but they have similar properties to the other sort of arrays.
type alias Row = Array.Array Cell type alias Board = Array.Array Row init = (Array.empty, Random.generate NewBoard (seedBoard))
Now we need to convert the random Lists of cells to Arrays:
update msg model = case msg of ... NewBoard cells -> (toBoard cells, Cmd.none) toBoard : (List (List Cell)) -> Board toBoard cells = Array.fromList (List.map toRow cells) toRow : (List Cell) -> Row toRow cells = Array.fromList cells
In the fourth, and final part, we will implement the nextGeneration function.
2 thoughts on “Game of Life in Elm (Pt 3)”