简体   繁体   中英

how to make a ordered leader board in python

we have a computing project and in the final stages I have to make a ordered leader board (top5). however this is more confusing than i thought. I've got this far so far but it isn't ordered nor the top 5.

def leaderboard():
    print ("\n")
    print ("⬇ Check out the leaderboard ⬇") #LEADERBOARD SECTION
    f = open('H_Highscore.txt', 'r')
    leaderboard = [line.replace('\n','') for line in f.readlines()]
    i = 0
    limit = 5
    while i < limit:
        leaderboard_tuples = [tuple(x.split(',')) for x in leaderboard]
        leaderboard_tuples.sort(key=lambda tup: tup[0])
        i+=1
    for i in leaderboard:
        print(i)
    f.close()
    time.sleep(10)

user = str(input("Enter a name: "))
file = open ("H_Highscore.txt", "a")
score = str(input("enter you score: "))
file.write("\n")
file.write(user)
file.write(",")
file.write(str(score)) # (int(x)) can not be written
file.write("pts")
file.write("\n")
file.close()
time.sleep(0.5)
leaderboard() 

it would be great if got some help but it's fine if I can't find any help.

For what I can understand you want to sort the scores that you read from the file "H_Highscore.txt" and print them to the console in order from the highest to the smallest. There are some important points if you want to do that in a more robust ways:
- Add tests on the input data to make sure the user has entered a valid name/score pair, or else you wont be able to sort it afterwards (you will get an error).
-If you want to stick to you own way of doing things and not the solution I will provide you should use "with open('H_Highscore.txt', 'r') as f" instead of "f = open('H_Highscore.txt', 'r')" because the with statement will ensure that the file is closed in case of an errorr (read more about it here ).
-I changed up your code to work in the way I understood it should work but you should really take a good look at the way you are writing to the file and the whole way your CLI works, so that the user can interact with it without having to run the code over and over again, maybe add a while loop with a break variable.

import time

limit = 5 # you can set out the limit here.

def leaderboard():
    scores = [] 
    print ("\n") 
    print ("⬇ Check out the leaderboard ⬇")
    #LEADERBOARD SECTION 
    for line in open('H_Highscore.txt', 'r'):
        name, score = line.split(",")
        score = int(score) # clean and convert to int to order the scores using sort()
        scores.append((score, name))
        
    sorted_scores = sorted(scores, reverse = True) # this will sort the scores based on the first position of the tuples
    
    for register in sorted_scores[:limit]:
        # I will use string formating, take a look at it, it is really usefull.
        text = f"%s: %s pts" % (register[1], register[0])
        print(text)

user = str(input("Enter a name: "))
file = open("H_Highscore.txt", "a")
score = str(input("enter you score: "))
# file.write("\n")
file.write(user)
file.write(",")
file.write(str(score)) # (int(x)) can not be written
file.write("\n")
# file.write("\n")
file.close()
time.sleep(0.5)
leaderboard() 

Play around with the code, add prints to see what each variable does on the way!

EDIT: Some minor typos.

You seem to be sorting five times and listing all the items from the leaderboard instead of sorting once and listing the top five.

You should be doing this:

def leaderboard():
    print()
    print("⬇ Check out the leaderboard ⬇") #LEADERBOARD SECTION
    f = open('H_Highscore.txt', 'r')
    leaderboard = [line.strip().split(',') for line in f.readlines()]
    leaderboard.sort(key=lambda item: -int(item[1][:-3]))
    for i in leaderboard[:5]:
        print(i)
    f.close()
    time.sleep(10)

Note how I used the negative of the score to sort highest first.

I could have used: , reverse=True

You are trying to sort on a string, eg 10pts . Key is to convert the string representation of the integer that is read from the text file back to an integer with int() , and then sort on that:

def leaderboard():
    print ("\n")
    print ("⬇ Check out the leaderboard ⬇") #LEADERBOARD SECTION
    f = open('H_Highscore.txt', 'r')
    leaderboard = [line.strip().split(',') for line in f.readlines() if line.strip()]
    leaderboard = [(i[0], int(i[1][:-3])) for i in leaderboard]
    leaderboard.sort(key=lambda tup: tup[1], reverse=True)
    for i in leaderboard[:5]:
        print(i[0], i[1],'pts')
    f.close()
    time.sleep(10)

user = str(input("Enter a name: "))
file = open ("H_Highscore.txt", "a")
score = str(input("enter you score: "))
file.write(f"{user},{score}pts\n")
file.close()
time.sleep(0.5)
leaderboard() 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM