pocket-friends/pocket_friends/game_files/classes/data_handler.py

68 lines
1.9 KiB
Python

import pocket_friends
import json
class DataHandler:
"""
Class that handles the hardware attributes and save files.
"""
def __init__(self):
# 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 class 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 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()
def update(self):
"""
Run the game logic.
"""
self.frames_passed += 1
# Run logic of the game every second.
if self.frames_passed >= game_fps:
# Add one to the age of the bloop.
self.attributes['age'] += 1
# Save the data when the age of the bloop is a multiple of 10.
if self.attributes['age'] % 10 == 0:
self.write_save()
# Reset frame counter
self.frames_passed = 0