Class: CodebreakerDiz::Game

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(difficulty: :kid) ⇒ Game

Returns a new instance of Game.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/codebreaker_diz/game.rb', line 9

def initialize(difficulty: :kid)
  validate_difficulty(difficulty)

  @difficulty   = difficulty

  @hint_indexes = (0...CODE_LENGTH).to_a

  @secret       = Array.new(CODE_LENGTH) { rand(MIN_CODE_NUMBER..MAX_CODE_NUMBER) }

  @tries_count  = DIFFICULTIES[@difficulty][:tries]
  @hints_count  = DIFFICULTIES[@difficulty][:hints]

  @matches      = ''
end

Instance Attribute Details

#hints_countObject (readonly)

Returns the value of attribute hints_count.



7
8
9
# File 'lib/codebreaker_diz/game.rb', line 7

def hints_count
  @hints_count
end

#tries_countObject (readonly)

Returns the value of attribute tries_count.



7
8
9
# File 'lib/codebreaker_diz/game.rb', line 7

def tries_count
  @tries_count
end

Instance Method Details

#check_guess(input) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/codebreaker_diz/game.rb', line 28

def check_guess(input)
  input = to_array(input)

  return I18n.t(:WRONG_FORMAT) unless valid? input

  @tries_count -= 1

  @matches = Matcher.new(@secret, input).matches
end

#dataObject



60
61
62
63
64
65
66
67
68
69
# File 'lib/codebreaker_diz/game.rb', line 60

def data
  {
    difficulty: DIFFICULTIES.keys.index(@difficulty),
    secret: @secret,
    tries_total: DIFFICULTIES[@difficulty][:tries],
    hints_total: DIFFICULTIES[@difficulty][:hints],
    tries_used: DIFFICULTIES[@difficulty][:tries] - @tries_count,
    hints_used: DIFFICULTIES[@difficulty][:hints] - @hints_count
  }
end

#generate_hintObject



38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/codebreaker_diz/game.rb', line 38

def generate_hint
  return I18n.t(:NO_HINTS_LEFT) if @hints_count.zero?

  index = @hint_indexes.sample

  hint = @secret[index]

  @hint_indexes.delete index

  @hints_count -= 1

  hint
end

#lose?Boolean

Returns:

  • (Boolean)


56
57
58
# File 'lib/codebreaker_diz/game.rb', line 56

def lose?
  @tries_count.zero?
end

#validate_difficulty(difficulty) ⇒ Object

Raises:

  • (ArgumentError)


24
25
26
# File 'lib/codebreaker_diz/game.rb', line 24

def validate_difficulty(difficulty)
  raise ArgumentError, I18n.t(:INVALID_DIFFICULTY) unless DIFFICULTIES.include? difficulty.to_sym
end

#win?Boolean

Returns:

  • (Boolean)


52
53
54
# File 'lib/codebreaker_diz/game.rb', line 52

def win?
  @matches == Array.new(CODE_LENGTH, EXACT_MATCH_SIGN).join
end