aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJoop Kiefte <ikojba@gmail.com>2020-08-31 04:55:26 +0200
committerJoop Kiefte <ikojba@gmail.com>2020-08-31 04:55:26 +0200
commitae8090cd4dea0df8f3d3a0dec668d94bd7068e9d (patch)
treebeb50dd59832cecbabecfeafbcac9c7a5343e9b2
parentd4ba62ce1cd608d751a9d5db2e30608687a2e58e (diff)
Factor out the keycode grabbing code
-rw-r--r--main.go19
1 files changed, 13 insertions, 6 deletions
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] {