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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of Board.



5
6
7
8
9
# File 'lib/ruby_terminal_games/board.rb', line 5

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.



4
5
6
# File 'lib/ruby_terminal_games/board.rb', line 4

def cols
  @cols
end

#heightObject

Returns the value of attribute height.



4
5
6
# File 'lib/ruby_terminal_games/board.rb', line 4

def height
  @height
end

#rowsObject

Returns the value of attribute rows.



4
5
6
# File 'lib/ruby_terminal_games/board.rb', line 4

def rows
  @rows
end

#widthObject

Returns the value of attribute width.



4
5
6
# File 'lib/ruby_terminal_games/board.rb', line 4

def width
  @width
end

Instance Method Details

#clear!Object



11
12
13
14
# File 'lib/ruby_terminal_games/board.rb', line 11

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

#draw_border!Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/ruby_terminal_games/board.rb', line 25

def draw_border!
  # Left and right border
  (0..height).each do |i|
    write("", row: i, col: 0)
    write("", row: i, col: width)
  end

  # Top and bottom border
  (0..width).each do |i|
    write("", row: 0, col: i)
    write("", row: height, col: i)
  end

  # Corners
  write("", row: 0, col: 0)
  write("", row: height, col: width)
  write("", row: 0, col: width)
  write("", row: height, col: 0)
end

#move_cursor(row, col) ⇒ Object



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

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

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



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

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