From 7846bfa04209cf2b9dd6b9a4f03fa8cad40b4caa Mon Sep 17 00:00:00 2001 From: Kevin Baumgartner Date: Fri, 8 May 2026 16:18:25 +0200 Subject: [PATCH] feat(highscore): add methods for highscore handling --- src/highscore.py | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/src/highscore.py b/src/highscore.py index 14f6564..16fae15 100644 --- a/src/highscore.py +++ b/src/highscore.py @@ -2,16 +2,46 @@ import json class Highscore: def __init__(self): + # fix path to json file with highscores self.path = "./highscore.json" + # check if file already exists, otherwise create it + try: + with open(self.path, "r") as f: + pass + except FileNotFoundError: + self.save_scores([]) + def load_scores(self): - pass + with open(self.path, "r") as f: + return json.load(f) 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): - pass + # load existing scores from file + scores = self.load_scores() - def get_top_scores(self, number_of_top_scores): - pass \ No newline at end of file + # assign values from new score and append to existing scores + 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] \ No newline at end of file