Class: Ai

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

Instance Method Summary collapse

Constructor Details

#initialize(player, board) ⇒ Ai

Returns a new instance of Ai.



6
7
8
9
10
# File 'lib/ang_ttt_gem/ai.rb', line 6

def initialize(player, board)
  @board = board
  @scoring = Scoring.new
  @max_mark = player.mark
end

Instance Method Details

#evaluate_the_boardObject



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_moveObject



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_markObject



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_moveObject



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_moveObject



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_moveObject



21
22
23
# File 'lib/ang_ttt_gem/ai.rb', line 21

def random_move
  @board.available_spaces.sample
end

#select_optimal_start_moveObject



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

Returns:

  • (Boolean)


74
75
76
# File 'lib/ang_ttt_gem/ai.rb', line 74

def state_is_terminal?
  @scoring.winner?(@board) || @scoring.draw?(@board)
end