I am currently working on a Python number guessing game. In my game, players achieve "high scores" by making the fewest guesses possible. I plan to record those high scores in a text file.
Players earn a spot on the high-score list by finishing the game in fewer guesses than some previous high score. How can I modify and then write a new high score list to my "Top 10" text file? Below is the code for the program.
from random import randint
a = True
n = randint(1,10)
guesses = 0
highscores = []
i = 0
beatenscores = 0
#If scores ever need to be reset just run function
def overwritefile():
f = open("Numbergame.txt", "w")
f.close()
#overwritefile()
#Guessing Game Code
while a == True:
guess = int(input("What is your guess? \nEnter a number!"))
if guess > n:
print("Guess is too high! \nTry Again!")
guesses += 1
elif guess < n:
print("Guess is too low! \nTry Again!")
guesses += 1
else:
guesses += 1
a = False
print("You guessed the number! \nIt was " + str(n) + "\nIt took you: " + str(guesses) + " guesses")
#Adding Score to the file
##f = open("Numbergame.txt", "a")
##f.write(str(guesses) + '\n')
##f.close()
# Retrieve the values from the text file and add them to as list, where they can be ints
# Maybe I will use the TRY thing got taught recently might help iron out some errors
with open('Numbergame.txt', 'rt') as f:
for line in f:
highscores.append(int(line.strip()))
print(highscores)
# Compare the values from the list and current one
for i in range(len(highscores)):
if highscores[i] > guesses:
print(guesses)
print(highscores[i])
beatenscores += 1
i + 1
else:
beatenscores += 0
print("You have beaten " + str(beatenscores)+ " scores")