How do I write a game loop in Haskell?

孤者浪人 提交于 2019-12-01 02:36:53

You'll probably want something like this

import Control.Monad.Loops

main = iterateM_ 
       (\w -> displayWorld w >> return (gameLoop w))
       initWorld
-- iterateM_ ((>>) <$> displayWorld <*> return . gameLoop) initWorld

Or if you don't want to use the whole monad-loops package (even though it rocks)

main = loop initWorld
  where loop w = displayWorld w >> loop (gameLoop w)

Basically you're just drawing the world, then looping again to with the next state.

More likely you want something like this though

 -- False when the user wants to exit the game
 keepGoing :: World -> Bool

 main = iterateUntilM_ keepGoing displayLoop initWorld
   where displayLoop w = displayWorld w >> return (gameLoop w)

Since otherwise you can't stop :)

Xiao Jia

I think what you declared is a state transition function, and the game loop itself should be a recursive function. The general idea looks like this:

initialState :: World
nextState :: World -> World
isFinalState :: World -> Bool

gameLoop world | isFinalState world = -- ...
               | otherwise = do
                     drawScene world
                     gameLoop (nextState world)

main = gameLoop initialState

In initialState the initial world can be constructed with initial parameters, etc. And in nextState you can process player inputs (keyboards, etc.) which will change the state of the world. isFinalState is used to detect whether we should exit the game loop.

This structure is somewhat similar to that frequently used in Erlang, e.g. Query an Erlang process for its state?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!