在 Haskell 中等待然后检测按键的简单方法是什么?

发布于 2024-09-26 17:33:43 字数 135 浏览 1 评论 0原文

我对 Haskell 还很陌生,所以我正在寻找一种简单的方法来检测按键,而不是使用 getLine 。

如果有人知道任何库,或者知道一些这样做的技巧,那就太好了!

如果有更好的地方可以问这个问题,请直接告诉我,我将不胜感激。

I'm pretty new to Haskell, so I'm looking for a simple-ish way to detect keypresses, rather than using getLine.

If anyone knows any libraries, or some trick to doing this, it would be great!

And if there is a better place to ask this, please direct me there, I'd appreciate it.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

十年不长 2024-10-03 17:33:43

如果您不想阻塞,可以使用 hReady 来检测是否已按下某个键。这对于您希望程序运行并在按键发生时获取按键而不暂停游戏的游戏非常有用。

这是我为此使用的一个便利函数:

ifReadyDo :: Handle -> IO a -> IO (Maybe a)
ifReadyDo hnd x = hReady hnd >>= f
   where f True = x >>= return . Just
         f _    = return Nothing

可以像这样使用:

stdin `ifReadyDo` getChar

如果按下了一个键并且什么都没有,则返回一个Maybe,即Just否则。

If you don't want blocking you can use hReady to detect whether a key has been pressed yet. This is useful for games where you want the program to run and pick up a key press whenever it has happened without pausing the game.

Here's a convenience function I use for this:

ifReadyDo :: Handle -> IO a -> IO (Maybe a)
ifReadyDo hnd x = hReady hnd >>= f
   where f True = x >>= return . Just
         f _    = return Nothing

Which can be used like this:

stdin `ifReadyDo` getChar

Returning a Maybe that is Just if a key was pressed and Nothing otherwise.

趴在窗边数星星i 2024-10-03 17:33:43
import System.IO

main :: IO ()
main = do
  hSetBuffering stdin NoBuffering
  x <- getChar
  putStrLn ("You pressed: " ++ [x])

我不知道什么时候才能保证有效。将终端置于“原始”模式是一个依赖于系统的过程。但它对我来说适用于 Linux 上的 GHC 6.12.1。

import System.IO

main :: IO ()
main = do
  hSetBuffering stdin NoBuffering
  x <- getChar
  putStrLn ("You pressed: " ++ [x])

I don't know when this is guaranteed to work. Putting the terminal into a "raw" mode is a system-dependent process. But it works for me with GHC 6.12.1 on Linux.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文