From ae8090cd4dea0df8f3d3a0dec668d94bd7068e9d Mon Sep 17 00:00:00 2001 From: Joop Kiefte Date: Mon, 31 Aug 2020 04:55:26 +0200 Subject: Factor out the keycode grabbing code --- main.go | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) (limited to 'main.go') diff --git a/main.go b/main.go index fb8d913..3de2cd5 100644 --- a/main.go +++ b/main.go @@ -61,6 +61,18 @@ func (f Field) String() (output string) { return output } +// GetKey() returns the key currently pressed. It always returns a 3 byte slice. Check first element for Escape for handling arrow keys +// Because a defer would trigger too late and the Restore and Close are essential, separated in a function. +func GetKey() []byte { + t, _ := term.Open("/dev/tty") + term.RawMode(t) + key := make([]byte, 3) + t.Read(key) + t.Restore() + t.Close() + return key +} + func main() { var f Field fmt.Print("\033[2J") // Clear screen @@ -73,12 +85,7 @@ func main() { f[p.Y][p.X] = true fmt.Print("\033[0;0H") // Position to 0,0 fmt.Println(f.String()) - t, _ := term.Open("/dev/tty") - term.RawMode(t) - key := make([]byte, 3) - t.Read(key) - t.Restore() - t.Close() + key := GetKey() switch key[0] { case 27: // Escape, read the arrow key pressed switch key[2] { -- cgit v1.2.3-70-g09d2