Sha256: dc7d923893278557bc57b7ee0d44508129cde4c739d51c3ede6550a77ca74209

Contents?: true

Size: 1.33 KB

Versions: 1

Compression:

Stored size: 1.33 KB

Contents

module Codebreaker
  class Game
    attr_reader :player, :attempts_left

    def initialize(player, difficulty_type)
      @player = player
      @difficulty_type = difficulty_type
      @attempts_left = difficulty.attempts
      @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_left -= 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 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?
      attempts_left.zero?
    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.8 lib/codebreaker/game.rb