Sha256: e480eb821dc3396d916dad96125c9dc4829eaa326de509e9ff32cc1ee9155793

Contents?: true

Size: 1.38 KB

Versions: 1

Compression:

Stored size: 1.38 KB

Contents

module Codebreaker
  class Game
    attr_reader :player

    def initialize(player, difficulty_type)
      @player = player
      @difficulty_type = difficulty_type
      @attempts_used = 0
      @is_win = false
    end

    def secret_code
      @secret_code ||= SecretCodeGenerator.new.call
    end

    def difficulty
      @difficulty ||= DifficultyFactory.build(@difficulty_type)
    end

    def take_hint
      ensure_game_is_not_over
      raise Errors::NoHintsError if hints.empty?

      hints.pop
    end

    def guess_secret_code(guess)
      ensure_game_is_not_over
      @attempts_used += 1
      matching = SecretCodeMatcher.new(secret_code, guess).call
      check_win(guess)
      matching
    end

    def lose?
      no_attempts? && !win?
    end

    def win?
      @is_win
    end

    def over?
      win? || lose?
    end

    def hints_left
      hints.count
    end

    def attempts_left
      difficulty.attempts - @attempts_used
    end

    def save_result
      raise Errors::GameSaveError unless win?

      CreateStatService.new(self).call
    end

    private

    def hints
      @hints ||= secret_code.sample(difficulty.hints)
    end

    def no_attempts?
      difficulty.attempts == @attempts_used
    end

    def ensure_game_is_not_over
      raise Errors::GameOverError if over?
    end

    def check_win(guess)
      @is_win = true if guess == secret_code
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
cb-core-0.1.7 lib/codebreaker/game.rb