diff options
author | Joop Kiefte <ikojba@gmail.com> | 2020-08-31 04:55:26 +0200 |
---|---|---|
committer | Joop Kiefte <ikojba@gmail.com> | 2020-08-31 04:55:26 +0200 |
commit | ae8090cd4dea0df8f3d3a0dec668d94bd7068e9d (patch) | |
tree | beb50dd59832cecbabecfeafbcac9c7a5343e9b2 | |
parent | d4ba62ce1cd608d751a9d5db2e30608687a2e58e (diff) |
Factor out the keycode grabbing code
-rw-r--r-- | main.go | 19 |
1 files changed, 13 insertions, 6 deletions
@@ -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] { |