Class: Board

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeBoard

Returns a new instance of Board.



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

def initialize
  @grid = [[nil, nil, nil],
           [nil, nil, nil],
           [nil, nil, nil]]
end

Instance Attribute Details

#gridObject

Returns the value of attribute grid.



2
3
4
# File 'lib/board.rb', line 2

def grid
  @grid
end

Instance Method Details

#add_piece(player_token, location) ⇒ Object

adds a piece to the grid indexes start at 0 from the top left corner of the grid



37
38
39
40
41
42
43
44
# File 'lib/board.rb', line 37

def add_piece(player_token, location)
  if validate_move(location)
    @grid[location.first][location.last] = player_token  
    return true
  else
    return false
  end
end

#available_spacesObject

checks for empty(nil) spaces on the grid



19
20
21
22
23
24
25
26
27
# File 'lib/board.rb', line 19

def available_spaces
  spaces = []
  @grid.each_with_index do |column, col_index|
    column.each_with_index do |space, row_index|
      spaces << [col_index, row_index] if space == nil
    end
  end
  spaces
end

#calculate_winObject

determines if there is a winning player and returns that player token



47
48
49
50
51
52
# File 'lib/board.rb', line 47

def calculate_win
  return diagonal_win if diagonal_win
  return horizontal_win if horizontal_win
  return vertical_win if vertical_win
  return 'nobody' if cat_game?
end

#cloneObject



10
11
12
13
14
15
16
# File 'lib/board.rb', line 10

def clone
  board = Board.new
  board.grid = [[@grid[0][0], @grid[0][1], @grid[0][2]],
                [@grid[1][0], @grid[1][1], @grid[1][2]],
                [@grid[2][0], @grid[2][1], @grid[2][2]]]
  return board
end


54
55
56
# File 'lib/board.rb', line 54

def print
  "\n#{@grid[0]}\n#{@grid[1]}\n#{@grid[2]}\n"
end

#validate_move(location) ⇒ Object



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

def validate_move(location)
  if location.first && location.last
    return @grid[location.first][location.last].nil?
  end
end