saving_games.rst 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. .. _doc_saving_games:
  2. Saving games
  3. ============
  4. Introduction
  5. ------------
  6. Save games can be complicated. For example, it may be desirable
  7. to store information from multiple objects across multiple levels.
  8. Advanced save game systems should allow for additional information about
  9. an arbitrary number of objects. This will allow the save function to
  10. scale as the game grows more complex.
  11. .. note::
  12. If you're looking to save user configuration, you can use the
  13. :ref:`class_ConfigFile` class for this purpose.
  14. Identify persistent objects
  15. ---------------------------
  16. Firstly, we should identify what objects we want to keep between game
  17. sessions and what information we want to keep from those objects. For
  18. this tutorial, we will use groups to mark and handle objects to be saved,
  19. but other methods are certainly possible.
  20. We will start by adding objects we wish to save to the "Persist" group. We can
  21. do this through either the GUI or script. Let's add the relevant nodes using the
  22. GUI:
  23. .. image:: img/groups.png
  24. Once this is done, when we need to save the game, we can get all objects
  25. to save them and then tell them all to save with this script:
  26. .. tabs::
  27. .. code-tab:: gdscript GDScript
  28. var save_nodes = get_tree().get_nodes_in_group("Persist")
  29. for i in save_nodes:
  30. # Now, we can call our save function on each node.
  31. .. code-tab:: csharp
  32. var saveNodes = GetTree().GetNodesInGroup("Persist");
  33. foreach (Node saveNode in saveNodes)
  34. {
  35. // Now, we can call our save function on each node.
  36. }
  37. Serializing
  38. -----------
  39. The next step is to serialize the data. This makes it much easier to
  40. read from and store to disk. In this case, we're assuming each member of
  41. group Persist is an instanced node and thus has a path. GDScript
  42. has helper functions for this, such as :ref:`to_json()
  43. <class_@GDScript_method_to_json>` and :ref:`parse_json()
  44. <class_@GDScript_method_parse_json>`, so we will use a dictionary. Our node needs to
  45. contain a save function that returns this data. The save function will look
  46. like this:
  47. .. tabs::
  48. .. code-tab:: gdscript GDScript
  49. func save():
  50. var save_dict = {
  51. "filename" : get_filename(),
  52. "parent" : get_parent().get_path(),
  53. "pos_x" : position.x, # Vector2 is not supported by JSON
  54. "pos_y" : position.y,
  55. "attack" : attack,
  56. "defense" : defense,
  57. "current_health" : current_health,
  58. "max_health" : max_health,
  59. "damage" : damage,
  60. "regen" : regen,
  61. "experience" : experience,
  62. "tnl" : tnl,
  63. "level" : level,
  64. "attack_growth" : attack_growth,
  65. "defense_growth" : defense_growth,
  66. "health_growth" : health_growth,
  67. "is_alive" : is_alive,
  68. "last_attack" : last_attack
  69. }
  70. return save_dict
  71. .. code-tab:: csharp
  72. public Godot.Collections.Dictionary<string, object> Save()
  73. {
  74. return new Godot.Collections.Dictionary<string, object>()
  75. {
  76. { "Filename", GetFilename() },
  77. { "Parent", GetParent().GetPath() },
  78. { "PosX", Position.x }, // Vector2 is not supported by JSON
  79. { "PosY", Position.y },
  80. { "Attack", Attack },
  81. { "Defense", Defense },
  82. { "CurrentHealth", CurrentHealth },
  83. { "MaxHealth", MaxHealth },
  84. { "Damage", Damage },
  85. { "Regen", Regen },
  86. { "Experience", Experience },
  87. { "Tnl", Tnl },
  88. { "Level", Level },
  89. { "AttackGrowth", AttackGrowth },
  90. { "DefenseGrowth", DefenseGrowth },
  91. { "HealthGrowth", HealthGrowth },
  92. { "IsAlive", IsAlive },
  93. { "LastAttack", LastAttack }
  94. };
  95. }
  96. This gives us a dictionary with the style
  97. ``{ "variable_name":value_of_variable }``, which will be useful when
  98. loading.
  99. Saving and reading data
  100. -----------------------
  101. As covered in the :ref:`doc_filesystem` tutorial, we'll need to open a file
  102. so we can write to it or read from it. Now that we have a way to
  103. call our groups and get their relevant data, let's use :ref:`to_json()
  104. <class_@GDScript_method_to_json>` to
  105. convert it into an easily stored string and store them in a file. Doing
  106. it this way ensures that each line is its own object, so we have an easy
  107. way to pull the data out of the file as well.
  108. .. tabs::
  109. .. code-tab:: gdscript GDScript
  110. # Note: This can be called from anywhere inside the tree. This function is
  111. # path independent.
  112. # Go through everything in the persist category and ask them to return a
  113. # dict of relevant variables.
  114. func save_game():
  115. var save_game = File.new()
  116. save_game.open("user://savegame.save", File.WRITE)
  117. var save_nodes = get_tree().get_nodes_in_group("Persist")
  118. for node in save_nodes:
  119. # Check the node is an instanced scene so it can be instanced again during load.
  120. if node.filename.empty():
  121. print("persistent node '%s' is not an instanced scene, skipped" % node.name)
  122. continue
  123. # Check the node has a save function.
  124. if !node.has_method("save"):
  125. print("persistent node '%s' is missing a save() function, skipped" % node.name)
  126. continue
  127. # Call the node's save function.
  128. var node_data = node.call("save")
  129. # Store the save dictionary as a new line in the save file.
  130. save_game.store_line(to_json(node_data))
  131. save_game.close()
  132. .. code-tab:: csharp
  133. // Note: This can be called from anywhere inside the tree. This function is
  134. // path independent.
  135. // Go through everything in the persist category and ask them to return a
  136. // dict of relevant variables.
  137. public void SaveGame()
  138. {
  139. var saveGame = new File();
  140. saveGame.Open("user://savegame.save", (int)File.ModeFlags.Write);
  141. var saveNodes = GetTree().GetNodesInGroup("Persist");
  142. foreach (Node saveNode in saveNodes)
  143. {
  144. // Check the node is an instanced scene so it can be instanced again during load.
  145. if (saveNode.Filename.Empty())
  146. {
  147. GD.Print(String.Format("persistent node '{0}' is not an instanced scene, skipped", saveNode.Name));
  148. continue;
  149. }
  150. // Check the node has a save function.
  151. if (!saveNode.HasMethod("Save"))
  152. {
  153. GD.Print(String.Format("persistent node '{0}' is missing a Save() function, skipped", saveNode.Name));
  154. continue;
  155. }
  156. // Call the node's save function.
  157. var nodeData = saveNode.Call("Save");
  158. // Store the save dictionary as a new line in the save file.
  159. saveGame.StoreLine(JSON.Print(nodeData));
  160. }
  161. saveGame.Close();
  162. }
  163. Game saved! Loading is fairly simple as well. For that, we'll read each
  164. line, use parse_json() to read it back to a dict, and then iterate over
  165. the dict to read our values. But we'll need to first create the object
  166. and we can use the filename and parent values to achieve that. Here is our
  167. load function:
  168. .. tabs::
  169. .. code-tab:: gdscript GDScript
  170. # Note: This can be called from anywhere inside the tree. This function
  171. # is path independent.
  172. func load_game():
  173. var save_game = File.new()
  174. if not save_game.file_exists("user://savegame.save"):
  175. return # Error! We don't have a save to load.
  176. # We need to revert the game state so we're not cloning objects
  177. # during loading. This will vary wildly depending on the needs of a
  178. # project, so take care with this step.
  179. # For our example, we will accomplish this by deleting saveable objects.
  180. var save_nodes = get_tree().get_nodes_in_group("Persist")
  181. for i in save_nodes:
  182. i.queue_free()
  183. # Load the file line by line and process that dictionary to restore
  184. # the object it represents.
  185. save_game.open("user://savegame.save", File.READ)
  186. while save_game.get_position() < save_game.get_len():
  187. # Get the saved dictionary from the next line in the save file
  188. var node_data = parse_json(save_game.get_line())
  189. # Firstly, we need to create the object and add it to the tree and set its position.
  190. var new_object = load(node_data["filename"]).instance()
  191. get_node(node_data["parent"]).add_child(new_object)
  192. new_object.position = Vector2(node_data["pos_x"], node_data["pos_y"])
  193. # Now we set the remaining variables.
  194. for i in node_data.keys():
  195. if i == "filename" or i == "parent" or i == "pos_x" or i == "pos_y":
  196. continue
  197. new_object.set(i, node_data[i])
  198. save_game.close()
  199. .. code-tab:: csharp
  200. // Note: This can be called from anywhere inside the tree. This function is
  201. // path independent.
  202. public void LoadGame()
  203. {
  204. var saveGame = new File();
  205. if (!saveGame.FileExists("user://savegame.save"))
  206. return; // Error! We don't have a save to load.
  207. // We need to revert the game state so we're not cloning objects during loading.
  208. // This will vary wildly depending on the needs of a project, so take care with
  209. // this step.
  210. // For our example, we will accomplish this by deleting saveable objects.
  211. var saveNodes = GetTree().GetNodesInGroup("Persist");
  212. foreach (Node saveNode in saveNodes)
  213. saveNode.QueueFree();
  214. // Load the file line by line and process that dictionary to restore the object
  215. // it represents.
  216. saveGame.Open("user://savegame.save", (int)File.ModeFlags.Read);
  217. while (saveGame.GetPosition() < saveGame.GetLen())
  218. {
  219. // Get the saved dictionary from the next line in the save file
  220. var nodeData = new Godot.Collections.Dictionary<string, object>((Godot.Collections.Dictionary)JSON.Parse(saveGame.GetLine()).Result);
  221. // Firstly, we need to create the object and add it to the tree and set its position.
  222. var newObjectScene = (PackedScene)ResourceLoader.Load(nodeData["Filename"].ToString());
  223. var newObject = (Node)newObjectScene.Instance();
  224. GetNode(nodeData["Parent"].ToString()).AddChild(newObject);
  225. newObject.Set("Position", new Vector2((float)nodeData["PosX"], (float)nodeData["PosY"]));
  226. // Now we set the remaining variables.
  227. foreach (KeyValuePair<string, object> entry in nodeData)
  228. {
  229. string key = entry.Key.ToString();
  230. if (key == "Filename" || key == "Parent" || key == "PosX" || key == "PosY")
  231. continue;
  232. newObject.Set(key, entry.Value);
  233. }
  234. }
  235. saveGame.Close();
  236. }
  237. Now we can save and load an arbitrary number of objects laid out
  238. almost anywhere across the scene tree! Each object can store different
  239. data depending on what it needs to save.
  240. Some notes
  241. ----------
  242. We have glossed over setting up the game state for loading. It's ultimately up
  243. to the project creator where much of this logic goes.
  244. This is often complicated and will need to be heavily
  245. customized based on the needs of the individual project.
  246. Additionally, our implementation assumes no Persist objects are children of other
  247. Persist objects. Otherwise, invalid paths would be created. To
  248. accommodate nested Persist objects, consider saving objects in stages.
  249. Load parent objects first so they are available for the :ref:`add_child()
  250. <class_node_method_add_child>`
  251. call when child objects are loaded. You will also need a way to link
  252. children to parents as the :ref:`NodePath
  253. <class_nodepath>` will likely be invalid.