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

Part 3 of 12 — Add the Pause

Lucamug

--

Previous: Part 2 — Add Keyboard Support

Next: Part 4—Add the Players (coming soon)

Add the pause

This is what we are making in this part 3 of the tutorial

The Game Loop never stop also when nobody is playing the game. Some browser may put it on hold when the page is not seen (either because below some other tab or because below under other applications) but better to handle our own way to pause the game.

Doing so, we can save CPU cycles (and power consumption).

Using The Elm Architecture is very simple to unsubscribe from listening to an event because the subscription function also get the model as argument. So we can add this if condition:

if model.isPaused then
[]
else
[ Browser.Events.onAnimationFrameDelta Frame ]

So when the flag model.isPaused that we added to the model is true, we do not subscribe to the onAnimationFrameDelta.

Now we need to set this flag. The Browser.Events.onVisibilityChange function help us here.

This is the analogue of document.hidden in Javascript as per this Elm code.

So we subscribe to this function with

Browser.Events.onVisibilityChange OnVisibilityChange

and in the update:

OnVisibilityChange visibility ->
case visibility of
Browser.Events.Hidden ->
( { model | isPaused = True }, cmd )
_ ->
( model, Cmd.none )

We only care about the Browser.Events.Hidden because once the pause is activated we want to disable it manually (pressing any key) and not automatically when the visibility change again.

While Browser.Events.Hidden is working well when changing tab in the browser, it doesn’t fire when switching to another application.

For these cases we should rely on the Javascript window.onblur event happen. So we can create a simple port…

--

--