-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHighScoresData.py
More file actions
71 lines (60 loc) · 2.41 KB
/
HighScoresData.py
File metadata and controls
71 lines (60 loc) · 2.41 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# HighScoresData class
from Constants import *
from pathlib import Path
import json
class HighScoresData():
"""The data file is stored as a list of lists in JSON format.
Each list is made up of a name and a score:
[[name, score], [name, score], [name, score] ...]
In this class, all scores are kept in self.scoresList
The list is kept in order of scores, highest to lowest.
"""
def __init__(self):
self.BLANK_SCORES_LIST = N_HIGH_SCORES * [['-----', 0]]
self.oFilePath = Path('HighScores.json')
# Try to open and load the data from the data file
try:
data = self.oFilePath.read_text()
except FileNotFoundError: # no file, set to blank scores and save
self.resetScores()
return
# File exists, load the scores from the JSON file
self.scoresList = json.loads(data)
def addHighScore(self, name, newHighScore):
# Find the appropriate place to add the new high score
placeFound = False
for index, nameScoreList in enumerate(self.scoresList):
thisScore = nameScoreList[1]
if newHighScore > thisScore:
# Insert into proper place, remove last entry
self.scoresList.insert(index, [name, newHighScore])
self.scoresList.pop(N_HIGH_SCORES)
placeFound = True
break
if not placeFound:
return # score does not belong in the list
# Save the updated scores
self.saveScores()
def saveScores(self):
scoresAsJson = json.dumps(self.scoresList)
self.oFilePath.write_text(scoresAsJson)
def resetScores(self):
self.scoresList = self.BLANK_SCORES_LIST.copy()
self.saveScores()
def getScoresAndNames(self):
namesList = []
scoresList = []
for nameAndScore in self.scoresList:
thisName = nameAndScore[0]
thisScore = nameAndScore[1]
namesList.append(thisName)
scoresList.append(thisScore)
return scoresList, namesList
def getHighestAndLowest(self):
# Element 0 is highest entry, element -1 is the lowest
highestEntry = self.scoresList[0]
lowestEntry = self.scoresList[-1]
# Get the score (element 1) of each sublist
highestScore = highestEntry[1]
lowestScore = lowestEntry[1]
return highestScore, lowestScore