save/load current game
This commit is contained in:
parent
a44ec0a41b
commit
0c905be6fc
3 changed files with 131 additions and 22 deletions
48
src/Main.gd
48
src/Main.gd
|
@ -3,8 +3,56 @@ extends Control
|
|||
onready var taquin = $HSplitContainer/Taquin
|
||||
|
||||
func _ready():
|
||||
load_game()
|
||||
print("Starting state: ", taquin.current_state_name())
|
||||
|
||||
func _notification(what):
|
||||
if what == MainLoop.NOTIFICATION_WM_QUIT_REQUEST:
|
||||
save_game()
|
||||
get_tree().quit() # default behavior
|
||||
|
||||
# https://docs.godotengine.org/en/3.2/tutorials/io/saving_games.html
|
||||
func save_game():
|
||||
var save_game = File.new()
|
||||
save_game.open("user://savegame.save", File.WRITE)
|
||||
var save_nodes = get_tree().get_nodes_in_group("Persist")
|
||||
for node in save_nodes:
|
||||
# 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")
|
||||
|
||||
# Augment data with origin
|
||||
node_data["path"] = node.get_path()
|
||||
|
||||
# Store the save dictionary as a new line in the save file
|
||||
save_game.store_line(to_json(node_data))
|
||||
save_game.close()
|
||||
|
||||
func load_game():
|
||||
var save_game = File.new()
|
||||
if not save_game.file_exists("user://savegame.save"):
|
||||
return # Error! We don't have a save to load.
|
||||
|
||||
# Load the file line by line and process that dictionary to restore
|
||||
# the object it represents.
|
||||
save_game.open("user://savegame.save", File.READ)
|
||||
while save_game.get_position() < save_game.get_len():
|
||||
# Get the saved dictionary from the next line in the save file
|
||||
var node_data = parse_json(save_game.get_line())
|
||||
|
||||
# Call the node's save function
|
||||
var node = get_node(node_data["path"])
|
||||
node.call("load", node_data)
|
||||
|
||||
save_game.close()
|
||||
|
||||
#
|
||||
# Signals
|
||||
#
|
||||
func _on_Taquin_state_changed(previous, new):
|
||||
print("Taquin state: ", Taquin.State.keys()[previous], " -> ", Taquin.State.keys()[new])
|
||||
match new:
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue