-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcursor.rb
106 lines (90 loc) · 2.18 KB
/
cursor.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
# frozen_string_literal: true
require 'io/console'
require_relative 'board'
KEYMAP = {
' ' => :space,
'h' => :left,
'j' => :down,
'k' => :up,
'l' => :right,
'w' => :up,
'a' => :left,
's' => :down,
'd' => :right,
"\t" => :tab,
"\r" => :return,
"\n" => :newline,
"\e" => :escape,
"\e[A" => :up,
"\e[B" => :down,
"\e[C" => :right,
"\e[D" => :left,
"\177" => :backspace,
"\004" => :delete,
"\u0003" => :ctrl_c
}.freeze
MOVES = {
left: [0, -1],
right: [0, 1],
up: [-1, 0],
down: [1, 0]
}.freeze
class Cursor
attr_reader :cursor_pos, :board, :selected
def initialize(cursor_pos, board)
@cursor_pos = cursor_pos
@board = board
@selected = false
end
def get_input
key = KEYMAP[read_char]
handle_key(key)
end
private
def read_char
STDIN.echo = false # stops the console from printing return values
STDIN.raw! # in raw mode data is given as is to the program--the system
# doesn't preprocess special characters such as control-c
input = STDIN.getc.chr # STDIN.getc reads a one-character string as a
# numeric keycode. chr returns a string of the
# character represented by the keycode.
# (e.g. 65.chr => "A")
if input == "\e"
begin
input << STDIN.read_nonblock(3)
rescue StandardError
nil
end # read_nonblock(maxlen) reads
# at most maxlen bytes from a
# data stream; it's nonblocking,
# meaning the method executes
# asynchronously; it raises an
# error if no data is available,
# hence the need for rescue
begin
input << STDIN.read_nonblock(2)
rescue StandardError
nil
end
end
STDIN.echo = true # the console prints return values again
STDIN.cooked! # the opposite of raw mode :)
input
end
def handle_key(key)
case key
when :return, :space
@selected = !@selected
@cursor_pos
when :left, :right, :up, :down
update_pos(MOVES[key])
nil
when :ctrl_c
Process.exit(0)
end
end
def update_pos(diff)
check_pos = [@cursor_pos[0] + diff[0], @cursor_pos[1] + diff[1]]
@cursor_pos = check_pos if @board.valid_pos?(check_pos)
end
end