Class: Mastermind::Game::Code

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

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sequence:) ⇒ Code

Returns a new instance of Code.

Raises:

  • (ArgumentError)


15
16
17
18
# File 'lib/mastermind/game/code.rb', line 15

def initialize(sequence:)
  raise ArgumentError unless sequence.all? { |piece| piece.is_a? Piece }
  @sequence = sequence
end

Instance Attribute Details

#sequenceObject (readonly)

Returns the value of attribute sequence.



4
5
6
# File 'lib/mastermind/game/code.rb', line 4

def sequence
  @sequence
end

Class Method Details

.from(colors) ⇒ Object



11
12
13
# File 'lib/mastermind/game/code.rb', line 11

def self.from(colors)
  new(sequence: colors.map { |color| Piece.new(color: color) })
end

.random(number_of_pieces = 4) ⇒ Object



6
7
8
9
# File 'lib/mastermind/game/code.rb', line 6

def self.random(number_of_pieces = 4)
  sequence = Array.new(number_of_pieces) { Piece.new }
  new(sequence: sequence)
end

Instance Method Details

#==(code) ⇒ Object



55
56
57
58
59
# File 'lib/mastermind/game/code.rb', line 55

def ==(code)
  code.is_a?(Code) &&
  length == code.length &&
  exact_matches_with(code) == length
end

#color_countsObject



24
25
26
27
28
29
# File 'lib/mastermind/game/code.rb', line 24

def color_counts
  sequence.each_with_object({}) do |piece, counts|
    counts[piece.color] ||= 0
    counts[piece.color] += 1
  end
end

#color_matches_with(code) ⇒ Object

Raises:

  • (ArgumentError)


40
41
42
43
44
45
46
47
48
# File 'lib/mastermind/game/code.rb', line 40

def color_matches_with(code)
  raise ArgumentError unless code.is_a? Code
  other_colors = code.color_counts
  sum = 0
  color_counts.each do |color, quantity|
    sum += [quantity, other_colors[color] || 0].min
  end
  sum
end

#exact_matches_with(code) ⇒ Object

Raises:

  • (ArgumentError)


31
32
33
34
35
36
37
38
# File 'lib/mastermind/game/code.rb', line 31

def exact_matches_with(code)
  raise ArgumentError unless code.is_a? Code
  sum = 0
  sequence.each_with_index do |piece, idx|
    sum += 1 if piece == code.sequence[idx]
  end
  sum
end

#lengthObject



20
21
22
# File 'lib/mastermind/game/code.rb', line 20

def length
  @sequence.length
end

#partial_matches_with(code) ⇒ Object

Raises:

  • (ArgumentError)


50
51
52
53
# File 'lib/mastermind/game/code.rb', line 50

def partial_matches_with(code)
  raise ArgumentError unless code.is_a? Code
  color_matches_with(code) - exact_matches_with(code)
end