monsterfangen/globals/save_game.gd

73 lines
2.4 KiB
GDScript

extends Node
# save_game.gd - Responsible for saving and loading the game using a SaveData resource
const SAVE_GAME_PATH := "user://savegame.save"
const VERSION: int = 1
# List all the nodes and resouces to save
var save_data: Resource = SaveData.new()
func save() -> void:
var save_file = FileAccess.open(SAVE_GAME_PATH, FileAccess.WRITE)
# Save the meta data like save game version and timestamps
var meta_data = {
"meta": {
"version" : VERSION,
"timestamp" : Time.get_datetime_string_from_system()
}
}
var meta_json_string = JSON.stringify(meta_data)
save_file.store_line(meta_json_string)
# for now, only save the savedata resource from above
if !save_data.has_method("save"):
print("Resource '%s' is missing a save() function, skipped" %save_data.resource_name)
return
# Call the node's / resource's save function
var node_data = save_data.call("save")
# Serialize the JSON string
var json_string = JSON.stringify(node_data)
# Store the save dictionary as a new line in the save file
save_file.store_line(json_string)
func load() -> void:
if not FileAccess.file_exists(SAVE_GAME_PATH):
print("No save file exists.")
return
# Load the save file line by line and process the dictionary to restore
# the object it represents
var save_file = FileAccess.open(SAVE_GAME_PATH, FileAccess.READ)
while save_file.get_position() < save_file.get_length():
var json_string = save_file.get_line()
# Creates the helper class to interact with JSON
var json = JSON.new()
# Check if there is any error while parsing the JSON string, skip in case of failure
var parse_result = json.parse(json_string)
if not parse_result == OK:
print("JSON Parse Error: ", json.get_error_message(), " in ", json_string, " at line", json.get_error_line())
continue
# Get the data from the JSON object
var node_data = json.get_data()
# handle the player data (name, money, etc.)
if node_data.has("player_data"):
print("save_game.gd: ", node_data)
# Firstly, we need to create the object and add it to the tree and set its position.
#var new_object = load(node_data["filename"]).instantiate()
#get_node(node_data["parent"]).add_child(new_object)
#new_object.position = Vector2(node_data["pos_x"], node_data["pos_y"])
# Now we set the remaining variables.
#for i in node_data.keys():
# if i == "filename" or i == "parent" or i == "pos_x" or i == "pos_y":
# continue
# new_object.set(i, node_data[i])