Python Forum
Highscore problem, need to print top 5
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Highscore problem, need to print top 5
#2
Well the problem is, that you tell the program to print all high scores that were ever made.
instead of doing this:
text_file = open("Scores.txt", "r")
whole_thing = text_file.read()
print (whole_thing)
text_file.close()
you could simply do this
with open("Scores.txt", "r") as text_file:
    lines = text_file.readlines()
    top_5_scores = reverse([f.rstrip() for f in lines][-5 if len(lines > 4) else 0:])
The good thing is, you already sort the file while building it. Since you check if the new score is higher than the highest high score and then append it to the end, the scores are sorted from lowest to highest.
so you could reduce the highscore function to this:
def highScore(score, enterUsername):
    highscore = 0
    last_high_score = 0
    with open("Scores.txt", "r") as text_file:
        line_parts = text_file.readlines()[-1].split(" has a score of ")
        if len(line_parts) > 1:
            last_high_score = int(line_parts[0])
    if int(score) > last_high_score:
        with open("Scores.txt", "a") as text_file:
            text_file.write("\n"+ str(enterUsername) +' has a score of '+ str(score) +"\n")
 
    print ("\n")
    with open("Scores.txt", "r") as text_file:
        top_5_scores = reverse([f.rstrip() for f in text_file.readlines()][-5 if len(lines > 4) else 0:]
        for entry in top_5_scores:
             print(entry)
Reply


Messages In This Thread
RE: Highscore problem, need to print top 5 - by ThiefOfTime - Jan-28-2020, 01:14 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  problem with print command in super() akbarza 5 691 Feb-01-2024, 12:25 PM
Last Post: deanhystad
  problem with spliting line in print akbarza 3 460 Jan-23-2024, 04:11 PM
Last Post: deanhystad
  problem with print lists MarekGwozdz 4 778 Dec-15-2023, 09:13 AM
Last Post: Pedroski55
  Problem with print variable in print.cell (fpdf) muconi 0 696 Dec-25-2022, 02:24 PM
Last Post: muconi
  C to Python code conversion print problem anakk1n 1 2,221 May-22-2020, 04:15 PM
Last Post: deanhystad
  problem with print format anna 7 4,441 May-16-2018, 11:28 AM
Last Post: anna

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020