1
0
Fork 0
1bit-godot-course/metroidvania/SaverLoader.gd

55 lines
1.4 KiB
GDScript

extends Node
const save_path = "user://savegame.save"
var is_loading = false
var custom_data = { # Defaults
"boss_defeated": false,
"missiles": 0,
"missiles_unlocked": false,
"health": 4,
}
func save_game():
var save_game = File.new()
save_game.open(save_path, File.WRITE)
var persistingNodes = get_tree().get_nodes_in_group("Persists")
save_game.store_line(to_json(custom_data))
for node in persistingNodes:
var nodeData = node.save()
save_game.store_line(to_json(nodeData))
save_game.close()
func load_game():
var save_game = File.new()
if not save_game.file_exists(save_path):
return
var persistingNodes = get_tree().get_nodes_in_group("Persists")
for node in persistingNodes:
node.queue_free()
save_game.open(save_path, File.READ)
if not save_game.eof_reached():
custom_data = parse_json(save_game.get_line())
while not save_game.eof_reached():
var current_line = save_game.get_line()
if current_line == "":
continue
current_line = parse_json(current_line)
if current_line != null:
var newNode = load(current_line["filename"]).instance()
get_node(current_line["parent"]).add_child(newNode, true)
newNode.position = Vector2(current_line["position_x"], current_line["position_y"])
for property in current_line.keys():
if property != "filename" and property != "parent" and property != "position_x" and property != "position_y":
newNode.set(property, current_line[property])
save_game.close()