Class: RichEngine::IO Private

Inherits:
Object
  • Object
show all
Defined in:
lib/rich_engine/io.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

Internal plumbing that bridges Game and the terminal: it flushes the canvas to $stdout (with render caching) and reads non-blocking keyboard input, translating escape sequences into key symbols.

Instance Method Summary collapse

Constructor Details

#initialize(width, height) ⇒ IO

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of IO.

Parameters:

  • width (Integer)

    the screen width in characters

  • height (Integer)

    the screen height in characters



18
19
20
21
22
# File 'lib/rich_engine/io.rb', line 18

def initialize(width, height)
  @screen_width = width
  @screen_height = height
  delete_cache
end

Instance Method Details

#read_asyncSymbol?

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Reads a single keypress without blocking, decoding multi-byte escape sequences (arrows, page keys, etc.) into key symbols.

Returns:

  • (Symbol, nil)

    the key pressed (e.g. :q, :up, :space, :esc), or nil if no input was waiting



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/rich_engine/io.rb', line 47

def read_async
  $stdin.raw do |io|
    key = $stdin.read_nonblock(2)
    _c1, c2 = key.chars

    if c2 && csi?(key)
      c3, c4 = $stdin.read_nonblock(2).chars

      if digit?(c3)
        symbolize_key("#{key}#{c3}#{c4}")
      else
        symbolize_key("#{key}#{c3}")
      end
    else
      symbolize_key(key)
    end
  rescue ::IO::WaitReadable
    nil
  end
end

#write(canvas, use_caching:) ⇒ Symbol

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Renders the canvas to $stdout, skipping the write when the canvas is unchanged since the last frame.

Parameters:

  • canvas (Array)

    the flat array of canvas cells to draw

  • use_caching (Boolean)

    when false, the render cache is dropped so the canvas is always redrawn

Returns:

  • (Symbol)

    :cache_hit when the frame was skipped, :cache_miss otherwise



32
33
34
35
36
37
38
39
40
# File 'lib/rich_engine/io.rb', line 32

def write(canvas, use_caching:)
  delete_cache unless use_caching

  with_caching(canvas) do
    Terminal::Cursor.goto(0, 0)
    output = build_output(canvas)
    $stdout.write output
  end
end