如何在Haskell中编写游戏循环?

sda*_*das 15 haskell functional-programming game-loop

我想在Haskell中编写一个游戏,循环的每次迭代都会计算出世界的状态.我以为我应该创建一个函数:

gameLoop :: World -> World
-- ...
Run Code Online (Sandbox Code Playgroud)

main :: IO ()称之为:

main = do
    gameLoop -- ...
Run Code Online (Sandbox Code Playgroud)

但问题是我缺少一些基本的理解如何包装gameLoop函数,以便它返回main的参数值.

如何在Haskell中创建游戏循环?

Dan*_*zer 13

你可能想要这样的东西

import Control.Monad.Loops

main = iterateM_ 
       (\w -> displayWorld w >> return (gameLoop w))
       initWorld
-- iterateM_ ((>>) <$> displayWorld <*> return . gameLoop) initWorld
Run Code Online (Sandbox Code Playgroud)

或者,如果你不想使用整个monad-loops包(即使它摇滚)

main = loop initWorld
  where loop w = displayWorld w >> loop (gameLoop w)
Run Code Online (Sandbox Code Playgroud)

基本上你只是画世界,然后再循环到下一个状态.

你更想要这样的东西

 -- 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)
Run Code Online (Sandbox Code Playgroud)

因为否则你不能停止:)