Sha256: d784027894e44704da86ac1cf0c7ec2ebf1913d54d7c2928d9b6b7c59585a463
Contents?: true
Size: 1.42 KB
Versions: 1
Compression:
Stored size: 1.42 KB
Contents
module Codebreaker class Game ATTEMPTS_COUNT = 10 HINTS_COUNT = 3 attr_reader :attempt, :hint, :is_winner 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.2.0 | lib/codebreaker/game.rb |