Advertisement
JAS_Software

Maths Quiz with Plot

May 5th, 2021
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.71 KB | None | 0 0
  1. from random import randint
  2. import matplotlib.pyplot as plot
  3.  
  4. def getPlayerName():
  5.     #get the players name
  6.     name = input('Enter your name: ').strip()
  7.     if name == '':
  8.         name = 'Unknown'
  9.     return name
  10.  
  11. def loadHighscores():
  12.     #load highscores and add to scores and names lists
  13.     scores = []
  14.     names = []
  15.     try:
  16.         with open('highscore.txt','r') as f:
  17.             for line in f:
  18.                 line = line.strip('\n')
  19.                 line = line.split(' ')
  20.                 names.append(line[0])
  21.                 scores.append(line[1])            
  22.     except FileNotFoundError:
  23.         print('Creating New Highscore File')
  24.         f = open('highscore.txt','w')
  25.         f.write('Unknown 0')
  26.         f.close()
  27.     return names,scores
  28.  
  29.  
  30. def displayHighScores(names,scores):
  31.     #print highscore table
  32.     print('')
  33.     print('NAME','\t','SCORE')
  34.     for pos in range(len(names)):
  35.         print(names[pos],'\t',scores[pos])
  36.     print('')
  37.  
  38.  
  39. def updateHighscores(names,name,scores,score):
  40.     #find the correct position for current score and insert into names scores lists
  41.     pos = 0
  42.     for current in scores:
  43.         if score < int(current):
  44.             pos += 1
  45.     scores.insert(pos,score)
  46.     names.insert(pos,name)
  47.     scores = scores[:10]
  48.     names = names[:10]
  49.     return names,scores
  50.  
  51. def saveHighscores(names,scores):
  52.     #write names and scores lists to highscore textfile
  53.     try:
  54.         with open('highscore.txt','w') as f:
  55.             for pos in range(len(scores)):
  56.                 f.write(names[pos] + ' ' + str(scores[pos]) + '\n')
  57.     except FileNotFoundError:
  58.         print('Creating New Highscore File')
  59.         f = open('highscore.txt','w')
  60.         f.write('Unknown 0')
  61.         f.close()
  62.  
  63.    
  64. def askQuestion(question):
  65.     #ask math question
  66.     a = randint(1,5)
  67.     b = randint(1,7)
  68.     c = randint(1,9)
  69.     answer = a * b * c
  70.     notValid = True
  71.     while notValid:
  72.         try:
  73.             response = int(input('{}. What is the product of {} * {} * {} ? '.format(question,a,b,c)))
  74.             notValid = False
  75.         except:
  76.             print('Invalid Input')
  77.             notValid = True
  78.     return answer,response
  79.  
  80.  
  81. def playAgain():
  82.     again = input('Do you want to play again (Y/N) ?').upper()
  83.     if again == 'Y':
  84.         return True
  85.     else:
  86.         return False
  87.  
  88. def welcome():
  89.     print('Welcome to the maths quiz')
  90.     print('Answer as many questions as you can')
  91.  
  92. def goodbye():
  93.     print('Goodbye, thank you for playing')
  94.  
  95. def quiz():
  96.     #ask questions until player gets one wrong
  97.     name = getPlayerName()
  98.     score = 0
  99.     ask = True
  100.     question = 0
  101.     while ask:
  102.         question += 1
  103.         answer, response = askQuestion(question)
  104.         if answer == response:
  105.             score += 1
  106.             #print('Correct, Score is {}'.format(score))
  107.         else:
  108.             print('Incorrect. The correct answer is {}'.format(answer))
  109.             print('{}, you scored {}'.format(name,score))
  110.             ask = False
  111.     return name,score
  112.  
  113. def game(names,scores):
  114.     again = True
  115.     while again:
  116.         name,score = quiz()    
  117.         names,scores = updateHighscores(names,name,scores,score)
  118.         saveHighscores(names,scores)
  119.         again = playAgain()
  120.     return names,scores
  121.  
  122. def showPlot(names,scores):
  123.     plot.bar(names,scores)
  124.     plot.title('Math Quiz Scores')
  125.     plot.ylabel('Scores')
  126.     plot.xlabel('Names')
  127.     #plot.gca().invert_yaxis()
  128.     #plot.gca().invert_xaxis()
  129.     plot.show()
  130.    
  131. #function calls
  132. welcome()
  133. names,scores = loadHighscores()
  134. displayHighScores(names,scores)
  135. names,scores = game(names,scores)
  136. displayHighScores(names,scores)
  137. showPlot(names,scores)
  138. goodbye()
  139.  
  140.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement