Sha256: 51591023d01c4b80645eb5adc48229e09fad30ae930dbf92ed11a0d8bb4f749b
Contents?: true
Size: 1.7 KB
Versions: 1
Compression:
Stored size: 1.7 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_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.3.0 | lib/codebreaker_first.rb |