我正在使用Haskell编写一个简单的游戏/游戏引擎。
下面是我的游戏循环的一个迭代:
input <- getInput -- where input is some list of pressed keys
let world' = update world input
-- ... continue with the next iterationgetInput函数如下所示:
getInput = do
w <- getKey $ CharKey 'W'
q <- getKey $ CharKey 'Q'
-- ...
return [("W", w), ...]update函数(在World.hs文件中)如下所示:
update world input = world'
where world' = -- if w, then do something, if q then do something, etc.如您所见,我的输入逻辑被分割为实际的Input.hs文件和World.hs文件。update函数不应该真的需要测试按键(在我看来)。
如何将输入与更新逻辑分离?
我想,我正在寻找类似回调之类的东西,它们可以随意注册和未注册。将moveForward注册到W的按键将是理想的。
我也研究过netwire --但我很难把头转到函数式反应性编程上。如果这是玻璃钢的情况,我希望任何使用它的例子,以及。
发布于 2014-03-01 06:53:01
您可以将一个动作声明为一个改变世界的函数:
type Action = Word -> World然后为独立于要绑定它们的键的事物创建操作:
moveForward :: Action
moveForward world = ...然后,可以将(key, action)对的列表传递给doInput函数:
doInput :: [(CharKey, Action)] -> World -> IO World
doInput bindings world = foldM checkKey world bindings where
checkKey world (key, action) = do
pressed <- getKey key
return $ if pressed then action world else world因此,在主循环中,您可以执行如下操作:
mainloop world = do
doRender world
world' <- doInput [(CharKey 'W', moveForward)] world
mainloop world'https://stackoverflow.com/questions/22108058
复制相似问题