Class: TTT::Minimax

Inherits:
Object
  • Object
show all
Defined in:
lib/games/tictactoe/minimax.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(board, number_of_turns_taken, human_value, computer_value) ⇒ Minimax

Returns a new instance of Minimax.



7
8
9
10
11
12
# File 'lib/games/tictactoe/minimax.rb', line 7

def initialize(board, number_of_turns_taken, human_value, computer_value)
  @board = board
  @number_of_turns_taken = number_of_turns_taken
  @human_value = human_value
  @computer_value = computer_value
end

Instance Attribute Details

#boardObject

Returns the value of attribute board.



5
6
7
# File 'lib/games/tictactoe/minimax.rb', line 5

def board
  @board
end

#choiceObject

Returns the value of attribute choice.



5
6
7
# File 'lib/games/tictactoe/minimax.rb', line 5

def choice
  @choice
end

#computer_valueObject

Returns the value of attribute computer_value.



5
6
7
# File 'lib/games/tictactoe/minimax.rb', line 5

def computer_value
  @computer_value
end

#human_valueObject

Returns the value of attribute human_value.



5
6
7
# File 'lib/games/tictactoe/minimax.rb', line 5

def human_value
  @human_value
end

#number_of_turns_takenObject

Returns the value of attribute number_of_turns_taken.



5
6
7
# File 'lib/games/tictactoe/minimax.rb', line 5

def number_of_turns_taken
  @number_of_turns_taken
end

Instance Method Details

#run_minimaxObject



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/games/tictactoe/minimax.rb', line 14

def run_minimax
  scores = []
  choices = []

  board_won = board.won?
  board_full = board.full?

  if board_won || board_full
    #rewind one player to see which player took last turn and therefore won the game
    self.number_of_turns_taken -= 1
    return score(board_won)
  end

  # @logger.debug "avaliable choices collection: #{available_choices}"

  available_choices.each do |available_choice|
    board_copy = Marshal.load(Marshal.dump(board))
    board_copy.change_square(available_choice, player_value)
    choices.push(available_choice)
    minimax = TTT::Minimax.new(board_copy, number_of_turns_taken + 1, human_value, computer_value)
    scores.push minimax.run_minimax
  end

  if computer_current_player?
    #https://stackoverflow.com/questions/2149802/in-ruby-what-is-the-cleanest-way-of-obtaining-the-index-of-the-largest-value-in
    max_score_index = scores.each_with_index.max[1]
    self.choice = choices[max_score_index]
    return scores[max_score_index]
  else
    # This is the min calculation
    min_score_index = scores.each_with_index.min[1]
    self.choice = choices[min_score_index]
    return scores[min_score_index]
  end
end