Class: Connect::Computer
- Inherits:
-
Object
- Object
- Connect::Computer
- Defined in:
- lib/connect/computer.rb
Instance Attribute Summary collapse
-
#piece ⇒ Object
readonly
Returns the value of attribute piece.
Instance Method Summary collapse
- #find_block_column(board) ⇒ Object
- #find_column(piece, board) ⇒ Object
- #find_random_column(board) ⇒ Object
- #find_win_column(board) ⇒ Object
-
#initialize ⇒ Computer
constructor
A new instance of Computer.
- #make_move(board) ⇒ Object
Constructor Details
#initialize ⇒ Computer
Returns a new instance of Computer.
6 7 8 |
# File 'lib/connect/computer.rb', line 6 def initialize @piece = 'O' end |
Instance Attribute Details
#piece ⇒ Object (readonly)
Returns the value of attribute piece.
4 5 6 |
# File 'lib/connect/computer.rb', line 4 def piece @piece end |
Instance Method Details
#find_block_column(board) ⇒ Object
34 35 36 37 |
# File 'lib/connect/computer.rb', line 34 def find_block_column(board) piece = 'X' find_column(piece, board) end |
#find_column(piece, board) ⇒ Object
39 40 41 42 43 44 45 46 47 48 49 |
# File 'lib/connect/computer.rb', line 39 def find_column(piece, board) columns = ('A'..'G').to_a columns.each do |column| board_copy = Board.new board_copy.cells = board.dup.cells.map(&:dup) board_copy.add_piece(column, piece) return column if board_copy.win? end nil end |
#find_random_column(board) ⇒ Object
24 25 26 27 |
# File 'lib/connect/computer.rb', line 24 def find_random_column(board) columns = ('A'..'G').to_a columns.sample end |
#find_win_column(board) ⇒ Object
29 30 31 32 |
# File 'lib/connect/computer.rb', line 29 def find_win_column(board) piece = @piece find_column(piece, board) end |
#make_move(board) ⇒ Object
10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/connect/computer.rb', line 10 def make_move(board) win = find_win_column(board) block = find_block_column(board) random = find_random_column(board) if win board.add_piece(win, @piece) elsif block board.add_piece(block, @piece) else board.add_piece(random, @piece) end end |