在Golang中的控制台键盘事件

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

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 (
	&quot;fmt&quot;
	&quot;github.com/eiannone/keyboard&quot;
)

func main() {
	keysEvents, err := keyboard.GetKeys(10)
	if err != nil {
		panic(err)
	}
	defer func() {
		_ = keyboard.Close()
	}()

	fmt.Println(&quot;Press ESC to quit&quot;)
	for {
		event := &lt;-keysEvents
		if event.Err != nil {
			panic(event.Err)
		}
		fmt.Printf(&quot;You pressed: rune %q, key %X\r\n&quot;, event.Rune, event.Key)
		if event.Key == keyboard.KeyEsc {
			break
		}
	}
}

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:

确定