Class: Mastermind::Knuth

Inherits:
Object
  • Object
show all
Defined in:
lib/mastermind/knuth.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(game) ⇒ Knuth

Returns a new instance of Knuth.



5
6
7
8
9
10
11
12
13
# File 'lib/mastermind/knuth.rb', line 5

def initialize(game)
  @game = game
  # 1. Create the set S of 1296 possible codes
  @possible_guesses = Game::Piece::COLORS.repeated_permutation(game.secret_length).to_a.map do |permutation|
    Game::Code.from(permutation)
  end
  @set = @possible_guesses.dup
  @game.turns.each { |turn| prune(turn) }
end

Instance Attribute Details

#gameObject (readonly)

Returns the value of attribute game.



3
4
5
# File 'lib/mastermind/knuth.rb', line 3

def game
  @game
end

Instance Method Details

#exploratory_guessObject

  1. Choose from the set of guesses with the maximum score, preferring members of S



33
34
35
36
# File 'lib/mastermind/knuth.rb', line 33

def exploratory_guess
  max_scoring = maximum_scoring_guesses
  (max_scoring & @set).sample || max_scoring.sample
end

#first_guessObject

  1. Make initial guess of 1122



23
24
25
26
27
28
29
30
# File 'lib/mastermind/knuth.rb', line 23

def first_guess
  first_color = Game::Piece::COLORS.sample
  second_color = Game::Piece::COLORS.reject { |color| color == first_color }.sample
  sequence = Array.new(@game.secret_length) do |position|
    position < @game.secret_length / 2 ? first_color : second_color
  end
  Game::Code.from(sequence)
end

#prepare_guessObject



15
16
17
18
19
20
# File 'lib/mastermind/knuth.rb', line 15

def prepare_guess
  return first_guess if @game.attempts == 0
  prune(@game.turns.last)
  return @set.first if @set.length == 1
  exploratory_guess
end