class Codebreaker::Game

Constants

CODE_SIZE
GUESS_PLACE
GUESS_PRESENCE
INCLUDE_IN_GAME_NUMBERS

Attributes

attempts[R]
breaker_numbers[R]
difficulty[R]
hints[R]
player_name[R]
showed_hints[R]

Public Class Methods

new(difficulty, user) click to toggle source
# File lib/app/entities/game.rb, line 13
def initialize(difficulty, user)
  @breaker_numbers = generate_random_code
  @breaker_numbers_copy = @breaker_numbers.clone.shuffle
  @hints = difficulty.level[:hints]
  @attempts = difficulty.level[:attempts]
  @difficulty = difficulty.level
  @player_name = user.name
  @showed_hints = []
end

Public Instance Methods

hint() click to toggle source
# File lib/app/entities/game.rb, line 29
def hint
  return if @hints.zero?

  @hints -= 1
  @showed_hints << @breaker_numbers_copy.pop
  @showed_hints.last
end
lose?(result) click to toggle source
# File lib/app/entities/game.rb, line 41
def lose?(result)
  @attempts == 1 && @breaker_numbers != result
end
start_round(user_input) click to toggle source
# File lib/app/entities/game.rb, line 23
def start_round(user_input)
  @attempts -= 1
  @game_numbers = { code: @breaker_numbers.clone, input: user_input }
  collect_place_guess + collect_presence_guess
end
to_h() click to toggle source
# File lib/app/entities/game.rb, line 45
def to_h
  {
    player_name: @player_name,
    level: @difficulty[:level],
    all_hints: @difficulty[:hints],
    all_attempts: @difficulty[:attempts],
    left_hints: @hints,
    left_attempts: @attempts,
    date: Time.now
  }
end
win?(result) click to toggle source
# File lib/app/entities/game.rb, line 37
def win?(result)
  @breaker_numbers == result
end

Private Instance Methods

collect_place_guess() click to toggle source
# File lib/app/entities/game.rb, line 59
def collect_place_guess
  @game_numbers[:input].map.with_index do |user_num, index|
    next if @game_numbers[:code][index] != user_num

    @game_numbers[:code][index] = nil
    @game_numbers[:input][index] = nil
    GUESS_PLACE
  end.compact
end
collect_presence_guess() click to toggle source
# File lib/app/entities/game.rb, line 69
def collect_presence_guess
  @game_numbers[:input].compact.map do |user_num|
    next unless @game_numbers[:code].include?(user_num)

    @game_numbers[:code].delete_at(@game_numbers[:code].index(user_num))
    GUESS_PRESENCE
  end.compact
end
generate_random_code() click to toggle source
# File lib/app/entities/game.rb, line 78
def generate_random_code
  Array.new(CODE_SIZE) { rand(INCLUDE_IN_GAME_NUMBERS) }
end