Class: Unbeatable_AI

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeUnbeatable_AI

Returns a new instance of Unbeatable_AI.



7
8
9
# File 'lib/unbeatable_ai.rb', line 7

def initialize
  @opponent = false
end

Instance Attribute Details

#opponentObject

Returns the value of attribute opponent.



5
6
7
# File 'lib/unbeatable_ai.rb', line 5

def opponent
  @opponent
end

Instance Method Details

#make_move(board, marker) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/unbeatable_ai.rb', line 39

def make_move(board, marker)
  best_square = nil
  best_score = -1.0/0
  opponent = board.get_opponent
  board.list_of_open_squares.each do |square|
    board.set_square(square, marker)
    score = -minimax(board, opponent, 1, -1.0/0, 1.0/0)
    board.undo_set_square(square)
    if score > best_score
      best_score = score
      best_square = square
    end 
  end
  return best_square
end

#minimax(board, marker, depth, alpha, beta) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/unbeatable_ai.rb', line 21

def minimax(board, marker, depth, alpha, beta)
  opponent = board.get_opponent
  score = 0
  best_score = -1.0/0
  if board.game_over?
    return score_board(board, marker) / depth
  else
    new_alpha = alpha
    board.list_of_open_squares.each do |square|
      board.set_square(square, marker)
      score = -minimax(board, opponent, depth + 1, -new_alpha, -beta)
      board.undo_set_square(square)
      best_score = score if score > best_score
    end
    return best_score 
  end
end

#score_board(board, marker) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/unbeatable_ai.rb', line 11

def score_board(board, marker)
  if !board.board_open? and !board.winner_on_board?
    return 0 
  elsif board.game_won?(marker)
    1.0
  else
    -1.0
  end
end