Beginner Tutorials: How to build a game in Elm — Part 1

Part 1 of 12 — The Game Loop

Lucamug
3 min readJun 8, 2019

--

Next: Part 2 — Add Keyboard

This is the first of 12 parts tutorial about making a game in Elm. Pure Functional Programming are a good fit for video games development, as expressed at the QuakeCon Convention by John Carmack.

Couple of disclaimers:

  1. I’m not a game developer, this was just an exercise that I wanted to do with my children to expose them to video games from a different perspective
  2. The code is not optimised for performance but it still pretty fast
This is what we are going to make in this part 1 of the tutorial

Let’s get started!

The game loop

Differently from a regular web application that sleep for most of the time and wake up only in case of some event, like an user click for example, a game is always awake.

This is done through a never ending loop, something like (in pseudo-code):

while game is running
process inputs
update game world
generate outputs
loop

In our case, the game run in the browser so we should sync up to the browser render loop that usually repaint the screen 60 times per second.
For this, in Javascript there is request​Animation​Frame. In Elm the analogues areonAnimationFrame or onAnimationFrameDelta.

So let’s build our basic TEA (The Elm Architecture) skeleton and add the subscription to onAnimationFrameDelta.

type alias Model = { count : Float }init _ = ( { count = 0 }, Cmd.none )type Msg = Frame Floatsubscriptions _ = onAnimationFrameDelta Frameupdate _ model = ( { model | count = model.count + 1 }, Cmd.none )view model = text ("Count: " ++ String.fromFloat model.count)main : Program () Model Msg
main =
Browser.element
{ init = init
, view = view
, update = update
, subscriptions = subscriptions
}

--

--