Sha256: 2277411a2f6cef73ae8089587a939180ab9106dcbf25f0118b14bd1896618818
Contents?: true
Size: 1.67 KB
Versions: 1
Compression:
Stored size: 1.67 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 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_results(name) Result.save name 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) raise Exception, 'To save, you must finish the game!' if @game_result.nil? results = results.to_a results << { name: name, tries: @user_tries, result: @game_result } File.write SCORES_FILE, results.to_json results 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.2.0 | lib/codebreaker_first.rb |