-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscore_handler.py
More file actions
52 lines (42 loc) · 1.46 KB
/
score_handler.py
File metadata and controls
52 lines (42 loc) · 1.46 KB
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
import json
import os
from datetime import datetime
import logging
SCORES_FILE = "scores.json"
def get_high_scores(limit=10):
"""Get the top high scores from the JSON file"""
try:
if not os.path.exists(SCORES_FILE):
return []
with open(SCORES_FILE, 'r') as file:
scores = json.load(file)
# Sort by score in descending order
sorted_scores = sorted(scores, key=lambda x: x['score'], reverse=True)
return sorted_scores[:limit]
except Exception as e:
logging.error(f"Error reading scores file: {e}")
return []
def save_score(player_name, score):
"""Save a new score to the JSON file"""
try:
scores = []
if os.path.exists(SCORES_FILE):
with open(SCORES_FILE, 'r') as file:
scores = json.load(file)
# Check for recent duplicate submissions
current_time = datetime.utcnow().isoformat()
# Create new score entry
new_score = {
'id': len(scores) + 1,
'player_name': player_name,
'score': score,
'created_at': current_time
}
scores.append(new_score)
# Write back to file
with open(SCORES_FILE, 'w') as file:
json.dump(scores, file)
return new_score
except Exception as e:
logging.error(f"Error saving score to file: {e}")
return None