Class: TTT::MoveGenerator

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(game) ⇒ MoveGenerator

Returns a new instance of MoveGenerator.



6
7
8
# File 'lib/tictactoe/move_generator.rb', line 6

def initialize(game)
  @game = game
end

Instance Attribute Details

#choiceObject

Returns the value of attribute choice.



4
5
6
# File 'lib/tictactoe/move_generator.rb', line 4

def choice
  @choice
end

#gameObject

Returns the value of attribute game.



4
5
6
# File 'lib/tictactoe/move_generator.rb', line 4

def game
  @game
end

Instance Method Details

#minimaxObject



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
# File 'lib/tictactoe/move_generator.rb', line 15

def minimax
  scores = []
  choices = []
  if game.over?
    return score(game)
  end

  available_choices.each do |available_choice|
    new_game_state = Marshal.load(Marshal.dump(game))
    new_game_state.change_square(available_choice, game.current_player.value)
    #below needed because pry indicates possible_game_state's board not updating after make_move above
    # possible_game_state.game_board = possible_board_state
    choices.push(available_choice)
    new_move_generator = MoveGenerator.new(new_game_state)
    scores.push new_move_generator.minimax
  end

  if game.current_player == computer_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]
    @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]
    @choice = choices[min_score_index]
    return scores[min_score_index]
  end

end

#random_moveObject

returns int representing display value of random available square



11
12
13
# File 'lib/tictactoe/move_generator.rb', line 11

def random_move
  available_choices.sample
end