Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: UTF-8 -*-
- # Author: Jonatan Littke
- # mathgame.py - A little random game I built for teaching Python
- import time
- import random
- class Question:
- def __init__(self):
- types = {"multiplication": "*", "addition": "+"}
- self.type = random.choice([v for k,v in types.iteritems()])
- self.figure_a = random.randint(1,10)
- self.figure_b = random.randint(1,10)
- self.math = "%i %s %i" % (self.figure_a, self.type, self.figure_b)
- self.question = "How much is %s? " % self.math
- self.answer = eval(self.math)
- class Game:
- def __init__(self, questions):
- self.start_time = time.time()
- self.questions = questions
- def run(self):
- for i in range(self.questions):
- q = Question()
- while raw_input(q.question) != str(q.answer):
- print "--> Wrong, try again!"
- print "--> Correct!"
- self.run_time = time.time() - self.start_time
- print "You completed %i questions in %.2f seconds!" % (self.questions, self.run_time)
- self.update_highscore()
- def update_highscore(self):
- file = open('mathgame_highscore.dat', "r+")
- old_highscore = float(file.read())
- if old_highscore > self.run_time:
- file = open('myprogram_highscore.dat', "w+")
- file.write(str(self.run_time))
- print "NEW highscore! (Old was %.2f seconds)!" % (old_highscore)
- # Run the program
- if __name__ == '__main__':
- game = Game(questions=5)
- game.run()
Add Comment
Please, Sign In to add comment