Sha256: 7ed1d09a7dd3f5ff711f042f60316548c51e066d3a567f1db7bd82a1e2d7f37f

Contents?: true

Size: 1.26 KB

Versions: 1

Compression:

Stored size: 1.26 KB

Contents

module Codebreaker
  class Game
    ATTEMPTS_COUNT = 10
    HINTS_COUNT = 3

    def initialize
      @secret_code = generate_code
      @attempt = 0
      @hint = 0
      @is_winner = false
    end

    def generate_code
      @secret_code = Array.new(4){ rand(6) + 1 }.join
    end

    def guess(input)
      return if input.length != 4
      @attempt += 1
      secret = @secret_code.chars.map(&:to_i)
      result = []
      input.chars.map(&:to_i).each_with_index do |digit, index|
        if digit == secret[index]
          secret[index] = nil
          result << '+'
        elsif secret.include? digit
          secret[secret.find_index(digit)] = nil
          result << '-'
        end
      end
      normalized_output = result.sort.join
      @is_winner = true if normalized_output == '++++'
      normalized_output
    end

    def hint
      return unless HINTS_COUNT > @hint
      @hint += 1
      @secret_code[rand(4)]
    end

    def winner?
      @is_winner
    end

    def ended?
      ATTEMPTS_COUNT == @attempt || @is_winner
    end

    def save
      YAML::Store.new('storage/storage.yml').transaction do |storage|
        storage[Time.now] = "attempts taken: #{@attempt}; hints used: #{@hint}; result: #{(winner? ? 'won' : 'loose')}"
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
codebreaker_z-1.0.0 lib/codebreaker/game.rb