-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcursorable.rb
executable file
·61 lines (52 loc) · 1019 Bytes
/
cursorable.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
require "io/console"
module Cursorable
KEYMAP = {
" " => :space,
"w" => :up,
"\e[A" => :up,
"\e[B" => :down,
"\e[C" => :right,
"\e[D" => :left,
"\u0003" => :ctrl_c,
}
MOVES = {
left: [0, -1],
right: [0, 1],
up: [-1, 0],
down: [1, 0]
}
def get_input
key = KEYMAP[read_char]
handle_key(key)
end
def handle_key(key)
case key
when :ctrl_c
exit 0
when :space
@cursor_pos
when :left, :right, :up, :down
update_pos(MOVES[key])
nil
else
puts key
end
end
def read_char
STDIN.echo = false
STDIN.raw!
input = STDIN.getc.chr
if input == "\e" then
input << STDIN.read_nonblock(3) rescue nil
input << STDIN.read_nonblock(2) rescue nil
end
ensure
STDIN.echo = true
STDIN.cooked!
return input
end
def update_pos(diff)
new_pos = [@cursor_pos[0] + diff[0], @cursor_pos[1] + diff[1]]
@cursor_pos = new_pos if @board.in_bounds?(new_pos)
end
end