Created
June 30, 2012 05:59
-
-
Save JDLeigh10/3022542 to your computer and use it in GitHub Desktop.
Ruby Trivia Game
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Load the text file, create an array consisting of each line | |
txt_data = File.open('questions.txt') | |
txt_data_array = txt_data.readlines | |
txt_data_array << "FINISHED" | |
# Initialize variables | |
questions_array = [] | |
z = [] | |
c = 0 | |
w = 0 | |
valid_input = ["A", "B", "C", "D"] | |
# Every six lines is put into the temporary array z, and then z is appended onto questions_array | |
txt_data_array.length.times do |x| | |
if x % 6 == 0 && x != 0 | |
questions_array << z | |
z = [] | |
end | |
z << txt_data_array[x] | |
end | |
# Starts the loop | |
# Puts the Question Number, Question and Choices | |
txt_data_array.length.times do |x| | |
puts "Question #{x+1}" | |
puts "+ ----------" | |
puts questions_array[x][1] | |
puts "A. #{questions_array[x][2]}" | |
puts "B. #{questions_array[x][3]}" | |
puts "C. #{questions_array[x][4]}" | |
puts "D. #{questions_array[x][5]} \n" | |
# Prompts the user for an answer, strips spaces and makes the answer uppercase | |
print "Answer: " | |
user_response = gets.chomp.upcase.strip | |
# Keep prompting the user until a valid answer is input | |
until valid_input.include?(user_response) == true | |
puts "Please answer either A,B,C or D" | |
print "Answer: " | |
user_response = gets.chomp.upcase.strip | |
end | |
# If the answer is correct, add one to c, puts Correct, and go to the next question | |
if "#{user_response}\n" == questions_array[x][0] | |
c += 1 | |
puts "Correct!" | |
puts "(#{c} Correct, #{w} Wrong)\n\n" | |
# If the answer is wrong, add one to w, puts Wrong, and go to the next question | |
else | |
w += 1 | |
puts "WRONG! The correct answer was #{questions_array[x][0]}" | |
puts "(#{c} Correct, #{w} Wrong)\n\n" | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment