Game of Life in Elm (Pt 4)

In the last part we started a timer, to update the game; now we need implement the “business logic”.

To check that everything is working, we can start with a simple function that inverts the state of the board on every tick:

nextGeneration : Board -> Board
nextGeneration board =
    Array.indexedMap (\i r -> (nextGenRow i r board)) board

nextGenRow : Int -> Row -> Board -> Row
nextGenRow rowIndex row board =
    Array.indexedMap (\i c -> (nextGenCell i rowIndex c board)) row

nextGenCell : Int -> Int -> Cell -> Board -> Cell
nextGenCell cellIndex rowIndex cell board =
    case cell of
        Alive -> Dead
        Dead -> Alive

Satisfied that the board updates as expected, we can move onto implementing the real rules. Everything is conditional on the current state of the cell, and the number of live neighbours it has:

nextGenCell : Cell -> Int -> Cell
nextGenCell cell liveNeighbours =
    case cell of
        Alive ->
            if liveNeighbours < 2 then
               Dead
            else if liveNeighbours > 3 then
               Dead
            else
               Alive
        Dead ->
            if liveNeighbours == 3 then
                Alive
            else
                Dead

We can count the neighbours for each cell:

liveNeighbours : Int -> Int -> Board -> Int
liveNeighbours rowIndex colIndex board =
    liveNeighboursAbove rowIndex colIndex board +
    liveNeighboursAdjacent rowIndex colIndex board +
    liveNeighboursBelow rowIndex colIndex board

liveNeighboursAbove : Int -> Int -> Board -> Int
liveNeighboursAbove rowIndex colIndex board =
    isAlive (rowIndex - 1) (colIndex - 1) board +
    isAlive (rowIndex - 1) (colIndex) board +
    isAlive (rowIndex - 1) (colIndex + 1) board

liveNeighboursAdjacent : Int -> Int -> Board -> Int
liveNeighboursAdjacent rowIndex colIndex board =
    isAlive rowIndex (colIndex - 1) board +
    isAlive rowIndex (colIndex + 1) board

liveNeighboursBelow : Int -> Int -> Board -> Int
liveNeighboursBelow rowIndex colIndex board =
    isAlive (rowIndex + 1) (colIndex - 1) board +
    isAlive (rowIndex + 1) (colIndex) board +
    isAlive (rowIndex + 1) (colIndex + 1) board

isAlive : Int -> Int -> Board -> Int
isAlive rowIndex colIndex board =
    case (getCell colIndex (getRow rowIndex board)) of
        Alive -> 1
        Dead -> 0

If the row or column index is 0, we need to wrap the grid around from top to bottom. We could do this by checking the index, but as the Array getters return a Maybe we can just handle the case that it doesn’t exist:

getRow : Int -> Board -> Row
getRow i board =
    case Array.get i board of
        Just row -> row
        Nothing ->
            case Array.get ((Array.length board) - 1) board of
                Just row -> row
                Nothing -> Debug.crash "oops"

getCell : Int -> Row -> Cell
getCell i row =
    case Array.get i row of
        Just cell -> cell
        Nothing ->
            case Array.get ((Array.length row) - 1) row of
                Just cell -> cell
                Nothing -> Debug.crash "oops"

The Elm philosophy leans towards covering all edge cases, which is generally a Good Thing, but can become annoying e.g. when parsing json.

Now we can put all the pieces together with a map:

nextGeneration : Board -> Board
nextGeneration board =
    Array.indexedMap (\i r -> (nextGenRow i r board)) board

nextGenRow : Int -> Row -> Board -> Row
nextGenRow rowIndex row board =
    Array.indexedMap (\i c -> (nextGenCell c (liveNeighbours rowIndex i board))) row

And we finally have a working Game of Life!

Game of Life in Elm (Pt 3)

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.

Game of Life in Elm (Pt 2)

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.

Game of Life in Elm (Pt 1)

I stay as far away as possible from the front end, and have no interest in React or Angular; but Elm has piqued my interest, as a new functional language “compiled” to JavaScript. I thought it might be interesting to try and implement Conway’s Game of Life.

In this, the first part of X, I will simply render the grid. You can follow along with the repo here, and see the working final version here. I’m using Elm 0.18, the latest version at the time.

We start with the standard program for the Elm architecture:

main: Program Never Model Msg
main =
    Html.program {
        init = init,
        view = view,
        update = update,
        subscriptions = \_ -> Sub.none
    }

The simplest way to represent the grid is as a list of lists:

type Cell = Dead | Alive
type alias Row = List Cell
type alias Board = List Row
type alias Model = Board

init : (Model, Cmd Msg)
init =
    (emptyBoard, Cmd.none)

emptyBoard : Board
emptyBoard = [
        [ Dead, Dead, Dead ],
        [ Dead, Dead, Dead ],
        [ Dead, Dead, Dead ]
    ]

We need an update function:

type Msg =
    Tick

update : Msg -> Model -> (Model, Cmd Msg)
update msg model =
    case msg of
        Tick ->
            (model, Cmd.none)

but this message will never be received, right now. Finally, we render the model as a table:

view : Model -> Html Msg
view model =
    div [] [
        h1 [] [ text "Game Of Life" ],
        div [ class "board" ] [
            table [ style [ ("border-collapse", "collapse"), ("border", "1px solid black") ] ] [
                tbody [] (List.map renderRow model)
            ]
        ]
    ]

renderRow : Row -> Html Msg
renderRow row =
    tr [] (List.map renderCell row)

renderCell : Cell -> Html Msg
renderCell box =
    td [ style [ ("border", "1px solid black"), ("height", "50px"), ("width", "50px") ] ] []

You can compile the main file using elm-make, or run elm-reactor, and you should see a 3×3 grid rendered.

In Part 2 we’ll look at how to make the “seed” more interesting.