Advertisement
Guest User

Untitled

a guest
May 26th, 2016
64
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.48 KB | None | 0 0
  1.  
  2. require_relative 'question.rb'
  3.  
  4.  
  5. current_path = File.dirname(__FILE__)
  6. file_name = current_path + '/questions.xml'
  7.  
  8. file = File.new(file_name, 'r:utf-8')
  9. questions = Questions.read_question_xml(file)
  10. file.close
  11.  
  12. right_answers_counter = 0
  13.  
  14. puts "\nВикторина v2.1\n"
  15. sleep(1)
  16.  
  17. questions.each do |question_data|
  18. question = Questions.new(question_data)
  19. question.ask_question
  20. right_answers_counter += question.check_answer
  21. end
  22.  
  23. puts "\nУ Вас #{right_answers_counter} правильных ответов"
  24.  
  25.  
  26. require 'rexml/document'
  27.  
  28. class Questions
  29.  
  30. def self.read_question_xml(xml_file)
  31. doc = REXML::Document.new(xml_file)
  32.  
  33. questions = []
  34.  
  35. doc.elements.each('questions/question') do |questions_element|
  36.  
  37. question_data = {time: "#{questions_element.attributes['seconds'].to_f}"}
  38.  
  39. variants = []
  40.  
  41. questions_element.elements.each do |question_element|
  42. case question_element.name
  43. when 'text' then question_data[:text] = question_element.text
  44. when 'variants'
  45. question_element.elements.each_with_index do |variant, index|
  46. variants << variant.text
  47. question_data[:right_answer_index] = index + 1 if variant.attributes['right']
  48. end
  49. question_data[:variants] = variants
  50. end
  51. end
  52.  
  53. questions << question_data
  54.  
  55. end
  56. return questions
  57. end
  58.  
  59.  
  60. def initialize(question_data)
  61. @question_data = question_data
  62. end
  63.  
  64.  
  65. def ask_question
  66. @time_for_question = @question_data[:time].to_f
  67.  
  68. puts "\nВремя на ответ: #{@time_for_question} сек."
  69. puts '3'
  70. sleep(1)
  71. puts '2'
  72. sleep(1)
  73. puts '1'
  74. sleep(1)
  75.  
  76. @start_time = Time.now
  77.  
  78. puts @question_data[:text]
  79.  
  80. @question_data[:variants].each_with_index do |variant, index|
  81. puts "#{index+1}. #{variant}"
  82. end
  83.  
  84. take_user_input
  85.  
  86. @end_time = Time.now
  87. end
  88.  
  89.  
  90. def take_user_input
  91. @user_input = STDIN.gets.chomp
  92. end
  93.  
  94.  
  95. def check_answer
  96. if @user_input == @question_data[:right_answer_index].to_s
  97. if @time_for_question >= @end_time - @start_time
  98. puts 'Верно!'
  99. return 1
  100. else
  101. puts 'Вы не уложились в отведенное для ответа время.'
  102. return 0
  103. end
  104. else
  105. puts 'Неправильный ответ!'
  106. return 0
  107. end
  108. end
  109.  
  110. end
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement