Sha256: 7ccb55b8737bfcb4c4938ed33045db4eeb467b4b751d45db4016a75da1d5adf4

Contents?: true

Size: 1.37 KB

Versions: 1

Compression:

Stored size: 1.37 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 attempts_left
      ATTEMPTS_COUNT - @attempt
    end

    def hints_left
      HINTS_COUNT - @hint
    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.1.0 lib/codebreaker/game.rb