3

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?

ami_GS
  • 852
  • 15
  • 21
  • 1
    The [termbox-go](https://github.com/nsf/termbox-go) library is commonly used for this. –  May 12 '15 at 13:54
  • 2
    possible duplicate of [How to react to keypress events in Go?](http://stackoverflow.com/questions/27198193/how-to-react-to-keypress-events-in-go) or [Golang function similar to getchar](http://stackoverflow.com/questions/14094190/golang-function-similar-to-getchar) – Dave C May 12 '15 at 15:35

1 Answers1

2

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
        }
    }
}
spf13
  • 561
  • 3
  • 9