Class: TakaTicTacToe::MediumAi

Inherits:
Computer
  • Object
show all
Defined in:
lib/taka_tic_tac_toe/ai_difficulty/medium_ai.rb

Constant Summary collapse

Negative_Infinity =
-1.0/0

Instance Attribute Summary

Attributes inherited from Computer

#difficulty, #mark, #opponent_mark

Instance Method Summary collapse

Methods inherited from Computer

#initialize

Constructor Details

This class inherits a constructor from TakaTicTacToe::Computer

Instance Method Details

#check_game_state(board, mark) ⇒ Object



38
39
40
41
42
# File 'lib/taka_tic_tac_toe/ai_difficulty/medium_ai.rb', line 38

def check_game_state(board, mark)
  return 0 if board.is_tie
  return 1 if board.winner == mark
  -1
end

#make_move(board) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# File 'lib/taka_tic_tac_toe/ai_difficulty/medium_ai.rb', line 5

def make_move(board)
  #possible_moves = {}
  best_score = Negative_Infinity
  best_index = 0
  board.empty_slots.each do |slots|
    board.set_move(@mark, slots)
    score = -negamax_score(board, -1, 0)
    #possible_moves[slots] = -negamax_score(board, -1)
    board.undo_move(slots)
      if score > best_score
        best_score = score
        best_index = slots
      end
  end
  #puts possible_moves
  return best_index
end

#negamax_score(board, color, depth) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/taka_tic_tac_toe/ai_difficulty/medium_ai.rb', line 23

def negamax_score(board, color, depth)
  score = Negative_Infinity

  mark = color == 1 ? @mark : @opponent_mark

  return check_game_state(board, (mark)) if board.has_winner || board.is_tie || depth == 4

  board.empty_slots.each do |slots|
    board.set_move(mark, slots)
    score = [score, -negamax_score(board, -color, depth += 1)].max
    board.undo_move(slots)
  end
  return score
end