-
Notifications
You must be signed in to change notification settings - Fork 0
/
leaderboard.py
59 lines (47 loc) · 1.98 KB
/
leaderboard.py
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import json
import os
LEADERBOARD_FILE = 'leaderboard.json'
# Function to load leaderboard data from the JSON file
def load_leaderboard():
"""Load the leaderboard from the JSON file."""
if os.path.exists(LEADERBOARD_FILE):
try:
with open(LEADERBOARD_FILE, 'r') as file:
return json.load(file)
except (json.JSONDecodeError, IOError) as e:
print(f"Error reading leaderboard file: {e}")
return [] # Return an empty leaderboard in case of error
else:
return []
# Function to save leaderboard data to the JSON file
def save_leaderboard(leaderboard):
"""Save the leaderboard to the JSON file."""
try:
with open(LEADERBOARD_FILE, 'w') as file:
json.dump(leaderboard, file, indent=4)
except IOError as e:
print(f"Error saving leaderboard file: {e}")
# Function to add a new player and score to the leaderboard
def add_score(name, score):
"""Add a score for a player and update the leaderboard."""
if not isinstance(score, int) or score < 0:
print("Error: The score must be a non-negative integer.")
return # Do not add the score if it's invalid
leaderboard = load_leaderboard()
leaderboard.append({"name": name, "score": score})
leaderboard = sorted(leaderboard, key=lambda x: x['score'], reverse=True) # Sort by score in descending order
save_leaderboard(leaderboard)
# Function to get the current leaderboard (sorted by score)
def get_leaderboard():
"""Get the sorted leaderboard."""
leaderboard = load_leaderboard()
return sorted(leaderboard, key=lambda x: x['score'], reverse=True)
# Function to display the leaderboard
def display_leaderboard():
"""Display the leaderboard in a formatted way."""
leaderboard = get_leaderboard()
print("Leaderboard:")
print("{:<20} {:<10}".format("Player", "Score"))
print("-" * 30)
for entry in leaderboard:
print("{:<20} {:<10}".format(entry["name"], entry["score"]))