class Board
Attributes
height[R]
width[R]
Public Class Methods
from_a(arr, connect_n = 4)
click to toggle source
# File lib/command_four/board.rb, line 50 def self.from_a(arr, connect_n = 4) board = Board.new(arr.length, arr[0].length, connect_n) for i in 0...arr[0].length for j in 0...arr.length if arr[j][i] != :empty board.drop_piece(j, arr[j][i]) end end end board end
new(width = 7, height = 6, connect_n = 4)
click to toggle source
# File lib/command_four/board.rb, line 4 def initialize(width = 7, height = 6, connect_n = 4) @width = width @height = height @connect_n = connect_n @state = GameState.new(false, []) @board = Array.new(@width) {Array.new(@height, :empty)} @completed_moves = 0 @max_moves = width * height end
Public Instance Methods
drop_piece(column, color)
click to toggle source
# File lib/command_four/board.rb, line 14 def drop_piece(column, color) if game_over?() raise PieceDropError.new("Game is already over") elsif invalid_index?(column) raise PieceDropError.new("Invalid column index: #{column}") elsif full?(column) raise PieceDropError.new("Column #{column} is already full") else first_empty_cell_index = @board[column].index {|cell| cell == :empty} @board[column][first_empty_cell_index] = color @completed_moves += 1 @state = ConnectNChecker.new(@board, @connect_n, column, first_empty_cell_index).check if @completed_moves >= @max_moves && !game_over?() @state = GameState.new(true, []) end end end
game_over?()
click to toggle source
# File lib/command_four/board.rb, line 32 def game_over? @state.game_over? end
to_a()
click to toggle source
# File lib/command_four/board.rb, line 62 def to_a @board end
winning_cells()
click to toggle source
# File lib/command_four/board.rb, line 36 def winning_cells @state.winning_cells end
winning_color()
click to toggle source
# File lib/command_four/board.rb, line 40 def winning_color if @state.winning_cells.length > 0 col_idx = @state.winning_cells[0][0] row_idx = @state.winning_cells[0][1] @board[col_idx][row_idx] else nil end end
Private Instance Methods
full?(column)
click to toggle source
# File lib/command_four/board.rb, line 75 def full?(column) @board[column][-1] != :empty end
invalid_index?(column)
click to toggle source
# File lib/command_four/board.rb, line 71 def invalid_index?(column) column < 0 || column >= @width end