Class: Codebreaker::Game

Inherits:
Object
  • Object
show all
Includes:
Message
Defined in:
lib/codebreaker/game.rb

Constant Summary collapse

ZERO_POINTS =
0
TEN_POINTS =
10
TWENTY_POINTS =
20
FIFTY_POINTS =
50
ONE_HUNDRED_POINTS =
100
BONUS_POINTS =
500
RIGHT_ANSWER =
'+'.freeze
RIGHT_ANSWER_DIFF_INDEX =
'-'.freeze
WRONG_ANSWER =
' '.freeze

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(*config) {|@configuration| ... } ⇒ Game

Returns a new instance of Game.

Yields:



19
20
21
22
23
24
25
# File 'lib/codebreaker/game.rb', line 19

def initialize(*config)
  @locale = Localization.new(:game)
  @configuration ||= GameConfiguration.new(*config)
  yield @configuration if block_given?
  apply_configuration
  generate_secret_code
end

Instance Attribute Details

#attemptsObject (readonly)

Returns the value of attribute attempts.



17
18
19
# File 'lib/codebreaker/game.rb', line 17

def attempts
  @attempts
end

#configurationObject (readonly)

Returns the value of attribute configuration.



17
18
19
# File 'lib/codebreaker/game.rb', line 17

def configuration
  @configuration
end

#hintsObject (readonly)

Returns the value of attribute hints.



17
18
19
# File 'lib/codebreaker/game.rb', line 17

def hints
  @hints
end

Instance Method Details

#guess_valid?(input) ⇒ Boolean

Returns:

  • (Boolean)


27
28
29
30
31
# File 'lib/codebreaker/game.rb', line 27

def guess_valid?(input)
  raise message['errors']['invalid_input'] unless input.is_a?(String)
  raise message['alerts']['invalid_input'] unless input[/\A[1-6]{4}\z/]
  true
end

#hintObject



43
44
45
46
47
48
49
50
51
# File 'lib/codebreaker/game.rb', line 43

def hint
  raise message['alerts']['no_hints'] if hints.zero?
  @hints -= 1
  return secret_code.sample if result.empty?
  not_guessed = result.chars.map.with_index do |item, index|
    secret_code[index] unless item == RIGHT_ANSWER
  end
  not_guessed.compact.sample
end

#scoreObject



53
54
55
# File 'lib/codebreaker/game.rb', line 53

def score
  calculate_score
end

#to_guess(input) ⇒ Object



33
34
35
36
37
# File 'lib/codebreaker/game.rb', line 33

def to_guess(input)
  raise message['alerts']['no_attempts'] if attempts.zero?
  @attempts -= 1
  @result = fancy_algo(input, secret_code)
end

#won?Boolean

Returns:

  • (Boolean)


39
40
41
# File 'lib/codebreaker/game.rb', line 39

def won?
  result == RIGHT_ANSWER * 4
end