Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #import libraries
- from random import randint
- from time import sleep
- #play/quit game function and highscore comparison
- def math_game(player_score, player_name):
- #load highscore
- try:
- print("The 10 highest scores previously were")
- with open("highscore.txt", "r") as f:
- highscore = f.read()
- print(highscore)
- except:
- print("Creating a new highscore.txt file")
- f = open('highscore.txt', 'w')
- f.close()
- #leave condition to break infinite loop
- play_on = True
- #load previous highscores and names into lists for comparison
- while play_on == True:
- scores = []
- names = []
- with open("highscore.txt", 'r') as file:
- for line in file:
- line = line.strip("\n")
- line = line.split(" ")
- names.append(line[0])
- scores.append(int(line[1]))
- #compare highscore
- position = 0
- for compare_score in scores:
- #if less than compare score, move to next
- if player_score < compare_score:
- position = position + 1
- #insert new name and score then cut list to top 10 names
- scores.insert(position, player_score)
- names.insert(position, player_name)
- scores = scores[:10]
- names = names[:10]
- #play/quit options
- print("HIGHSCORES")
- with open("highscore.txt", 'w') as file:
- for i in range(len(scores)):
- file.write(names[i] + " " + str(scores[i]) + "\n")
- print(names[i] + " " + str(scores[i]))
- #update leave condition
- play_on = play_quit()
- #main game function
- def new_game():
- print("Starting a new math game!")
- user_name = input("What is your name? ")
- score = 0
- turns = 0
- #run for 10 rounds
- while turns < 10:
- #create two random variables between 0 and 9
- factor_A = randint(0,9)
- factor_B = randint(0,9)
- #ask user to multiply variables
- try:
- question = int(input(str(factor_A) + " times " + str(factor_B) + " is:"))
- #if the answer is correct, change score by 1, or else do not
- if question == factor_A * factor_B:
- print("Correct!")
- score += 1
- else:
- print("Incorrect")
- #report score
- print("Your score is: " + str(score))
- turns += 1
- except ValueError:
- print("Integers only!")
- #recall play/quit function
- math_game(score, user_name)
- #opening play/quit function with score of 0
- def play_quit():
- try:
- play = int(input("Choose [1] to play or any other number to quit:"))
- if play == 1:
- new_game()
- else:
- #return False to update leave condition
- print("Thanks for playing!")
- return False
- except ValueError:
- print("Integers only!")
- math_game(0)
- #call play/quit function
- play_quit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement