feat(highscore): add comments and json file

This commit is contained in:
Kevin Baumgartner
2026-05-08 16:55:58 +02:00
parent 7e6d1813b5
commit b466ee3d7c
2 changed files with 65 additions and 0 deletions
+38
View File
@@ -0,0 +1,38 @@
[
{
"name": "Niklas",
"ects": 55,
"time": "02:00",
"won": true
},
{
"name": "Anna",
"ects": 48,
"time": "01:35",
"won": true
},
{
"name": "Kevin",
"ects": 42,
"time": "01:58",
"won": true
},
{
"name": "Lena",
"ects": 35,
"time": "01:44",
"won": false
},
{
"name": "Lukas",
"ects": 20,
"time": "00:58",
"won": false
},
{
"name": "Max",
"ects": 12,
"time": "00:30",
"won": false
}
]
+27
View File
@@ -13,14 +13,33 @@ class Highscore:
self.save_scores([])
def load_scores(self):
"""
Will load the highscore json file.
:return: All scores form json file.
"""
with open(self.path, "r") as f:
return json.load(f)
def save_scores(self, scores):
"""
Write score data into json file. File will be overwritten.
:param scores: Scores to store in json highscore file.
:return: None.
"""
# save scores to file
with open(self.path, "w") as file:
json.dump(scores, file, indent=4)
def add_score(self, player_name, score_ects, time_survived, won):
"""
Add a new score to the list of existing scores from highscore file. The
number of entries is limited to 50.
:param player_name: Name of the player.
:param score_ects: Scored ECTS in game.
:param time_survived: Time survived in game.
:param won: Game won/lose.
:return: None.
"""
# load existing scores from file
scores = self.load_scores()
@@ -42,11 +61,19 @@ class Highscore:
self.save_scores(scores)
def get_top_scores(self):
"""
Get top 5 scores from highscore file.
:return: Return top 5 scores as list.
"""
scores = self.load_scores()
scores.sort(key=lambda score: score["ects"], reverse=True)
return scores[:5]
def get_top_scores_formatted(self):
"""
Get top 5 scores from highscore file in nice format.
:return: Return top 5 scores as formatted string in list.
"""
top_scores = self.get_top_scores()
formatted_scores = []