Sha256: ea0d86812223bdfaeb85e92ad94dc589dbbd50ca7575d970b859f7c6310ad03e

Contents?: true

Size: 1.98 KB

Versions: 1

Compression:

Stored size: 1.98 KB

Contents

# frozen_string_literal: true

module Codebreaker
  # Game of bulls and cows.
  class Game
    attr_reader :storage, :matcher, :hints, :status

    attr_accessor :user, :number_of_attempts, :number_of_hints, :attempts_left, :hints_left, :difficulty, :secret_code
    def initialize(matcher: Matcher.new)
      @storage = storage
      @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(4) { roll_dice }.join
    end

    def roll_dice
      rand(1..6)
    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.5 lib/codebreaker_mats/game.rb