-
Notifications
You must be signed in to change notification settings - Fork 0
/
save.py
132 lines (112 loc) · 4.51 KB
/
save.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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import os
import json
import lzma
def commit_save(savedata: dict, username) -> None:
"""
Writes passed savedata to the savefile in working directory.
"""
# Sort anything sort-able just for my sanity when debugging savefiles
username = username.lower()
for i in list(savedata.keys()):
if isinstance((savedata[i]), list):
savedata[i].sort()
json_vers = json.dumps(savedata)
with lzma.open("saves/" + username + '.save', 'wb') as f:
f.write(json_vers.encode())
return
def get_save(username) -> dict:
"""
Reads the savefile in working directory to a dictionary,
then returns the dictionary.
"""
username = username.lower()
with lzma.open("saves/" + username + '.save', 'rb') as f:
return json.loads(f.read().decode())
def list_saves() -> list:
saves = []
dir_contents = os.listdir("saves")
for item in dir_contents:
if item[-5:] == ".save":
saves += [item[:-5]]
saves.sort()
return saves
def init_save(username) -> list:
"""
Checks if savefile exists in working directory,
and if not, creates it with default settings.
"""
if username:
username = username.lower()
if os.path.exists("saves/" + username + '.save'):
return []
else:
commit_save({"Completed": [], "Settings": {}}, username)
return []
else:
saves = list_saves()
if saves:
return saves
else:
commit_save({"Completed": [], "Settings": {}}, 'User')
return ['User']
def rewrite_save(username) -> None:
"""
Rewrites the save with default settings.
"""
username = username.lower()
commit_save({"Completed": [], "Settings": {}}, username)
return
def erase_save(username) -> None:
"""
Rewrites the save with default settings.
"""
username = username.lower()
os.remove("saves/" + username + '.save')
return
def add_savedata(category: str, data: list, username, categorytype: str = "list") -> bool:
"""
Adds variable $data to the key of $category in the savedata.
"""
username = username.lower()
savedata = get_save(username) # We need the savedata so we don't overwrite anything
if categorytype == "list": # If we're dealing with a list,
if data[0] not in savedata[category]: # > We can simply check if the given data exists, and if it doesn't:
savedata[category] += [data[0]] # > > Add it to the list in our savedata variable
commit_save(savedata, username) # > > Write our new savedata to the system
return True # > > And exit out, happy and free!
elif categorytype == "dict": # If we have a dictionary,
savedata[category][data[0]] = data[1] # > It doesn't matter if the data exists, we just need to set the value
commit_save(savedata, username) # > Write the new savedata to the system
return True # > And exit.
else: # If it's neither a list nor dictionary, something's gone wrong!
raise ValueError("Save data additions must be in a list or dictionary.")
def check_savedata(category: str, data: str, username) -> bool:
"""
Checks if $data exists in $category of the savedata
"""
username = username.lower()
savedata = get_save(username)
if data in savedata[category]:
if isinstance(savedata[category], list):
return True
elif isinstance(savedata[category], dict):
return savedata[category][data]
else:
return False
def decompress_save(username) -> None:
username = username.lower()
if os.path.exists(savedata):
with open(username + ".json", 'wt') as f:
json.dump(get_save(), f, ensure_ascii=False, indent=4)
else:
print("No compressed save file to decompress.\nMaybe try playing the game?")
def compress_save(username) -> None:
username = username.lower()
if os.path.exists(username + ".json"):
with open(username + ".json", 'rt') as f:
commit_save(json.load(f), username)
jsonSize = os.path.getsize("saves/" + username + ".json")
lzmaSize = os.path.getsize("saves/" + username + ".save")
print(f"Compressed {jsonSize} to {lzmaSize}, saving {round((1-(lzmaSize/jsonSize))*100)}% of the space!")
else:
print("No decompressed save file to compress")