Guest User

Untitled

a guest
Jul 19th, 2018
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.49 KB | None | 0 0
  1. # -*- coding: UTF-8 -*-
  2. # Author: Jonatan Littke
  3. # mathgame.py - A little random game I built for teaching Python
  4.  
  5. import time
  6. import random
  7.  
  8. class Question:
  9. def __init__(self):
  10. types = {"multiplication": "*", "addition": "+"}
  11. self.type = random.choice([v for k,v in types.iteritems()])
  12. self.figure_a = random.randint(1,10)
  13. self.figure_b = random.randint(1,10)
  14. self.math = "%i %s %i" % (self.figure_a, self.type, self.figure_b)
  15. self.question = "How much is %s? " % self.math
  16. self.answer = eval(self.math)
  17.  
  18. class Game:
  19. def __init__(self, questions):
  20. self.start_time = time.time()
  21. self.questions = questions
  22.  
  23. def run(self):
  24. for i in range(self.questions):
  25. q = Question()
  26. while raw_input(q.question) != str(q.answer):
  27. print "--> Wrong, try again!"
  28. print "--> Correct!"
  29. self.run_time = time.time() - self.start_time
  30. print "You completed %i questions in %.2f seconds!" % (self.questions, self.run_time)
  31. self.update_highscore()
  32.  
  33. def update_highscore(self):
  34. file = open('mathgame_highscore.dat', "r+")
  35. old_highscore = float(file.read())
  36. if old_highscore > self.run_time:
  37. file = open('myprogram_highscore.dat', "w+")
  38. file.write(str(self.run_time))
  39. print "NEW highscore! (Old was %.2f seconds)!" % (old_highscore)
  40.  
  41. # Run the program
  42. if __name__ == '__main__':
  43. game = Game(questions=5)
  44. game.run()
Add Comment
Please, Sign In to add comment