Sha256: d31924d4b39ae96a31eda3c8b3c2cb14dca12e678a27e7a95c83c152660c49dc

Contents?: true

Size: 1.89 KB

Versions: 2

Compression:

Stored size: 1.89 KB

Contents

# frozen_string_literal: true

module Codebreaker
  class Game
    attr_reader :tries_left

    def start
      @code = Array.new(LENGTH) { rand(MIN..MAX) }.join
      @hint = @code.chars.sample
      @tries_left = TRIES
      @finished = false
      @won = false
    end

    def check_guess(input)
      verify input

      @tries_left -= 1

      result = check_input(@code.chars, input.chars)
      define_stage result
      result
    end

    def use_hint
      @hint
    end

    def finished?
      @finished
    end

    def won?
      @won
    end

    def tries
      TRIES - @tries_left
    end

    def answer
      @code if finished?
    end

    def save_score(name, file_name = 'scores.yml')
      player = Player.new(name, tries)

      scores = process_file(file_name)
      scores << player
      scores = scores.min_by(10, &:tries)

      File.open(file_name, 'w') { |f| f.write scores.to_yaml }
    end

    def high_scores(file_name = 'scores.yml')
      process_file file_name
    end

    private

    def check_input(code_chars, input_chars)
      num_of_pluses = LENGTH.times.count { |i| code_chars[i] == input_chars[i] }

      input_chars.each do |char|
        next unless code_chars.include? char
        code_chars.delete_at(code_chars.index(char))
      end

      num_of_minuses = LENGTH - num_of_pluses - code_chars.size

      ('+' * num_of_pluses) + ('-' * num_of_minuses)
    end

    def define_stage(result)
      if result == ('+' * LENGTH)
        @finished = true
        @won = true
      elsif @tries_left.zero?
        @finished = true
      end
    end

    def process_file(file_name)
      return [] if !File.exist?(file_name) || File.zero?(file_name)
      YAML.load_file(file_name)
    end

    def verify(input)
      msg = "Guesses must consist of #{LENGTH} digits from #{MIN} to #{MAX}"
      raise(ArgumentError, msg) if !input.is_a?(String) || !input.match?(REGEXP)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
ep-codebreaker-0.1.2 lib/ep-codebreaker/game.rb
ep-codebreaker-0.1.1 lib/ep-codebreaker/game.rb