lib/alex_codebreaker/game.rb in alex_codebreaker-0.1.12 vs lib/alex_codebreaker/game.rb in alex_codebreaker-0.1.13
- old
+ new
@@ -1,15 +1,18 @@
module AlexCodebreaker
class Game
include AlexCodebreaker::Modules::ArgumentsValidation
+ FILENAME_EXTENSION = '.yml'.freeze
- attr_reader :secret_code, :session
+ attr_reader :secret_code, :session, :game_id
- def initialize
+ def initialize(outer_id: nil)
+ @game_id = outer_id if outer_id
@secret_code = AlexCodebreaker::SecretCodeGenerator.new.secret_code
@secret_code_for_hint = @secret_code.clone.uniq
@session = Session.new
+ save_game
end
def hint
return unless @session.check_hints
@@ -17,27 +20,44 @@
end
def guess(user_input)
return unless guess_validation(user_input) && @session.check_attempts
+ save_game
compare_codes(user_input)
end
private
def process_hint
- return @secret_code_for_hint.first if @secret_code_for_hint.one?
-
- @secret_code_for_hint.delete(@secret_code_for_hint.sample)
+ hint = if @secret_code_for_hint.one?
+ @secret_code_for_hint.first
+ else
+ @secret_code_for_hint.delete(@secret_code_for_hint.sample)
+ end
+ save_game
+ hint
end
def compare_codes(user_input)
user_input = format_user_input(user_input)
comparison = Comparison.new(user_input, @secret_code.clone)
comparison.response
end
def format_user_input(user_input)
user_input.chars.map(&:to_i)
+ end
+
+ def save_game
+ @game_id ||= AlexCodebreaker::IDGenerator.new.unique_id
+ unless File.directory?(AlexCodebreaker.configuration.games_folder_path)
+ FileUtils.mkdir_p(AlexCodebreaker.configuration.games_folder_path)
+ end
+ File.open(save_game_path, 'w') { |file| file.write(to_yaml) }
+ end
+
+ def save_game_path
+ "#{AlexCodebreaker.configuration.games_folder_path}#{@game_id}#{FILENAME_EXTENSION}"
end
end
end