Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- require_relative 'question.rb'
- current_path = File.dirname(__FILE__)
- file_name = current_path + '/questions.xml'
- file = File.new(file_name, 'r:utf-8')
- questions = Questions.read_question_xml(file)
- file.close
- right_answers_counter = 0
- puts "\nВикторина v2.1\n"
- sleep(1)
- questions.each do |question_data|
- question = Questions.new(question_data)
- question.ask_question
- right_answers_counter += question.check_answer
- end
- puts "\nУ Вас #{right_answers_counter} правильных ответов"
- require 'rexml/document'
- class Questions
- def self.read_question_xml(xml_file)
- doc = REXML::Document.new(xml_file)
- questions = []
- doc.elements.each('questions/question') do |questions_element|
- question_data = {time: "#{questions_element.attributes['seconds'].to_f}"}
- variants = []
- questions_element.elements.each do |question_element|
- case question_element.name
- when 'text' then question_data[:text] = question_element.text
- when 'variants'
- question_element.elements.each_with_index do |variant, index|
- variants << variant.text
- question_data[:right_answer_index] = index + 1 if variant.attributes['right']
- end
- question_data[:variants] = variants
- end
- end
- questions << question_data
- end
- return questions
- end
- def initialize(question_data)
- @question_data = question_data
- end
- def ask_question
- @time_for_question = @question_data[:time].to_f
- puts "\nВремя на ответ: #{@time_for_question} сек."
- puts '3'
- sleep(1)
- puts '2'
- sleep(1)
- puts '1'
- sleep(1)
- @start_time = Time.now
- puts @question_data[:text]
- @question_data[:variants].each_with_index do |variant, index|
- puts "#{index+1}. #{variant}"
- end
- take_user_input
- @end_time = Time.now
- end
- def take_user_input
- @user_input = STDIN.gets.chomp
- end
- def check_answer
- if @user_input == @question_data[:right_answer_index].to_s
- if @time_for_question >= @end_time - @start_time
- puts 'Верно!'
- return 1
- else
- puts 'Вы не уложились в отведенное для ответа время.'
- return 0
- end
- else
- puts 'Неправильный ответ!'
- return 0
- end
- end
- end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement