As a learning example for elm I want to create a simple snake game with the elm architecture.
Here is the full code so far: https://gist.github.com/DanEEStar/b11509514d72eaafb640378fc7c93b44
A part of the program is a UpdateWorld
message which gets generated by a button click and a updateWorld
function which is called when the user presses the space key.
This leads to the following compiling and working code (snippets form the full code):
update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
UpdateWorld ->
( updateWorld model, Cmd.none )
KeyPress keyCode ->
( handleInput keyCode model, Cmd.none )
handleInput : Int -> Model -> Model
handleInput keyCode model =
case Char.fromCode keyCode of
' ' ->
updateWorld model
_ ->
model
updateWorld : Model -> Model
updateWorld model =
{ model | snake = updateSnake model.snake }
subscriptions : Model -> Sub Msg
subscriptions model =
Keyboard.presses KeyPress
view : Model -> Html Msg
view model =
div []
-- here I can simply tell `onClick` to generate the `UpdateWorld` command
[ button [ onClick UpdateWorld ] [ text "tick" ]
]
In this code snippets it is very clear that the onClick
event generates the UpdateWorld
command.
But in the handleInput
function I have to "manually" call the updateWorld
function.
What I would rather do is "generate" a new UpdateWorld
command from my handleInput
function. I think this would clarify the code. Something like:
handleInput keyCode =
case Char.fromCode keyCode of
' ' ->
-- how can I generate this command in my code
UpdateWorld
How could I do this?
Is this even a good idea, or what would be a better pattern?