I am developing a game and i need to add a leader board to it. I have coded one which allows the user to add high scores, view high scores and erase all high score. Now I need to sort all the scores in order of highest to lowest. Here's my code currently [NOTE: I'm aware that this isn't the best menu but I will change that later on]:
choice = input(str("Would you like to add a high score to the leader board?: "))
if choice == "y":
user1 = input(str("Enter username 1: "))
hs1 = input(str("Enter high score: "))
user2 = input(str("Enter username 2: "))
hs2 = input(str("Enter high score: "))
data1 = user1 + ": " + hs1
data2 = user2 + ": " + hs2
with open("leaderboard.txt","a") as file:
file.write(data1)
file.write("\n")
file.write(data2)
file.write("\n")
print("Data added.")
elif choice == "n":
final_list = []
with open("leaderboard.txt","r") as file:
first_list = file.readlines()
for i in first_list:
final_list.append(i.strip())
print("Leader board")
print("-------------")
for count in range(0,len(final_list)):
print(final_list[count])
else:
with open("leaderboard.txt","w") as file:
file.write(" ")
print("leader board cleared.")
I would like the leader board to be displayed once ordered something like this:
1. James F: 32
2. Harris W: 18
3. Courtney J: 12
Thank you for reading!