Hi,
This is my first Elm program, and I’m writing some code that looks like it’ll be hard for other, even beginner-y beginners to understand. I’m looking for a clearer way to do what I wanna do, which is: process multiple types of key presses in a GraphicSVG gameApp.
The documentation at https://package.elm-lang.org/packages/MacCASOutreach/graphicsvg/2.1.0/GraphicSVG shows this example:
update msg model =
case msg of
Tick _ ( keys, _, _ ) ->
case keys (Key "r") of
JustDown ->
{ model
| angle = model.angle - model.speed
, speed = -model.speed
}
_ ->
{ model | angle = model.angle + model.speed }
This works for me, but the problem comes when I want to process input on, say, keys ‘a’, ‘s’, ‘d’, and ‘f’.
My first try was this, handling just two keys:
update msg model =
case msg of
Tick _ ( keys, _, _ ) ->
let model2 = case keys (Key "e") of
JustDown ->
{ model | speed = model.speed * 2}
_ -> model
in
case keys (Key "r") of
JustDown ->
{ model2
| angle = model2.angle - model2.speed
, speed = -model2.speed
}
_ ->
{ model2 | angle = model2.angle + model2.speed }
In prose: first a new model is computed for the presence/absence of the ‘e’ key, then that’s used as an input to compute another new model based on the presence/absecnce of the ‘r’ key.
I was able to generalize this using the foldl
function (reproduced below), but without going through it line-by-line, but at this point the code is looking quite big and mysterious, and not suited towards other beginners. Is there a simpler approach I’m missing here?
update msg model =
case msg of
Tick _ (keys, _, _) ->
let
turnyUpdate model = { model | angle = model.angle + model.speed }
keyUpdater string model =
case keys (Key string) of
JustDown ->
case string of
"a" ->
{ model
| angle = model.angle - model.speed
, speed = -model.speed
}
"s" ->
{ model
| angle = 0
, speed = 0
}
"d" ->
{ model
| speed = model.speed + 1
, angle = model.angle + model.speed
}
_ ->
turnyUpdate model
_ ->
turnyUpdate model
in
List.foldl keyUpdater model ["a", "s", "d", "f"]