我正在Elm写一个游戏,在这个游戏中有一个按钮按下时应该将游戏板重置为初始状态。但是我不明白按钮点击信号如何传播到电路板模型的更新功能。在下面的代码中,我刚刚将单位值传递给stepBoard
,但我对它无能为力,所以我该如何解决呢?
--MODEL
type Board = [(Int,Int)]
type Game = {name: String, board: Board}
defaultGame = {name = "Test", board = [(3,3)]}
--UPDATE
stepBoard click (colsInit, rowsInit) (rows, cols) g =
{g | board <- if ? then --some initial value (colsInit, rowsInit)
else --some updated value using (rows, cols)}
stepGame: Input -> Game -> Game
stepGame {click, name, rowsColsInit, rowsCols} g = stepBoard click (0,0) (0,0) g
game = foldp stepGame defaultGame input
--INPUT
type Input = {click:(), name: String, rowsColsInit: (Int,Int), rowsCols: (Int,Int)}
input = Input <~ clicks ~ nameSignal ~ rowsColsInitSignal ~ rowsColsSignal
--VIEW
(btn, clicks) = Input.button "Click"
答案 0 :(得分:3)
合并foldp
和点击信息可能不直观。
采用的常用解决方案是用于编码不同可能事件的ADT:
data Input = Init (Int, Int)
| Update { name : String
, rowsCols : ( Int, Int )
}
input = merge (Init <~ (sampleOn clicks rowsColsInitSignal))
(OtherInput <~ nameSignal ~ rowsColsSignal)
现在您可以在更新功能中按案例匹配:
stepBoard input g =
let newBoard =
case input of
Init (initRows, initCols) -> -- do your initialisation here
Update {name, rowsCols} -> -- do your update here
in { g | board <- newBoard }