Class: TerminalGameEngine::Frame

Inherits:
Object
  • Object
show all
Defined in:
lib/terminal_game_engine/frame.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(width, height) ⇒ Frame

Returns a new instance of Frame.



5
6
7
# File 'lib/terminal_game_engine/frame.rb', line 5

def initialize(width, height)
  @rows = height.times.map { ' ' * width }
end

Instance Attribute Details

#rowsObject (readonly)

Returns the value of attribute rows.



3
4
5
# File 'lib/terminal_game_engine/frame.rb', line 3

def rows
  @rows
end

Class Method Details

.clear_screenObject



55
56
57
# File 'lib/terminal_game_engine/frame.rb', line 55

def self.clear_screen
  print "\033[2J"
end

.disable_cursorObject



59
60
61
# File 'lib/terminal_game_engine/frame.rb', line 59

def self.disable_cursor
  print "\x1B[?25l"
end

.enable_cursorObject



63
64
65
# File 'lib/terminal_game_engine/frame.rb', line 63

def self.enable_cursor
  print "\x1B[?25h"
end

.move_cursor(x, y) ⇒ Object



51
52
53
# File 'lib/terminal_game_engine/frame.rb', line 51

def self.move_cursor(x, y)
  print "\033[#{y+1};#{x+1}H"
end

.setup(disable_cursor: true) ⇒ Object



67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
# File 'lib/terminal_game_engine/frame.rb', line 67

def self.setup(disable_cursor: true)
  clear_screen
  disable_cursor if disable_cursor

  $stdin.raw!
  at_exit do
    puts "\r"
    enable_cursor if disable_cursor
    $stdin.cooked!
    system 'stty sane'
  end

  trap 'WINCH' do
    clear_screen
  end
end

Instance Method Details

#draw(x, y, sprite) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/terminal_game_engine/frame.rb', line 17

def draw(x, y, sprite)
  lines = sprite.split("\n")

  lines.each_with_index do |line, i|
    if line.size > 0 && y+lines.size <= self.height && y+i >= 0
      # crop when drawing off left
      if x < 0
        line = line[x.abs..-1]
        x = 0
      end

      # crop when drawing off right
      if x+line.size-1 >= self.width
        line = line[0..(self.width-1)-(x+line.size)]
      end

      @rows[y+i][x..x+line.size-1] = line
    end
  end
end

#draw_center(y, sprite) ⇒ Object



38
39
40
41
42
# File 'lib/terminal_game_engine/frame.rb', line 38

def draw_center(y, sprite)
  sprite_width = sprite.split("\n").first.size
  x = self.width / 2 - sprite_width / 2
  draw x, y, sprite
end

#heightObject



13
14
15
# File 'lib/terminal_game_engine/frame.rb', line 13

def height
  @rows.size
end

#renderObject



44
45
46
47
48
49
# File 'lib/terminal_game_engine/frame.rb', line 44

def render
  @rows.each_with_index do |row, i|
    Frame.move_cursor 0, i
    print row
  end
end

#widthObject



9
10
11
# File 'lib/terminal_game_engine/frame.rb', line 9

def width
  @rows.first.size
end