pocket-friends/pocket_friends/io/data.py

56 lines
1.6 KiB
Python

import pocket_friends
import json
class SaveData:
"""
Class used to read and write save data for the game
Attributes:
attributes (dict): Dictionary containing all the attributes to read and write from a save file.
"""
def __init__(self):
"""
Constructs the object with all starting values.
"""
# Attributes that are saved to a file to recover upon startup.
self.attributes = {
'version': pocket_friends.__version__,
'time_elapsed': 0,
'bloop': '',
'age': 0,
'health': 0,
'hunger': 0,
'happiness': 0,
'care_counter': 0,
'missed_care': 0,
'adult': 0,
'evolution_stage': '',
}
# Frame counter
self.frames_passed = 0
def write_save(self):
"""
Writes attributes of the save object to "save.json" file.
"""
with open(save_dir + '/save.json', 'w') as save_file:
json.dump(self.attributes, save_file)
save_file.close()
def read_save(self):
"""
Reads from "save.json" and inserts into the save object's attributes dictionary. Creates file if it does not
exist.
"""
# Open up the save file and read it into self.attributes.
try:
with open(save_dir + '/save.json', 'r') as save_file:
self.attributes = json.load(save_file)
save_file.close()
# If there is no save file, write one with the defaults.
except FileNotFoundError:
self.write_save()