Class: OXO::Board
- Inherits:
-
Object
- Object
- OXO::Board
- Defined in:
- lib/oxo/board.rb
Instance Attribute Summary collapse
-
#cols ⇒ Object
Returns the value of attribute cols.
-
#rows ⇒ Object
Returns the value of attribute rows.
Instance Method Summary collapse
- #full? ⇒ Boolean
-
#initialize ⇒ Board
constructor
A new instance of Board.
- #legal_move?(row, col) ⇒ Boolean
- #legal_moves ⇒ Object
- #place(color, row, col) ⇒ Object
- #to_s ⇒ Object
- #win?(color) ⇒ Boolean
Constructor Details
#initialize ⇒ Board
Returns a new instance of Board.
8 9 10 11 |
# File 'lib/oxo/board.rb', line 8 def initialize @rows, @cols = 3, 3 @board = Array.new(@rows) { Array.new(@cols) } end |
Instance Attribute Details
#cols ⇒ Object
Returns the value of attribute cols.
6 7 8 |
# File 'lib/oxo/board.rb', line 6 def cols @cols end |
#rows ⇒ Object
Returns the value of attribute rows.
6 7 8 |
# File 'lib/oxo/board.rb', line 6 def rows @rows end |
Instance Method Details
#full? ⇒ Boolean
35 36 37 |
# File 'lib/oxo/board.rb', line 35 def full? !@board.flatten.include? nil end |
#legal_move?(row, col) ⇒ Boolean
13 14 15 |
# File 'lib/oxo/board.rb', line 13 def legal_move?(row, col) on_board?(row, col) && !piece_at(row, col) end |
#legal_moves ⇒ Object
23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/oxo/board.rb', line 23 def legal_moves empty_squares = [] 1.upto(rows) do |row| 1.upto(cols) do |col| empty_squares << [row, col] unless piece_at(row, col) end end empty_squares end |
#place(color, row, col) ⇒ Object
17 18 19 20 21 |
# File 'lib/oxo/board.rb', line 17 def place(color, row, col) return unless legal_move?(row, col) @board[row - 1][col - 1] = color end |
#to_s ⇒ Object
48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
# File 'lib/oxo/board.rb', line 48 def to_s output = "\n".dup hline = "+---" * @cols << "+\n" characters = @board.map {|row| row.map {|pos| pos.to_s.ljust(1) } } output << hline characters.each do |row| output << "| " << row.join(" | ") << " |" << "\n" output << hline end output << "\n" end |
#win?(color) ⇒ Boolean
39 40 41 42 43 44 45 46 |
# File 'lib/oxo/board.rb', line 39 def win?(color) @board.each {|row| return true if row.uniq == [color] } @board.transpose.each {|col| return true if col.uniq == [color] } return true if @board.flatten.values_at(0, 4, 8).uniq == [color] return true if @board.flatten.values_at(2, 4, 6).uniq == [color] false end |