16

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

gameLoop :: World -> World
-- ...

main :: IO ()称之为:

main = do
    gameLoop -- ...

但问题是我缺少对如何包装gameLoop函数以使其返回main参数值的一些基本理解。

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

4

2 回答 2

13

你可能会想要这样的东西

import Control.Monad.Loops

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

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

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

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

你更有可能想要这样的东西

 -- 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)

因为否则你不能停止:)

于 2013-10-10T01:55:17.007 回答
3

我认为你声明的是一个状态转换函数,游戏循环本身应该是一个递归函数。总体思路如下:

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

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

main = gameLoop initialState

initialState初始世界中,可以使用初始参数等构建。在nextState您可以处理将改变世界状态的玩家输入(键盘等)。 isFinalState用于检测我们是否应该退出游戏循环。

这种结构有点类似于 Erlang 中经常使用的结构,例如Query an Erlang process for its state?

于 2013-10-10T01:55:09.743 回答