Class: Termfront::Input
- Inherits:
-
Object
- Object
- Termfront::Input
- Defined in:
- lib/termfront/input.rb
Instance Method Summary collapse
- #clear ⇒ Object
-
#initialize ⇒ Input
constructor
A new instance of Input.
- #key?(sym) ⇒ Boolean
- #process(stdin, player: nil) ⇒ Object
- #read_keys(stdin) ⇒ Object
Constructor Details
#initialize ⇒ Input
Returns a new instance of Input.
5 6 7 8 |
# File 'lib/termfront/input.rb', line 5 def initialize @key_state = {} @pending = +"" end |
Instance Method Details
#clear ⇒ Object
70 71 72 73 |
# File 'lib/termfront/input.rb', line 70 def clear @key_state.clear @pending.clear end |
#key?(sym) ⇒ Boolean
66 67 68 |
# File 'lib/termfront/input.rb', line 66 def key?(sym) @key_state[sym] end |
#process(stdin, player: nil) ⇒ Object
56 57 58 59 60 61 62 63 64 |
# File 'lib/termfront/input.rb', line 56 def process(stdin, player: nil) keys = read_keys(stdin) @key_state.each_key { |k| @key_state[k] -= 1 } @key_state.delete_if { |_, v| v <= 0 } keys.each { |k| @key_state[k] = Config::KEY_TIMEOUT } keys end |
#read_keys(stdin) ⇒ Object
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 |
# File 'lib/termfront/input.rb', line 10 def read_keys(stdin) keys = [] while IO.select([stdin], nil, nil, 0) begin @pending << stdin.read_nonblock(64) rescue IO::WaitReadable break end end i = 0 while i < @pending.bytesize ch = @pending.getbyte(i) if ch == 27 if @pending.getbyte(i + 1) == 91 && (code = @pending.getbyte(i + 2)) case code when 65 then keys << :up when 66 then keys << :down when 67 then keys << :right when 68 then keys << :left end i += 3 else keys << :esc i += 1 end else case ch when 119 then keys << :w when 97 then keys << :a when 115 then keys << :s when 100 then keys << :d when 32 then keys << :space when 113 then keys << :q when 116 then keys << :t when 101 then keys << :e end i += 1 end end @pending.clear keys end |