Sha256: 70eb9f2ed814206a5386f4f736ed49fa02a8e36fa72e940ede1819973dc31964

Contents?: true

Size: 1.8 KB

Versions: 1

Compression:

Stored size: 1.8 KB

Contents

require 'json'
require_relative 'codebreaker_first/version'

module Codebreaker
  MAX_TRIES = 6

  # Rubocop
  class Game
    attr_accessor :code, :user_tries, :game_result

    def initialize(code = '', user_tries = 0, game_result = nil)
      @code = code
      @user_tries = user_tries
      @game_result = game_result
    end

    def from_hash(data)
      Game.new data['code'], data['user_tries'], data['game_result']
    end

    def start
      4.times do
        @code << rand(1...6).to_s
      end
    end

    def check_code(input_code)
      @user_tries += 1
      return loose if @user_tries >= MAX_TRIES
      return win if input_code == @code

      validate_code input_code

      result = ''

      @code.chars.each.with_index do |char, index|
        result << '+' if char == input_code[index]

        result << '-' unless char == input_code[index]
      end

      result
    end

    def win
      @game_result = true
    end

    def loose
      @game_result = false
    end

    def save_result(name)
      raise Exception, 'To save, you must finish the game!' if @game_result.nil?

      Result.save name, @user_tries, @game_result
    end

    def results
      Result.results
    end

    private

    def validate_code(code)
      raise Exception unless code.is_a?(Numeric) || code.is_a?(String)

      code = code.to_s

      raise Exception, 'Code must contains 4 numbers from 1 to 6' unless code =~ /^[1-6]{4}$/
    end
  end

  # Rubocop
  class Result
    SCORES_FILE = File.expand_path('scores.json', __dir__)

    def self.save(name, tries, result)
      scores = results.to_a

      scores << { name: name, tries: tries, result: result }

      File.write SCORES_FILE, scores.to_json

      scores
    end

    def self.results
      file = File.read SCORES_FILE

      JSON.parse file
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
codebreaker_first-0.4.0 lib/codebreaker_first.rb