【发布时间】:2021-10-05 22:35:26
【问题描述】:
我正在尝试编写一个简单的基于命令行的反射游戏,它会在随机时间后提示用户按 Enter,然后输出反应时间。我正在使用基于此示例的 reactimate:https://wiki.haskell.org/Yampa/reactimate 我的代码完全按照我的预期工作:
module Main where
import Control.Monad
import Data.IORef
import Data.Time.Clock
import System.Random
import FRP.Yampa
main :: IO ()
main = do
startTime <- getCurrentTime
startTimeRef <- newIORef startTime
randomTime <- randomRIO (0, 10)
reactimate helloMessage (sense startTimeRef) sayNow (randomTimePassed randomTime)
playerTime <- getCurrentTime
playerTimeRef <- newIORef playerTime
s <- getLine --programm will wait here
reactimate doNothing (sense playerTimeRef) endMessage (enterPressed s)
now <- getCurrentTime
let reactionTime = now `diffUTCTime` playerTime in putStr (show reactionTime)
helloMessage :: IO ()
helloMessage = putStrLn "Press Enter as quickly as possible when I say so..."
randomTimePassed :: Double -> SF () Bool
randomTimePassed r = time >>> arr (>r)
sayNow :: Bool -> Bool -> IO Bool
sayNow _ x = when x (putStrLn "NOW!") >> return x
doNothing :: IO ()
doNothing = return ()
enterPressed :: String -> SF () Bool --this is not how I want it to be
enterPressed s = arr (\_ -> s == "")
endMessage :: Bool -> Bool -> IO Bool
endMessage _ x = when x (putStr "You reacted in: ") >> return x
sense :: IORef UTCTime -> Bool -> IO (Double, Maybe ())
sense timeRef _ = do
now <- getCurrentTime
lastTime <- readIORef timeRef
writeIORef timeRef now
let dt = now `diffUTCTime` lastTime
return (realToFrac dt, Just ())
但是对于我在代码中标记的按下回车部分,它根本没有真正使用 FRP。由于程序只是等待 getLine 终止,然后立即结束反应循环。所以它几乎只是使用 IO Monad 而不是 FRP。有什么方法可以重构信号函数enterPressed,使其以“FRPish”方式工作?或者这在使用 reactimate 时根本不可能?
【问题讨论】:
-
将Yampa 与来自句柄(如stdin)的输入一起使用非常困难。也许试试
yampa-gloss或yampa-sdl2。它们具有内置的键盘输入感应功能。