Godsim/scripts/world.gd

91 lines
2.6 KiB
GDScript

extends Node
var world_seed = 0;
var world_info = {
"seed": 0,
"name": "world"
}
func _ready():
#new_world()
pass
func new_world():
world_info.seed = round(Time.get_unix_time_from_system())
print("World seed is " + str(world_info.seed))
print("World name is " + str(world_info.name))
func save_world():
print("Saving world")
var save_game = FileAccess.open("user://%s.save" % world_info.name, FileAccess.WRITE)
# Saving world info
var world_save = world_info.duplicate()
world_save["node"] = "worldinfo"
save_game.store_line(JSON.stringify(world_save))
var save_nodes = get_tree().get_nodes_in_group("Persistent")
for node in save_nodes:
# Check the node is an instanced scene so it can be instanced again during load.
if node.scene_file_path.is_empty():
print("persistent node '%s' is not an instanced scene, skipped" % node.name)
continue
# Check the node has a save function.
if !node.has_method("save"):
print("persistent node '%s' is missing a save() function, skipped" % node.name)
continue
# Call the node's save function.
var node_data = node.call("save")
#print(node_data)
if (node_data == {}): continue
# JSON provides a static method to serialized JSON string.
var json_string = JSON.stringify(node_data)
# Store the save dictionary as a new line in the save file.
save_game.store_line(json_string)
func load_world(save_name):
if not FileAccess.file_exists("user://%s.save" % save_name):
return
var save_nodes = get_tree().get_nodes_in_group("Persistent")
for i in save_nodes:
i.queue_free()
var save_game = FileAccess.open("user://%s.save" % save_name, FileAccess.READ)
var earth = get_tree().root.get_node("world/Earth")
while save_game.get_position() < save_game.get_length():
var json_string = save_game.get_line()
var json = JSON.new()
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
var node_data = json.get_data()
var new_object
match node_data["node"]:
"tile":
new_object = preload("res://scenes/models/tile.tscn").instantiate()
earth.add_child(new_object)
new_object.position = Vector3(node_data["pos_x"], node_data["pos_y"], node_data["pos_z"])
new_object.add_to_group("Persistent")
new_object.update_tile()
"worldinfo":
world_info = node_data
world_info["node"] = null
continue
for i in node_data.keys():
if i == "node" or "pos" in i:
continue
new_object.set(i, node_data[i])
await get_tree().physics_frame
earth.mark_empty_tiles()