# 【保存游戏】
使用 var2str 和 str2var 进行保存和恢复游戏。
extends Node2D
const SAVE_FILE_PATH := "user://game.save"
onready var save_button: Button = $HBoxContainer/SaveButton
onready var load_button: Button = $HBoxContainer/LoadButton
onready var reset_button: Button = $HBoxContainer/ResetButton
func _ready() -> void:
save_button.connect("pressed",self,"save")
save_button.connect("pressed",self,"load_save")
save_button.connect("pressed",self,"reset")
func save() -> void:
var save_data := {}
var units := get_tree().get_nodes_in_group("units")
for unit in units:
save_data[get_path_to(unit)] = {
"current_cell": unit.current_cell,
"rotation": unit.rotation
}
var data_as_string := var2str(save_data)
var file := File.new()
file.open(SAVE_FILE_PATH, File.WRITE)
file.store_string(data_as_string)
file.close()
func load_save() -> void:
var file := File.new()
file.open(SAVE_FILE_PATH, File.READ)
var data: Dictionary = str2var(file.get_as_text())
file.close()
var units := get_tree().get_nodes_in_group("units")
for unit in units:
var path := get_path_to(unit)
if data.has(path):
unit.current_cell = data[path].current_cell
unit.rotation = data[path].rotation
func reset() -> void:
get_tree().reload_current_scene()