class Tictactoe::Ai::ABNegamax

Constants

COLOR_OPPONENT
COLOR_SELF

Attributes

depth_limit[R]
depth_reached_score[R]

Public Class Methods

new(depth_limit, depth_reached_score) click to toggle source
# File lib/tictactoe/ai/ab_negamax.rb, line 7
def initialize(depth_limit, depth_reached_score)
  @depth_limit = depth_limit
  @depth_reached_score = depth_reached_score
end

Public Instance Methods

best_nodes(tree) click to toggle source
# File lib/tictactoe/ai/ab_negamax.rb, line 18
def best_nodes(tree)
  negamax(tree)[:nodes]
end
score(tree) click to toggle source
# File lib/tictactoe/ai/ab_negamax.rb, line 14
def score(tree)
  negamax(tree)[:score]
end

Private Instance Methods

negamax(node, depth = depth_limit, a = -1000, b = 1000, color = COLOR_SELF) click to toggle source
# File lib/tictactoe/ai/ab_negamax.rb, line 23
def negamax(node, depth = depth_limit, a = -1000, b = 1000, color = COLOR_SELF)
  return {:score => color * node.score, :nodes => []} if node.is_final?
  return {:score => color * depth_reached_score, :nodes => node.children} if depth == 0

  best_score = -1000
  best_nodes = []
  node.children.each do |child|
    score = -negamax(child, depth-1, -b, -a, -color)[:score]
    if score > best_score
      best_score = score
      best_nodes = [child]
    elsif score == best_score
      best_nodes << child
    end
    a = [a, score].max
    break if a > b
  end

  {:score => best_score, :nodes => best_nodes}
end