Class: Ai
- Inherits:
-
Object
- Object
- Ai
- Defined in:
- lib/ai.rb
Instance Attribute Summary collapse
-
#choice ⇒ Object
readonly
Returns the value of attribute choice.
-
#mark ⇒ Object
readonly
Returns the value of attribute mark.
Instance Method Summary collapse
-
#initialize(mark, manager) ⇒ Ai
constructor
A new instance of Ai.
- #score(board, mark) ⇒ Object
- #score_moves(board, mark, depth, scores) ⇒ Object
- #smart_move(board) ⇒ Object
Constructor Details
Instance Attribute Details
#choice ⇒ Object (readonly)
Returns the value of attribute choice.
5 6 7 |
# File 'lib/ai.rb', line 5 def choice @choice end |
#mark ⇒ Object (readonly)
Returns the value of attribute mark.
5 6 7 |
# File 'lib/ai.rb', line 5 def mark @mark end |
Instance Method Details
#score(board, mark) ⇒ Object
13 14 15 16 17 18 19 |
# File 'lib/ai.rb', line 13 def score(board, mark) if @state.winner?(board, mark) || @state.winner?(board, @manager.other_mark(mark)) -10 else 0 end end |
#score_moves(board, mark, depth, scores) ⇒ Object
21 22 23 24 25 26 27 28 29 30 |
# File 'lib/ai.rb', line 21 def score_moves(board, mark, depth, scores) return score(board, mark) if @state.terminal?(board) || (board.size == 16 && depth == 2) @state.empty_indices(board).each do |move| board[move] = mark scores[move] = -1 * score_moves(board, @manager.other_mark(mark), depth + 1, Hash.new) board[move] = "-" end best_score = scores.values.max depth == 0 ? scores : best_score end |
#smart_move(board) ⇒ Object
32 33 34 |
# File 'lib/ai.rb', line 32 def smart_move(board) @choice = score_moves(board, @mark, 0, Hash.new).max_by{ |k, v| v }[0] end |