-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathleaderboard.py
More file actions
28 lines (22 loc) · 783 Bytes
/
leaderboard.py
File metadata and controls
28 lines (22 loc) · 783 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import json
from settings import HIGH_SCORE_FILE
class Leaderboard:
def __init__(self):
self.filepath = HIGH_SCORE_FILE
self.scores = self.load_scores()
def load_scores(self):
try:
with open(self.filepath, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return []
def save_scores(self):
with open(self.filepath, 'w') as f:
json.dump(self.scores, f, indent=4)
def add_score(self, name, score):
self.scores.append({'name': name, 'score': score})
self.scores.sort(key=lambda x: x['score'], reverse=True)
self.scores = self.scores[:10]
self.save_scores()
def get_scores(self):
return self.scores