scipiguy

FutureLearn Files - Maths Game with Lists

Nov 24th, 2019
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.18 KB | None | 0 0
  1. try:
  2.     print("The 10 highest scores previously were")
  3.     with open("highscores.txt", "r") as f:
  4.         highscore = int(f.read())
  5.         #print("The highest score previously was ")
  6.         print(highscore)
  7. except:
  8.     print("Creating a new highscore.txt file")
  9.     f = open("highscores.txt", "w")
  10.     f.close()
  11.     #highscore = 0
  12.    
  13. while True:
  14.     scores = []
  15.     names = []
  16.  
  17.     name = input("\nWhat is your name:>> ")
  18.    
  19.     with open("highscores.txt", "r") as file:
  20.         for line in file:
  21.             line = line.strip("\n")
  22.             line = line.split(" ")
  23.             names.append(line[0])
  24.             scores.append(int(line[1]))
  25.     score = 0
  26.  
  27.     print("\n\nWelcome to the Maths Quiz")
  28.     print("Can you answer three questions and score maximum points?")
  29.  
  30.     print("\nQuestion 1: What is the product of 2x2x2?")
  31.     answer = int(input("Your answer :>> "))
  32.     if answer == 8:
  33.         print("Correct")
  34.         score += 1
  35.         print("Your score is", score)
  36.     else:
  37.         print("Incorrect, the answer is 8")
  38.         print("Your score is ", score)
  39.  
  40.     print("\nQuestion 2: What is the product of 3x3x3?")
  41.     answer = int(input("Your answer :>> "))
  42.     if answer == 27:
  43.         print("Correct")
  44.         score += 1
  45.         print("Your score is", score)
  46.     else:
  47.         print("Incorrect, the answer is 27")
  48.         print("Your score is ", score)
  49.  
  50.     print("\nQuestion 3: What is the product of 4x4x4?")
  51.     answer = int(input("Your answer :>> "))
  52.     if answer == 64:
  53.         print("Correct")
  54.         score += 1
  55.         print("Your score is", score)
  56.     else:
  57.         print("Incorrect, the answer is 64")
  58.         print("Your score is ", score)
  59.  
  60.     position = 0
  61.     for compare_score in scores:
  62.         if score < compare_score:
  63.             position = position + 1
  64.     scores.insert(position, score)
  65.     names.insert(position, name)
  66.     scores = scores[:10]
  67.     names = names[:10]
  68.  
  69.     print("\n**********\nHIGHSCORES\n**********")
  70.     with open("highscores.txt", "w") as file:
  71.         for i in range(len(scores)):
  72.             file.write(names[i] + " " + str(scores[i]) + "\n")
  73.             print(names[i] + " " + str(scores[i]))
Add Comment
Please, Sign In to add comment