gpt4 book ai didi

elm - "generate"如何在简单应用中拥有自己的命令

转载 作者:行者123 更新时间:2023-12-02 09:19:08 24 4
gpt4 key购买 nike

作为 elm 的学习示例,我想用 elm 架构创建一个简单的贪吃蛇游戏。

这里是完整的代码: https://gist.github.com/DanEEStar/b11509514d72eaafb640378fc7c93b44

程序的一部分是通过单击按钮生成的 UpdateWorld 消息和用户按下空格键时调用的 updateWorld 函数。

这导致以下编译和工作代码(片段构成完整代码):

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" ]
]

在此代码片段中,很明显 onClick 事件生成了 UpdateWorld 命令。但是在 handleInput 函数中,我必须“手动”调用 updateWorld 函数。

我宁愿做的是从我的 handleInput 函数“生成”一个新的 UpdateWorld 命令。我认为这会澄清代码。像这样的东西:

handleInput keyCode =
case Char.fromCode keyCode of
' ' ->
-- how can I generate this command in my code
UpdateWorld

我该怎么做?

这甚至是个好主意,还是更好的模式?

最佳答案

回想一下,update 只是一个函数,这意味着您可以递归调用它。

考虑更改 handleInput 的签名以也返回一个 (Model, Cmd Msg),就像 update 函数一样:

handleInput : Int -> Model -> (Model, Cmd Msg)
handleInput keyCode model =
case Char.fromCode keyCode of
' ' ->
update UpdateWorld model
'a' ->
{ model | snake = changeSnakeDirection model.snake West } ! []
...

您可以删除 updateWorld 函数并将该代码移至 UpdateWorld 消息处理程序:

update : Msg -> Model -> ( Model, Cmd Msg )
update msg model =
case msg of
UpdateWorld ->
( { model | snake = updateSnake model.snake }, Cmd.none )

ChangeDirection newDirection ->
( { model | snake = changeSnakeDirection model.snake newDirection }, Cmd.none )

KeyPress keyCode ->
handleInput keyCode model

关于elm - "generate"如何在简单应用中拥有自己的命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44175660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com