Sha256: d2725c842a1e13c4a8e4cb966bd186c150faafddf84485354e39ff2ef407a21f

Contents?: true

Size: 2 KB

Versions: 1

Compression:

Stored size: 2 KB

Contents

module Codebreaker
  class Game
    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 in_progress?
      status == :in_progress
    end

    def save_stat(stat_file)
      File.open(stat_file, 'a+') do |f|
        f.write({ 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 }.to_yaml)
      end
    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

1 entries across 1 versions & 1 rubygems

Version Path
codebreaker_mats-0.1.6 lib/codebreaker_mats/game.rb