保存游戏

简介

保存游戏可能很复杂。比如, 我们可能会想要储存跨多个关卡的多个物品的信息。更高级的保存游戏可能需要存储关于具有任意数量的对象的附加信息。当游戏变得更加复杂时,这将让保存函数可以随着游戏一同变得更加复杂。

注解

如果你想保存玩家的设置, 你可以用 ConfigFile 来实现这个目的。

识别持久化对象

首先,我们应该确定在游戏会话中要保存什么对象,以及我们要从这些对象中保存什么信息。本教程中,我们将使用组来标记和处理要保存的对象,但当然也有其他可行的方法。

首先我们将想要保存的对象添加到“Persist”组。 在 编写脚本(续) 教程中,我们学会了通过GUI或脚本完成此操作。 那就让我们使用GUI来添加相关节点吧:

../../_images/groups.png

完成此操作后, 在我们需要保存游戏时,我们可以获取所有对象以保存它们,然后告诉所有对象通过此脚本保存数据:

GDScript

C#

  1. var save_nodes = get_tree().get_nodes_in_group("Persist")
  2. for i in save_nodes:
  3. # Now, we can call our save function on each node.
  1. var saveNodes = GetTree().GetNodesInGroup("Persist");
  2. foreach (Node saveNode in saveNodes)
  3. {
  4. // Now, we can call our save function on each node.
  5. }

序列化

下一步是序列化数据。 这使得从硬盘读取数据和存储数据到硬盘变得更加容易。 在这种情况下,我们假设Persist组的每个成员都是一个实例化的节点,因此它们都有一个路径。 GDScript 有相关的辅助函数,如 to_json() 和 parse_json(),所以我们使用Dictionary来表示数据。 我们的节点需要包含一个返回Dictionary的保存函数。 保存函数看上去大概会像这样:

GDScript

C#

  1. func save():
  2. var save_dict = {
  3. "filename" : get_filename(),
  4. "parent" : get_parent().get_path(),
  5. "pos_x" : position.x, # Vector2 is not supported by JSON
  6. "pos_y" : position.y,
  7. "attack" : attack,
  8. "defense" : defense,
  9. "current_health" : current_health,
  10. "max_health" : max_health,
  11. "damage" : damage,
  12. "regen" : regen,
  13. "experience" : experience,
  14. "tnl" : tnl,
  15. "level" : level,
  16. "attack_growth" : attack_growth,
  17. "defense_growth" : defense_growth,
  18. "health_growth" : health_growth,
  19. "is_alive" : is_alive,
  20. "last_attack" : last_attack
  21. }
  22. return save_dict
  1. public Godot.Collections.Dictionary<string, object> Save()
  2. {
  3. return new Godot.Collections.Dictionary<string, object>()
  4. {
  5. { "Filename", GetFilename() },
  6. { "Parent", GetParent().GetPath() },
  7. { "PosX", Position.x }, // Vector2 is not supported by JSON
  8. { "PosY", Position.y },
  9. { "Attack", Attack },
  10. { "Defense", Defense },
  11. { "CurrentHealth", CurrentHealth },
  12. { "MaxHealth", MaxHealth },
  13. { "Damage", Damage },
  14. { "Regen", Regen },
  15. { "Experience", Experience },
  16. { "Tnl", Tnl },
  17. { "Level", Level },
  18. { "AttackGrowth", AttackGrowth },
  19. { "DefenseGrowth", DefenseGrowth },
  20. { "HealthGrowth", HealthGrowth },
  21. { "IsAlive", IsAlive },
  22. { "LastAttack", LastAttack }
  23. };
  24. }

我们得到一个样式为 { "variable_name":that_variables_value } 的字典,它在加载游戏数据时会被用到。

保存和读取数据

正如在 文件系统 教程中所述,我们需要打开一个文件来向其中写入或读取数据。 既然我们有办法调用我们的组并获取它们的相关数据,那么就让我们使用 to_json() 将数据转换成一个容易存储的字符串并将它存储在文件中吧。 这样做可以确保每一行都是一个完整的对象的信息,这样的话将数据从文件中提取出来也会更加容易。

GDScript

C#

  1. # Note: This can be called from anywhere inside the tree. This function is
  2. # path independent.
  3. # Go through everything in the persist category and ask them to return a
  4. # dict of relevant variables.
  5. func save_game():
  6. var save_game = File.new()
  7. save_game.open("user://savegame.save", File.WRITE)
  8. var save_nodes = get_tree().get_nodes_in_group("Persist")
  9. for node in save_nodes:
  10. # Check the node is an instanced scene so it can be instanced again during load.
  11. if node.filename.empty():
  12. print("persistent node '%s' is not an instanced scene, skipped" % node.name)
  13. continue
  14. # Check the node has a save function.
  15. if !node.has_method("save"):
  16. print("persistent node '%s' is missing a save() function, skipped" % node.name)
  17. continue
  18. # Call the node's save function.
  19. var node_data = node.call("save")
  20. # Store the save dictionary as a new line in the save file.
  21. save_game.store_line(to_json(node_data))
  22. save_game.close()
  1. // Note: This can be called from anywhere inside the tree. This function is
  2. // path independent.
  3. // Go through everything in the persist category and ask them to return a
  4. // dict of relevant variables.
  5. public void SaveGame()
  6. {
  7. var saveGame = new File();
  8. saveGame.Open("user://savegame.save", (int)File.ModeFlags.Write);
  9. var saveNodes = GetTree().GetNodesInGroup("Persist");
  10. foreach (Node saveNode in saveNodes)
  11. {
  12. // Check the node is an instanced scene so it can be instanced again during load.
  13. if (saveNode.Filename.Empty())
  14. {
  15. GD.Print(String.Format("persistent node '{0}' is not an instanced scene, skipped", saveNode.Name));
  16. continue;
  17. }
  18. // Check the node has a save function.
  19. if (!saveNode.HasMethod("Save"))
  20. {
  21. GD.Print(String.Format("persistent node '{0}' is missing a Save() function, skipped", saveNode.Name));
  22. continue;
  23. }
  24. // Call the node's save function.
  25. var nodeData = saveNode.Call("Save");
  26. // Store the save dictionary as a new line in the save file.
  27. saveGame.StoreLine(JSON.Print(nodeData));
  28. }
  29. saveGame.Close();
  30. }

游戏保存好了! 加载也很简单。 为此,我们将读取每一行,使用parse_json() 将其读回到一个字典中,然后遍历字典以读取保存的值。 首先我们需要创建对象,这可以通过使用文件名和父值来实现。 这就是我们的加载函数:

GDScript

C#

  1. # Note: This can be called from anywhere inside the tree. This function
  2. # is path independent.
  3. func load_game():
  4. var save_game = File.new()
  5. if not save_game.file_exists("user://savegame.save"):
  6. return # Error! We don't have a save to load.
  7. # We need to revert the game state so we're not cloning objects
  8. # during loading. This will vary wildly depending on the needs of a
  9. # project, so take care with this step.
  10. # For our example, we will accomplish this by deleting saveable objects.
  11. var save_nodes = get_tree().get_nodes_in_group("Persist")
  12. for i in save_nodes:
  13. i.queue_free()
  14. # Load the file line by line and process that dictionary to restore
  15. # the object it represents.
  16. save_game.open("user://savegame.save", File.READ)
  17. while save_game.get_position() < save_game.get_len():
  18. # Get the saved dictionary from the next line in the save file
  19. var node_data = parse_json(save_game.get_line())
  20. # Firstly, we need to create the object and add it to the tree and set its position.
  21. var new_object = load(node_data["filename"]).instance()
  22. get_node(node_data["parent"]).add_child(new_object)
  23. new_object.position = Vector2(node_data["pos_x"], node_data["pos_y"])
  24. # Now we set the remaining variables.
  25. for i in node_data.keys():
  26. if i == "filename" or i == "parent" or i == "pos_x" or i == "pos_y":
  27. continue
  28. new_object.set(i, node_data[i])
  29. save_game.close()
  1. // Note: This can be called from anywhere inside the tree. This function is
  2. // path independent.
  3. public void LoadGame()
  4. {
  5. var saveGame = new File();
  6. if (!saveGame.FileExists("user://savegame.save"))
  7. return; // Error! We don't have a save to load.
  8. // We need to revert the game state so we're not cloning objects during loading.
  9. // This will vary wildly depending on the needs of a project, so take care with
  10. // this step.
  11. // For our example, we will accomplish this by deleting saveable objects.
  12. var saveNodes = GetTree().GetNodesInGroup("Persist");
  13. foreach (Node saveNode in saveNodes)
  14. saveNode.QueueFree();
  15. // Load the file line by line and process that dictionary to restore the object
  16. // it represents.
  17. saveGame.Open("user://savegame.save", (int)File.ModeFlags.Read);
  18. while (saveGame.GetPosition() < saveGame.GetLen())
  19. {
  20. // Get the saved dictionary from the next line in the save file
  21. var nodeData = new Godot.Collections.Dictionary<string, object>((Godot.Collections.Dictionary)JSON.Parse(saveGame.GetLine()).Result);
  22. // Firstly, we need to create the object and add it to the tree and set its position.
  23. var newObjectScene = (PackedScene)ResourceLoader.Load(nodeData["Filename"].ToString());
  24. var newObject = (Node)newObjectScene.Instance();
  25. GetNode(nodeData["Parent"].ToString()).AddChild(newObject);
  26. newObject.Set("Position", new Vector2((float)nodeData["PosX"], (float)nodeData["PosY"]));
  27. // Now we set the remaining variables.
  28. foreach (KeyValuePair<object, object> entry in nodeData)
  29. {
  30. string key = entry.Key.ToString();
  31. if (key == "Filename" || key == "Parent" || key == "PosX" || key == "PosY")
  32. continue;
  33. newObject.Set(key, entry.Value);
  34. }
  35. }
  36. saveGame.Close();
  37. }

现在我们可以保存和加载几乎任何位于场景树中的任意数量的对象了! 每个对象可以根据需要保存的内容存储不同的数据。

一些注释

我们可能忽略了”将游戏状态设置到适合以加载数据”这一步。最终, 这一步怎么做的决定权在项目创建者手里。这通常很复杂, 需要根据单个项目的需求对此步骤进行大量定制。

另外, 此实现假定没有Persist对象是其他Persist对象的子对象。 否则会产生无效路径。 如果这是项目的需求之一,可以考虑分阶段保存对象(父对象优先),以便在加载子对象时可用它们将确保它们可用于 add_child() 调用。 由于 NodePath 可能无效,因此可能还需要某种方式将子项链接到父项。