class Board

Attributes

columns[R]
grid[R]
path_coords[RW]

the board class is, at its core, a 6x7 array of cell objects. The board class is also responsible for setting the correct searchpaths for the cells, which will be how the game searches for a winner.

rows[R]
winner[R]

Public Class Methods

new() click to toggle source
# File lib/connect_four.rb, line 26
def initialize
        @grid = create_board
        @rows = ("A".."F").to_a
        @columns = ("1".."7").to_a
        @path_coords = {:N =>[-1,0],:NE =>[-1,1],:E =>[0,1],:SE =>[1,1],:S =>[1,0],:SW =>[1,-1],:W =>[0,-1],:NW =>[-1,-1]}
end

Public Instance Methods

cell(a1,column = nil) click to toggle source
# File lib/connect_four.rb, line 33
def cell(a1,column = nil)
        #takes either an alphanumeric string argument (e.g. B3), or two Fixnums, and returns cell at those coordinates.
        a1.is_a?(String) ? @grid[@rows.index(a1[0].upcase)][@columns.index(a1[1])] : @grid[a1][column]
end
offset(cell_x_y, x_offset, y_offset) click to toggle source
# File lib/connect_four.rb, line 38
def offset(cell_x_y, x_offset, y_offset)
        @grid[cell_x_y.row + x_offset][cell_x_y.column + y_offset]
end

Private Instance Methods

create_board() click to toggle source
# File lib/connect_four.rb, line 43
def create_board #creates the board as 6x7 multidimensional array of Cell objects.
        board = Array.new(6){Array.new(7)}
        board.each_with_index do |row,row_number|
                row.each_index do |column_number|
                        board[row_number][column_number] = Cell.new({:row => row_number,:column => column_number})
                        set_search_paths(board[row_number][column_number])
                end
        end
        board #return the populated array of cell objects.
end
set_search_paths(cell) click to toggle source
# File lib/connect_four.rb, line 54
def set_search_paths(cell)
        #adds search paths to the appropriate cells. For example, the bottom left cell will get N, NE, and E searchpaths,
        #since SE,S,SW,W,or NW paths would take us off the board. These searchpaths are how we test for a winner,
        #without searching every possible winning configuration.
        if cell.row > 2
                cell.add_search_path(:N) 
        end

        if (cell.row >2) && (cell.column < 4)
                cell.add_search_path(:NE) 
        end

        if cell.column < 4
                cell.add_search_path(:E) 
        end

        if (cell.row<3) && (cell.column < 4)
                cell.add_search_path(:SE)
        end

        if cell.row < 3
                cell.add_search_path(:S)
        end

        if (cell.row<3)&&(cell.column>2)
                cell.add_search_path(:SW)
        end

        if (cell.column > 2)
                cell.add_search_path(:W)
        end

        if (cell.row>2)&&(cell.column>2)
                cell.add_search_path(:NW)
        end
end