Advertisement
Guest User

Untitled

a guest
Feb 4th, 2015
297
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.22 KB | None | 0 0
  1. # Trivia Challenge
  2. # Trivia game that reads a plain text file
  3.  
  4. import sys
  5.  
  6. def open_file(file_name, mode):
  7.     """Open a file."""
  8.     try:
  9.         the_file = open(file_name, mode)
  10.     except IOError as e:
  11.         print("Unable to open the file", file_name, "Ending program.\n", e)
  12.         input("\n\nPress the enter key to exit.")
  13.         sys.exit()
  14.     else:
  15.         return the_file
  16.  
  17. def next_line(the_file):
  18.     """Return next line from the trivia file, formatted."""
  19.     line = the_file.readline()
  20.     line = line.replace("/", "\n")
  21.     return line
  22.  
  23. def next_block(the_file):
  24.     """Return the next block of data from the trivia file."""
  25.     category = next_line(the_file)
  26.    
  27.     question = next_line(the_file)
  28.    
  29.     answers = []
  30.     for i in range(4):
  31.         answers.append(next_line(the_file))
  32.        
  33.     correct = next_line(the_file)
  34.     if correct:
  35.         correct = correct[0]
  36.     explanation = next_line(the_file)
  37.     points = int(next_line(the_file))
  38.  
  39.     return category, question, answers, correct, explanation, points
  40.  
  41. def welcome(title):
  42.     """Welcome the player and get his/her name."""
  43.     print("\t\tWelcome to Trivia Challenge!\n")
  44.     print("\t\t", title, "\n")
  45.  
  46. def main():
  47.     trivia_file = open_file("trivia.txt", "r")
  48.     title = next_line(trivia_file)
  49.     welcome(title)
  50.     score = 0
  51.  
  52.     # get first block
  53.     category, question, answers, correct, explanation, points = next_block(trivia_file)
  54.     while category:
  55.         # ask a question
  56.         print(category)
  57.         print(question)
  58.         for i in range(4):
  59.             print("\t", i + 1, "-", answers[i])
  60.  
  61.         # get answer
  62.         answer = input("What's your answer?: ")
  63.  
  64.         # check answer
  65.         if answer == correct:
  66.             print("\n Right! ", end = " ")
  67.             score += points
  68.         else:
  69.             print("\nWrong.", end=" ")
  70.         print(explanation)
  71.         print("Score:", score, "\n\n")
  72.  
  73.         # get next block
  74.         category, question, answers, correct, explanation, points = next_block(trivia_file)
  75.  
  76.     trivia_file.close()
  77.  
  78.     print("That was the last question!")
  79.     print("You're final score is", score)
  80.  
  81. main()  
  82. input("\n\nPress the enter key to exit.")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement