英文:
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 协程和一个处理这些事件的通道。以下是使用他们文档中的键盘库的示例代码:
package main
import (
"fmt"
"github.com/eiannone/keyboard"
)
func main() {
keysEvents, err := keyboard.GetKeys(10)
if err != nil {
panic(err)
}
defer func() {
_ = keyboard.Close()
}()
fmt.Println("Press ESC to quit")
for {
event := <-keysEvents
if event.Err != nil {
panic(event.Err)
}
fmt.Printf("You pressed: rune %q, key %X\r\n", event.Rune, event.Key)
if event.Key == keyboard.KeyEsc {
break
}
}
}
英文:
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.
package main
import (
"fmt"
"github.com/eiannone/keyboard"
)
func main() {
keysEvents, err := keyboard.GetKeys(10)
if err != nil {
panic(err)
}
defer func() {
_ = keyboard.Close()
}()
fmt.Println("Press ESC to quit")
for {
event := <-keysEvents
if event.Err != nil {
panic(event.Err)
}
fmt.Printf("You pressed: rune %q, key %X\r\n", event.Rune, event.Key)
if event.Key == keyboard.KeyEsc {
break
}
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论