我如何在Haskell中编写游戏循环? [英] How do I write a game loop in Haskell?

查看:134
本文介绍了我如何在Haskell中编写游戏循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  gameLoop :: World  - >世界
- ...

并有 main :: IO()调用它:

  main = do 
gameLoop - ...

但问题在于我缺少一些基本的理解,如何将 gameLoop 函数,以便它返回 main 的参数值。

我们将在Haskell中创建一个游戏循环?

解决方案

您可能需要类似这样的内容

  import Control.Monad.Loops 
$ b $ main = iterateM_
(\w - > displayWorld w> > return(gameLoop w))
initWorld
- iterateM_((>>)< $> displayWorld< return> gameLoop)initWorld

或者,如果您不想使用整个monad-loops软件包(尽管它很有可能)

  main = loop initWorld 
其中loop w = disp layWorld w>>循环(gameLoop w)

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



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

   -  - 当用户想要退出游戏时出错
KeepGoing :: World - > Bool

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

因为否则你不能停止:)

I want to code a game in Haskell where every iteration of the loop computes the state of the world. I thought I should create a function:

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

and have main :: IO () call it:

main = do
    gameLoop -- ...

But the problem is that I'm missing some fundamental understanding of how to wrap the gameLoop function so that it returns main's parameter value.

How would one go about creating a game loop in Haskell?

解决方案

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

这篇关于我如何在Haskell中编写游戏循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆