Class: RubyTerminalGames::Board

Inherits:
Object
  • Object
show all
Defined in:
lib/ruby_terminal_games/board.rb

Direct Known Subclasses

Hangman::Board, Snake::Board, Sudoku::Board

Constant Summary collapse

EMPTY_CHAR =
" ".freeze
HORIZONTAL_LINE =
"─".freeze
VERTICAL_LINE =
"│".freeze
HORIZONTAL_DASHED_LINE =
"┄".freeze
VERTICAL_DASHED_LINE =
"┆".freeze
LEFT_TOP_CORNER =
"┌".freeze
RIGHT_TOP_CORNER =
"┐".freeze
LEFT_BOTTOM_CORNER =
"└".freeze
RIGHT_BOTTOM_CORNER =
"┘".freeze
CENTER_SEPARATOR =
"┼".freeze
LEFT_SEPARATOR =
"├".freeze
RIGHT_SEPARATOR =
"┤".freeze
BOTTOM_SEPARATOR =
"┴".freeze
TOP_SEPARATOR =
"┬".freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(width: nil, height: nil) ⇒ Board

Returns a new instance of Board.



19
20
21
22
23
# File 'lib/ruby_terminal_games/board.rb', line 19

def initialize(width: nil, height: nil)
  @rows, @cols = STDOUT.winsize
  @width = width || @cols
  @height = height || @rows
end

Instance Attribute Details

#colsObject

Returns the value of attribute cols.



18
19
20
# File 'lib/ruby_terminal_games/board.rb', line 18

def cols
  @cols
end

#heightObject

Returns the value of attribute height.



18
19
20
# File 'lib/ruby_terminal_games/board.rb', line 18

def height
  @height
end

#rowsObject

Returns the value of attribute rows.



18
19
20
# File 'lib/ruby_terminal_games/board.rb', line 18

def rows
  @rows
end

#widthObject

Returns the value of attribute width.



18
19
20
# File 'lib/ruby_terminal_games/board.rb', line 18

def width
  @width
end

Instance Method Details

#clear!Object



25
26
27
28
# File 'lib/ruby_terminal_games/board.rb', line 25

def clear!
  move_cursor(1, 1)
  rows.times { write(EMPTY_CHAR * cols) }
end

#draw_border!Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
# File 'lib/ruby_terminal_games/board.rb', line 39

def draw_border!
  (0..height).each do |i|
    write(VERTICAL_LINE, row: i, col: 0)
    write(VERTICAL_LINE, row: i, col: width)
  end

  (0..width).each do |i|
    write(HORIZONTAL_LINE, row: 0, col: i)
    write(HORIZONTAL_LINE, row: height, col: i)
  end

  write(LEFT_TOP_CORNER, row: 0, col: 0)
  write(RIGHT_BOTTOM_CORNER, row: height, col: width)
  write(RIGHT_TOP_CORNER, row: 0, col: width)
  write(LEFT_BOTTOM_CORNER, row: height, col: 0)
end

#move_cursor(row, col) ⇒ Object



35
36
37
# File 'lib/ruby_terminal_games/board.rb', line 35

def move_cursor(row, col)
  write("\e[#{row};#{col}H")
end

#write(text, row: nil, col: nil) ⇒ Object



30
31
32
33
# File 'lib/ruby_terminal_games/board.rb', line 30

def write(text, row: nil, col: nil)
  move_cursor(row, col) if (row && col)
  STDOUT.write(text)
end