在Golang中的控制台键盘事件

huangapple go评论136阅读模式
英文:

Keyboard event on console in Golang

问题

我现在正在使用Golang创建基于CUI的扫雷游戏。
我想处理键盘事件来操作游戏。

你有什么办法可以实现这个吗?

英文:

I'm now creating CUI based mine sweeper in Golang.
And I would like to deal with keyboard events to manipulate the game.

Do you have any idea to achieve this?

答案1

得分: 2

每个操作系统处理键盘按键的方式略有不同。你可以编写一个库,将它们抽象成一个通用的接口,或者更好的是使用别人已经编写好的库。

如评论中所提到的,termbox-go 是一个不错的选择。它很稳定并且被广泛采用。

另一个不错的选择是 eiannone/keyboard,它更小巧,正在积极开发,并受到 termbox-go 的启发。

针对你的特定用例,你可能需要一个监听键盘事件的 Go 协程和一个处理这些事件的通道。以下是使用他们文档中的键盘库的示例代码:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/eiannone/keyboard"
  5. )
  6. func main() {
  7. keysEvents, err := keyboard.GetKeys(10)
  8. if err != nil {
  9. panic(err)
  10. }
  11. defer func() {
  12. _ = keyboard.Close()
  13. }()
  14. fmt.Println("Press ESC to quit")
  15. for {
  16. event := <-keysEvents
  17. if event.Err != nil {
  18. panic(event.Err)
  19. }
  20. fmt.Printf("You pressed: rune %q, key %X\r\n", event.Rune, event.Key)
  21. if event.Key == keyboard.KeyEsc {
  22. break
  23. }
  24. }
  25. }
英文:

Each operating system has a slightly different way of handling keyboard presses. You could write a library that abstracts these into a common interface, or better, use one that someone else already wrote.

As mentioned in the comments, termbox-go is a good option. It's stable and has broad adoption.

Another good option is eiannone/keyboard which is much smaller, actively developed and inspired by termbox-go.

For your specific use case you'll likely want to have a go routine that's listening to keyboard events and a channel that handles them. Here's the example using the keyboard library from their documentation.

  1. package main
  2. import (
  3. &quot;fmt&quot;
  4. &quot;github.com/eiannone/keyboard&quot;
  5. )
  6. func main() {
  7. keysEvents, err := keyboard.GetKeys(10)
  8. if err != nil {
  9. panic(err)
  10. }
  11. defer func() {
  12. _ = keyboard.Close()
  13. }()
  14. fmt.Println(&quot;Press ESC to quit&quot;)
  15. for {
  16. event := &lt;-keysEvents
  17. if event.Err != nil {
  18. panic(event.Err)
  19. }
  20. fmt.Printf(&quot;You pressed: rune %q, key %X\r\n&quot;, event.Rune, event.Key)
  21. if event.Key == keyboard.KeyEsc {
  22. break
  23. }
  24. }
  25. }

huangapple
  • 本文由 发表于 2015年5月12日 20:39:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/30191171.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定