Module: TTT::Minimax

Included in:
AI
Defined in:
lib/ttt/minimax.rb

Instance Method Summary collapse

Instance Method Details

#alpha_beta_swapped?(alpha, beta) ⇒ Boolean

Returns:

  • (Boolean)


30
31
32
# File 'lib/ttt/minimax.rb', line 30

def alpha_beta_swapped?(alpha, beta)
  alpha >= beta
end

#base_case_satisfied?Boolean

Returns:

  • (Boolean)


34
35
36
# File 'lib/ttt/minimax.rb', line 34

def base_case_satisfied?
  board.winner? || board.draw_game?
end

#eval_score(max_player, index, score, alpha, beta, ab_value, best_move) ⇒ Object



24
25
26
27
28
# File 'lib/ttt/minimax.rb', line 24

def eval_score(max_player, index, score, alpha, beta, ab_value, best_move)
  best_move, alpha, ab_value = [index, score, score] if max_player && score > ab_value
  beta, ab_value             = [score, score]        if !max_player && score < ab_value
  [alpha, beta, ab_value, best_move]
end

#gen_score_game_tree(max_player, ply, alpha, beta, ab_value) ⇒ Object



12
13
14
15
16
17
18
19
20
21
22
# File 'lib/ttt/minimax.rb', line 12

def gen_score_game_tree(max_player, ply, alpha, beta, ab_value)
  best_move = 0
  available_moves.each do |index|
    board[][index]                   = mark_curr_player_side(max_player)
    score                            = minimax(!max_player, ply + 1, alpha, beta)
    alpha, beta, ab_value, best_move = eval_score(max_player, index, score, alpha, beta, ab_value, best_move)
    undo_move(index)
    break if alpha_beta_swapped?(alpha, beta)
  end
  [ab_value, best_move]
end

#mark_curr_player_side(max_player) ⇒ Object



42
43
44
# File 'lib/ttt/minimax.rb', line 42

def mark_curr_player_side(max_player)
  max_player ? side : opposite_side(side)
end

#minimax(max_player = true, ply = 0, alpha = -1000,, beta = 1000) ⇒ Object



3
4
5
6
7
8
9
10
# File 'lib/ttt/minimax.rb', line 3

def minimax(max_player = true, ply = 0, alpha = -1000, beta = 1000)
  return(board.winner? ? winning_score(max_player, ply) : 0) if base_case_satisfied?
  ab_value            = max_player ? alpha : beta
  return ab_value if ply >= max_ply

  ab_value, best_move = gen_score_game_tree(max_player, ply, alpha, beta, ab_value)
  return(ply == 0 ? best_move : ab_value)
end

#winning_score(max_player, ply) ⇒ Object



38
39
40
# File 'lib/ttt/minimax.rb', line 38

def winning_score(max_player, ply)
  max_player ? (-1000 + ply) : (1000 - ply)
end