feat(highscore): add methods for highscore handling

This commit is contained in:
Kevin Baumgartner
2026-05-08 16:18:25 +02:00
parent 3c8e0a9b9a
commit 7846bfa042
+35 -5
View File
@@ -2,16 +2,46 @@ import json
class Highscore: class Highscore:
def __init__(self): def __init__(self):
# fix path to json file with highscores
self.path = "./highscore.json" self.path = "./highscore.json"
def load_scores(self): # check if file already exists, otherwise create it
try:
with open(self.path, "r") as f:
pass pass
except FileNotFoundError:
self.save_scores([])
def load_scores(self):
with open(self.path, "r") as f:
return json.load(f)
def save_scores(self, scores): def save_scores(self, scores):
pass with open(self.path, "w") as file:
json.dump(scores, file, indent=4)
def add_score(self, player_name, score_ects, time_survived, won): def add_score(self, player_name, score_ects, time_survived, won):
pass # load existing scores from file
scores = self.load_scores()
def get_top_scores(self, number_of_top_scores): # assign values from new score and append to existing scores
pass new_score = {
"name": player_name,
"ects": score_ects,
"time": time_survived,
"won": won
}
scores.append(new_score)
# sort by ects descending
scores.sort(key=lambda score: score["ects"], reverse=True)
# keep only top 50 elements
scores = scores[:50]
self.save_scores(scores)
def get_top_scores(self):
scores = self.load_scores()
scores.sort(key=lambda score: score["ects"], reverse=True)
return scores[:5]