feat(highscore): add methods for highscore handling
This commit is contained in:
+35
-5
@@ -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
|
||||
# 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]
|
||||
Reference in New Issue
Block a user