这是我Traveller项目的一个å问题。
我把处ç†è¾“入的粗俗代ç 放在一起。它有效,直到我å‘æ··åˆä¸å¼•å…¥TChan
。下é¢æ˜¯å·¥ä½œä»£ç ,以åŠå¦‚何使用它的示例。然åŽï¼Œæˆ‘将改å˜å®ƒå¹¶è§£é‡Šæˆ‘ä¸ºä»€ä¹ˆè¿™æ ·åšã€‚然åŽï¼Œæˆ‘将谈论这个问题。
{-# LANGUAGE ScopedTypeVariables #-}
import Control.Monad (forever)
import Control.Concurrent (forkIO)
import Control.Monad.STM (STM,atomically)
import Control.Concurrent.STM.TChan
import Reactive.Banana
import Reactive.Banana.Frameworks
data Planet = Vulcan
| Mars
| Terra
deriving (Eq,Read,Show)
data Command = Move Planet
| Look
| Quit
| Null
deriving Show
makeNetworkDescription :: AddHandler (Maybe Command) -> IO EventNetwork
makeNetworkDescription addCommandEvent = compile $ do
eInput <- fromAddHandler addCommandEvent
let eCommand = filterJust eInput
bCommand = stepper Null eCommand
eCommandChanged <- changes bCommand
reactimate $ (\n -> appendFile "output.txt" ("Command is " ++ show n)) <$>
eCommandChanged
在ghci
ä¸æ‰§è¡Œä»¥ä¸‹æ“作将è¯æ˜Žè¿™æ˜¯æœ‰æ•ˆçš„。
(addCommandEvent,fireCommand) <- newAddHandler :: IO (AddHandler (Maybe Command),Maybe Command -> IO ())
networkDescr <- makeNetworkDescription addCommandEvent
actuate networkDescr
return (Just $ Look) >>= fireCommand
所以,现在我已ç»æœ‰äº†åŸºæœ¬çš„机制,我想开始构建它。这将是一个多人游æˆã€‚到目å‰ä¸ºæ¢ï¼Œè¾“入处ç†çš„第一æ¥æ˜¯ä»ŽTChan
获å–输入。这个想法是,所有玩家都会写入æ¤TChan
,并且æ¯ä¸ªå‘½ä»¤éƒ½ä¼šæŒ‰ç…§å®ƒåˆ°è¾¾çš„顺åºè¿›è¡Œå¤„ç†ã€‚
æ‰€ä»¥æˆ‘æ·»åŠ äº†ä¸€ä¸ªæ–°åŠŸèƒ½'inputFrame'
inputFrame :: TChan Command -> IO ()
inputFrame commandChannel = do
(addCommandEvent,fireCommand) <- newAddHandler
networkDescr <- makeNetworkDescription addCommandEvent
actuate networkDescr
forkIO $ forever (atomically $ tryReadTChan commandChannel) >>= fireCommand
return ()
以下是我在ghci
ä¸å°è¯•ä½¿ç”¨å®ƒçš„方法。
commandChan <- atomically $ newTChan :: IO (TChan Command)
_ <- atomically $ writeTChan commandChan Look
output.txt
æ— æ³•å†™å…¥ã€‚æ£åœ¨è¯»å–commandChan
ï¼Œå› ä¸ºæˆ‘æ£€æŸ¥å®ƒæ˜¯å¦åœ¨å¡«å……åŽå˜ä¸ºç©ºã€‚我åšé”™äº†å¾ˆæ˜Žæ˜¾å—?如果没有,我该如何解决问题呢?å¦å¤–,对于我的预期目的,TChan
是æ£ç¡®çš„选择å—?
ç”案 0 :(得分:2)
ä½ å¯èƒ½æƒ³è¦
forkIO $ forever (atomically (tryReadTChan commandChannel) >>= fireCommand)
但我没有测试过这个。å¦å¤–,猜测一下,您å¯èƒ½å¸Œæœ›é¿å…tryReadTChan
。åªéœ€ä½¿ç”¨æ™®é€šçš„readTChan
,就å¯ä»¥èŽ·å¾—有效的retry
而ä¸æ˜¯è½®è¯¢ã€‚