Jan-28-2020, 01:14 PM
(This post was last modified: Jan-28-2020, 01:15 PM by ThiefOfTime.)
Well the problem is, that you tell the program to print all high scores that were ever made.
instead of doing this:
so you could reduce the highscore function to this:
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)