Reputation: 33
I used the code from https://stackoverflow.com/a/53299137/11001876 and it works so far but I'm not sure how to limit the highscores to only 5 with only the highest scores staying on the highscore text file. I've edited the code in the link to fit my program:
# Winning Code
elif U1Score > U2Score:
print(username1, "Won")
highscores = open("highscores.txt", "r")
highscores.close()
with open('highscores.txt', 'w') as f:
for username1, U1Score in scores:
f.write('Username: {0}, Score: {1}\n'.format(username1, U1Score))
highscores.close()
highscores = open("highscores.txt", "r")
print(highscores.read())
highscores.close()
else:
print(username2, "Won")
highscores = open("highscores.txt", "r")
highscores.close()
with open('highscores.txt', 'w') as f:
for username2, U2Score in scores:
f.write('Username: {0}, Score: {1}\n'.format(username2, U2Score))
highscores.close()
highscores = open("highscores.txt", "r")
print(highscores.read())
highscores.close()
However I'm still not sure how to limit the scores to 5 different scores and how to order them from highest to lowest. Thanks I'm new here :)
Upvotes: 1
Views: 67
Reputation: 1054
Simple solution is to instead of printing the file.read() read the file by lines (cause the delimiter you used is line) and then print just 5 lines.
Something like that maybe:
f = open("highscores.txt", "r")
highscores_lines = f.read()
for line in highscores_line[:5]:
print(line)
And if you want to order and print by descending you could use some sorting algorithm by the number in each line and order the lines before you print them.
reference for sorting - https://www.programiz.com/python-programming/methods/list/sort#targetText=The%20sort()%20method%20sorts,()%20for%20the%20same%20purpose.
Upvotes: 1