class TicTacToe::Board

Constants

BLANK_SYMBOL

Public Class Methods

new(matrix_or_size) click to toggle source
# File lib/tic_tac_toe/board.rb, line 8
def initialize(matrix_or_size)
  @matrix =
    case matrix_or_size
    when Matrix  then matrix_or_size
    when Integer then Matrix.build(matrix_or_size) { BLANK_SYMBOL }
    end
end

Public Instance Methods

columns() click to toggle source
# File lib/tic_tac_toe/board.rb, line 46
def columns
  @matrix.transpose.to_a
end
diagonals() click to toggle source
# File lib/tic_tac_toe/board.rb, line 50
def diagonals
  (right_diagonals + left_diagonals)
    .map { |diagonal| diagonal.map { |field| @matrix[*field] } }
end
fields() click to toggle source
# File lib/tic_tac_toe/board.rb, line 16
def fields
  @matrix.each_with_index.map { |_, *field| field }
end
mark(field, symbol) click to toggle source
# File lib/tic_tac_toe/board.rb, line 24
def mark(field, symbol)
  new_matrix = @matrix.dup
  new_matrix.send(:[]=, *field, symbol)
  TicTacToe::Board.new(new_matrix)
end
marked?(field) click to toggle source
# File lib/tic_tac_toe/board.rb, line 30
def marked?(field)
  @matrix[*field] != BLANK_SYMBOL
end
rows() click to toggle source
# File lib/tic_tac_toe/board.rb, line 42
def rows
  @matrix.to_a
end
size() click to toggle source
# File lib/tic_tac_toe/board.rb, line 20
def size
  @matrix.row_count
end
to_s() click to toggle source
# File lib/tic_tac_toe/board.rb, line 34
def to_s
  table = TTY::Table.new(@matrix.to_a)
  table.render(:unicode) do |renderer|
    renderer.border.separator = :each_row
    renderer.padding = [0, 1, 0, 1]
  end
end

Private Instance Methods

left_diagonals() click to toggle source
    • x -

  • x - -

x - - -

      • -

# File lib/tic_tac_toe/board.rb, line 69
def left_diagonals
  fields.group_by { |x, y| x + y }.values
end
right_diagonals() click to toggle source
      • -

x - - -

  • x - -

    • x -

# File lib/tic_tac_toe/board.rb, line 61
def right_diagonals
  fields.group_by { |x, y| x - y }.values
end