Sha256: 2c8dc7b14f1a8df1195bf55d09267bf2971f1c5200fb36c4f4475933f108b98f

Contents?: true

Size: 1.92 KB

Versions: 2

Compression:

Stored size: 1.92 KB

Contents

module Codebreaker
  class Game
    include Stats
    CODE_RANGE_MIN = 1
    CODE_RANGE_MAX = 6
    COUNT_OF_NUMBER = 4
    attr_reader :matcher, :hints, :status

    attr_accessor :user, :number_of_attempts, :number_of_hints, :attempts_left, :hints_left, :difficulty, :secret_code
    def initialize(matcher: Matcher.new)
      @matcher = matcher
    end

    def start
      generate_secret_code
      generate_hints
      @attempts_left = @number_of_attempts = 0
      @hints_left = @number_of_hints = 0
      matcher.secret_code = @secret_code
      @status = :in_progress
      @difficulty
    end

    def attempts_available?
      return false if won? || lost?

      attempts_left.positive? || lost
    end

    def guess(guess)
      @attempts_left -= 1
      matcher.match?(guess) && won
    end

    def marks
      matcher.marks
    end

    def hint!
      if hints_left.positive?
        @hints_left -= 1
        hints.shift
      end
    end

    def won?
      status == :won
    end

    def lost?
      status == :lost
    end

    def save_stat(stat_file)
      save_stat_in_file(stat_file, stats_hash)
    end

    def stats_hash
      { user: @user,
        difficulty: @difficulty,
        attempts: @number_of_attempts,
        attempts_used: @number_of_attempts - @attempts_left,
        hints: @number_of_hints,
        hints_used: @number_of_hints - @hints_left }
    end

    def set_difficulty(diff, attempts, hints)
      @number_of_attempts = @attempts_left = attempts
      @number_of_hints = @hints_left = hints
      @difficulty = diff
    end

    private

    def generate_secret_code
      @secret_code = Array.new(COUNT_OF_NUMBER) { roll_dice }.join
    end

    def roll_dice
      rand(CODE_RANGE_MIN..CODE_RANGE_MAX)
    end

    def generate_hints
      @hints = @secret_code.split('').shuffle
    end

    def won
      @status = :won
      true
    end

    def lost
      @status = :lost
      false
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
codebreaker_mats-0.1.8 lib/codebreaker_mats/game.rb
codebreaker_mats-0.1.7 lib/codebreaker_mats/game.rb