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?
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?
 
    
    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
        }
    }
}
