-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathSaverAndLoader.gd
More file actions
92 lines (77 loc) · 2.41 KB
/
SaverAndLoader.gd
File metadata and controls
92 lines (77 loc) · 2.41 KB
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
extends Node
const FILE_NAME := "user://savegame.save"
const F_NAME := "filename"
const POS_X := "position_x"
const POS_Y := "position_y"
const PARENT := "parent"
var is_loading := false
var custom_data = {
missiles_unlocked = false,
boss_defeated = false
}
func save_game():
var file := File.new()
var err := file.open(FILE_NAME, File.WRITE)
if err:
print(err)
print("Game not saved! Could not open file for writing!")
return
file.store_line(to_json(custom_data))
var persistNodes := get_tree().get_nodes_in_group("Persists")
for node in persistNodes:
var nodeData:Dictionary = node.save()
if nodeData:
file.store_line(to_json(nodeData))
file.close()
func load_game():
var file := File.new()
if not file.file_exists(FILE_NAME):
print("Game not loaded! ", FILE_NAME, " does not exist!")
return
var err := file.open(FILE_NAME, File.READ)
if err:
print(err)
print("Game not loaded! Could not open file")
return
# Get rid of the existing nodes
# Note: Parents must ensure their children are corectly loaded
var persistNodes := get_tree().get_nodes_in_group("Persists")
for node in persistNodes:
node.queue_free()
if not file.eof_reached():
custom_data = parse_json(file.get_line())
while not file.eof_reached():
var lineFromFile := file.get_line()
if lineFromFile.empty():
continue
var currentLine = parse_json(lineFromFile)
if not currentLine:
print("Problem loading. Could not parse the following line:")
print(lineFromFile)
continue
if typeof(currentLine) != TYPE_DICTIONARY:
print("Problem loading. The following line is not a dictionary:")
print(lineFromFile)
continue
# Enforce a schema on the records being read in
# TODO: Implement this in a more flexible way
if (not currentLine.has(F_NAME)
or not currentLine.has(POS_X)
or not currentLine.has(POS_Y)
or not currentLine.has(PARENT)):
continue
var newNode:Node2D = (load(currentLine[F_NAME]) as PackedScene).instance()
if not newNode:
continue
newNode.position = Vector2(currentLine[POS_X], currentLine[POS_Y])
get_node(currentLine[PARENT]).add_child(newNode, true)
# TODO: Implement this such that we don't need the check
for property in currentLine.keys():
assert(typeof(property) == TYPE_STRING)
if (property == F_NAME
or property == POS_X
or property == POS_Y
or property == PARENT):
continue
newNode.set(property, currentLine[property])
file.close()