功能香蕉旅行者 - 将行为放在一起游戏状态

时间:2012-10-23 17:04:13

标签: haskell frp reactive-banana

问题是我不知道如何创建Behavior t GameState

类型的行为

我有更多的代码,但我试图展示我认为有必要谈论这个问题。如果有空白填写,请告诉我。这就是我所拥有的:

data GameState = GameState {agent    :: Agent
                           ,universe :: Universe
                           }

type Universe = Gr Planet ()

data Command = Move PlanetName
             | Look
             | Quit
                 deriving Show

data PlayerCommand = PlayerCommand Command PID
                   | Null
                       deriving Show

updateGS :: PlayerCommand -> GameState -> GameState
updateGS (PlayerCommand (Move planet) pid) gs =
   let agent = getAgent pid gs
       nodes = labNodes $ universe gs
       current = location agent
       Just fromP = lookup (fromEnum current) nodes
       Just toP   = lookup (fromEnum planet) nodes
       fromNode = fromEnum current
       toNode = fromEnum planet
       uPlayer = Player pid (getPlanetName toP) (Location planet)
       mData = MoveData uPlayer (toNode,toP) (fromNode,fromP) nodes
       uPlanets = updateLNodeList mData
   in GameState uPlayer (mkGraph uPlanets $ labUEdges gates

initialGS :: GameState
initialGS = GameState initPlayer (makeUniverse makePlanetNodes)

和事件网络

makeNetworkDescription :: AddHandler PlayerCommand -> IO EventNetwork
makeNetworkDescription addCommandEvent = compile $ do
   eInput <- fromAddHandler addCommandEvent
   let bCommand = stepper Null eInput
   eCommandChanged <- changes bCommand
   let bGameState :: Behavior t GameState
       bGameState = stepper initialGS 
   reactimate $ (\n -> appendFile "output.txt" ("Command is " ++ show n)) <$> eCommandChanged

我相信bGameState需要使用eCommandChange,但我遇到类型问题

stepper :: a -> Event t a -> Behavior t a

这让我相信我需要将eInput :: Event t PlayerCommand转换成一个 eGameState :: Event t GameState,我可以使用stepper制作Behavior t GameState

所以,我的问题是,我的思路是正确的吗?如果没有,我可以被重定向吗?如果是这样,eGameState :: Event t GameState会是什么样的?

回应以下回复。当我最初考虑accumB时,我发现了一个类型错误。当我尝试你的建议时会发生什么。

let bGameState :: Behavior t GameState
    bGameState = accumB initialGS $ updateGS <$ eInput

产生错误

 Couldn't match expected type `GameState'
             with actual type `PlayerCommand'
 Expected type: GameState -> GameState
   Actual type: PlayerCommand -> GameState -> GameState
 In the first argument of `(<$)', namely `updateGS'
 In the second argument of `($)', namely `updateGS <$ eInput'

不知道该怎么做。我会看看你的例子,看看答案是否清楚。感谢您选择accumB是正确的方法,因为我专注于stepper

我研究建议的代码越多,我对类型错误感到困惑就越多。

1 个答案:

答案 0 :(得分:2)

确实,您需要创建一个记住GameState的事件,并将updateGS函数应用于该事件以创建新事件。这就是函数accumE及其表兄accumB的目的。特别是,你可以写

bGameState = accumB initialGS $ updateGS <$> eInput

要了解有关此模式的更多信息,请查看examples pages上的示例,特别是Counter.hs和TwoCounters.hs示例。


值得一提的另一点是,我建议避免changes函数,除非你正在处理低级框​​架的东西。如文档中所述,它有几个限制;最糟糕的限制是在reactimate执行之前该值不可用。你可以轻松地以这种方式进行无限循环,其目的非常狭窄。

在你的情况下,bCommand似乎是多余的,你有eCommandChanged = eInput

士气:将事件变成一种行为很容易,但是没有办法回来。