Class: Ai
- Inherits:
-
Object
- Object
- Ai
- Defined in:
- lib/ang_ttt_gem/ai.rb
Instance Method Summary collapse
- #evaluate_the_board ⇒ Object
- #find_best_move ⇒ Object
- #find_opponent_mark ⇒ Object
-
#initialize(player, board) ⇒ Ai
constructor
A new instance of Ai.
- #max_move ⇒ Object
- #min_move ⇒ Object
- #random_move ⇒ Object
- #select_optimal_start_move ⇒ Object
- #state_is_terminal? ⇒ Boolean
Constructor Details
Instance Method Details
#evaluate_the_board ⇒ Object
78 79 80 81 82 83 84 |
# File 'lib/ang_ttt_gem/ai.rb', line 78 def evaluate_the_board decision = nil decision = 1 if @scoring.winner?(@board) && @scoring.winning_mark(@board) == @max_mark decision = -1 if @scoring.winner?(@board) && @scoring.winning_mark(@board) != @max_mark decision = 0 if @scoring.draw?(@board) decision end |
#find_best_move ⇒ Object
25 26 27 28 29 30 31 32 33 34 |
# File 'lib/ang_ttt_gem/ai.rb', line 25 def find_best_move if @board.available_spaces.count == 9 best_move = select_optimal_start_move else find_opponent_mark move_reference, best_score = max_move best_move = move_reference end best_move end |
#find_opponent_mark ⇒ Object
12 13 14 15 |
# File 'lib/ang_ttt_gem/ai.rb', line 12 def find_opponent_mark state = @board.current_state @min_mark = state.reject {|c| c =~ /^#{@max_mark}|\s{1}$/ }.first end |
#max_move ⇒ Object
36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
# File 'lib/ang_ttt_gem/ai.rb', line 36 def max_move best_move = nil best_score = nil @board.available_spaces.each do |move| @board.set(move, @max_mark) if state_is_terminal? score = evaluate_the_board else move_reference, score = min_move end @board.undo_move(move) if best_score.nil? || score > best_score best_score = score best_move = move end end return best_move, best_score end |
#min_move ⇒ Object
55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/ang_ttt_gem/ai.rb', line 55 def min_move best_move = nil best_score = nil @board.available_spaces.each do |move| @board.set(move, @min_mark) if state_is_terminal? score = evaluate_the_board else move_reference, score = max_move end @board.undo_move(move) if best_score.nil? || score < best_score best_score = score best_move = move end end return best_move, best_score end |
#random_move ⇒ Object
21 22 23 |
# File 'lib/ang_ttt_gem/ai.rb', line 21 def random_move @board.available_spaces.sample end |
#select_optimal_start_move ⇒ Object
17 18 19 |
# File 'lib/ang_ttt_gem/ai.rb', line 17 def select_optimal_start_move [0, 2, 4, 6, 8].sample end |
#state_is_terminal? ⇒ Boolean
74 75 76 |
# File 'lib/ang_ttt_gem/ai.rb', line 74 def state_is_terminal? @scoring.winner?(@board) || @scoring.draw?(@board) end |