saving_games.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  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 class :ref:`JSON<class_json>` to convert between dictionary and string,
  43. Our node needs to contain a save function that returns this data.
  44. The save function will look like this:
  45. .. tabs::
  46. .. code-tab:: gdscript GDScript
  47. func save():
  48. var save_dict = {
  49. "filename" : get_scene_file_path(),
  50. "parent" : get_parent().get_path(),
  51. "pos_x" : position.x, # Vector2 is not supported by JSON
  52. "pos_y" : position.y,
  53. "attack" : attack,
  54. "defense" : defense,
  55. "current_health" : current_health,
  56. "max_health" : max_health,
  57. "damage" : damage,
  58. "regen" : regen,
  59. "experience" : experience,
  60. "tnl" : tnl,
  61. "level" : level,
  62. "attack_growth" : attack_growth,
  63. "defense_growth" : defense_growth,
  64. "health_growth" : health_growth,
  65. "is_alive" : is_alive,
  66. "last_attack" : last_attack
  67. }
  68. return save_dict
  69. .. code-tab:: csharp
  70. public Godot.Collections.Dictionary<string, Variant> Save()
  71. {
  72. return new Godot.Collections.Dictionary<string, Variant>()
  73. {
  74. { "Filename", SceneFilePath },
  75. { "Parent", GetParent().GetPath() },
  76. { "PosX", Position.X }, // Vector2 is not supported by JSON
  77. { "PosY", Position.Y },
  78. { "Attack", Attack },
  79. { "Defense", Defense },
  80. { "CurrentHealth", CurrentHealth },
  81. { "MaxHealth", MaxHealth },
  82. { "Damage", Damage },
  83. { "Regen", Regen },
  84. { "Experience", Experience },
  85. { "Tnl", Tnl },
  86. { "Level", Level },
  87. { "AttackGrowth", AttackGrowth },
  88. { "DefenseGrowth", DefenseGrowth },
  89. { "HealthGrowth", HealthGrowth },
  90. { "IsAlive", IsAlive },
  91. { "LastAttack", LastAttack }
  92. };
  93. }
  94. This gives us a dictionary with the style
  95. ``{ "variable_name":value_of_variable }``, which will be useful when
  96. loading.
  97. Saving and reading data
  98. -----------------------
  99. As covered in the :ref:`doc_filesystem` tutorial, we'll need to open a file
  100. so we can write to it or read from it. Now that we have a way to
  101. call our groups and get their relevant data, let's use the class :ref:`JSON<class_json>` to
  102. convert it into an easily stored string and store them in a file. Doing
  103. it this way ensures that each line is its own object, so we have an easy
  104. way to pull the data out of the file as well.
  105. .. tabs::
  106. .. code-tab:: gdscript GDScript
  107. # Note: This can be called from anywhere inside the tree. This function is
  108. # path independent.
  109. # Go through everything in the persist category and ask them to return a
  110. # dict of relevant variables.
  111. func save_game():
  112. var save_game = FileAccess.open("user://savegame.save", FileAccess.WRITE)
  113. var save_nodes = get_tree().get_nodes_in_group("Persist")
  114. for node in save_nodes:
  115. # Check the node is an instanced scene so it can be instanced again during load.
  116. if node.scene_file_path.is_empty():
  117. print("persistent node '%s' is not an instanced scene, skipped" % node.name)
  118. continue
  119. # Check the node has a save function.
  120. if !node.has_method("save"):
  121. print("persistent node '%s' is missing a save() function, skipped" % node.name)
  122. continue
  123. # Call the node's save function.
  124. var node_data = node.call("save")
  125. # JSON provides a static method to serialized JSON string.
  126. var json_string = JSON.stringify(node_data)
  127. # Store the save dictionary as a new line in the save file.
  128. save_game.store_line(json_string)
  129. .. code-tab:: csharp
  130. // Note: This can be called from anywhere inside the tree. This function is
  131. // path independent.
  132. // Go through everything in the persist category and ask them to return a
  133. // dict of relevant variables.
  134. public void SaveGame()
  135. {
  136. using var saveGame = FileAccess.Open("user://savegame.save", FileAccess.ModeFlags.Write);
  137. var saveNodes = GetTree().GetNodesInGroup("Persist");
  138. foreach (Node saveNode in saveNodes)
  139. {
  140. // Check the node is an instanced scene so it can be instanced again during load.
  141. if (string.IsNullOrEmpty(saveNode.SceneFilePath))
  142. {
  143. GD.Print($"persistent node '{saveNode.Name}' is not an instanced scene, skipped");
  144. continue;
  145. }
  146. // Check the node has a save function.
  147. if (!saveNode.HasMethod("Save"))
  148. {
  149. GD.Print($"persistent node '{saveNode.Name}' is missing a Save() function, skipped");
  150. continue;
  151. }
  152. // Call the node's save function.
  153. var nodeData = saveNode.Call("Save");
  154. // Json provides a static method to serialized JSON string.
  155. var jsonString = Json.Stringify(nodeData);
  156. // Store the save dictionary as a new line in the save file.
  157. saveGame.StoreLine(jsonString);
  158. }
  159. }
  160. Game saved! Now, to load, we'll read each
  161. line. Use the :ref:`parse<class_JSON_method_parse>` method to read the
  162. JSON string back to a dictionary, and then iterate over
  163. the dict to read our values. But we'll need to first create the object
  164. and we can use the filename and parent values to achieve that. Here is our
  165. load function:
  166. .. tabs::
  167. .. code-tab:: gdscript GDScript
  168. # Note: This can be called from anywhere inside the tree. This function
  169. # is path independent.
  170. func load_game():
  171. if not FileAccess.file_exists("user://savegame.save"):
  172. return # Error! We don't have a save to load.
  173. # We need to revert the game state so we're not cloning objects
  174. # during loading. This will vary wildly depending on the needs of a
  175. # project, so take care with this step.
  176. # For our example, we will accomplish this by deleting saveable objects.
  177. var save_nodes = get_tree().get_nodes_in_group("Persist")
  178. for i in save_nodes:
  179. i.queue_free()
  180. # Load the file line by line and process that dictionary to restore
  181. # the object it represents.
  182. var save_game = FileAccess.open("user://savegame.save", FileAccess.READ)
  183. while save_game.get_position() < save_game.get_length():
  184. var json_string = save_game.get_line()
  185. # Creates the helper class to interact with JSON
  186. var json = JSON.new()
  187. # Check if there is any error while parsing the JSON string, skip in case of failure
  188. var parse_result = json.parse(json_string)
  189. if not parse_result == OK:
  190. print("JSON Parse Error: ", json.get_error_message(), " in ", json_string, " at line ", json.get_error_line())
  191. continue
  192. # Get the data from the JSON object
  193. var node_data = json.get_data()
  194. # Firstly, we need to create the object and add it to the tree and set its position.
  195. var new_object = load(node_data["filename"]).instantiate()
  196. get_node(node_data["parent"]).add_child(new_object)
  197. new_object.position = Vector2(node_data["pos_x"], node_data["pos_y"])
  198. # Now we set the remaining variables.
  199. for i in node_data.keys():
  200. if i == "filename" or i == "parent" or i == "pos_x" or i == "pos_y":
  201. continue
  202. new_object.set(i, node_data[i])
  203. .. code-tab:: csharp
  204. // Note: This can be called from anywhere inside the tree. This function is
  205. // path independent.
  206. public void LoadGame()
  207. {
  208. if (!FileAccess.FileExists("user://savegame.save"))
  209. {
  210. return; // Error! We don't have a save to load.
  211. }
  212. // We need to revert the game state so we're not cloning objects during loading.
  213. // This will vary wildly depending on the needs of a project, so take care with
  214. // this step.
  215. // For our example, we will accomplish this by deleting saveable objects.
  216. var saveNodes = GetTree().GetNodesInGroup("Persist");
  217. foreach (Node saveNode in saveNodes)
  218. {
  219. saveNode.QueueFree();
  220. }
  221. // Load the file line by line and process that dictionary to restore the object
  222. // it represents.
  223. using var saveGame = FileAccess.Open("user://savegame.save", FileAccess.ModeFlags.Read);
  224. while (saveGame.GetPosition() < saveGame.GetLength())
  225. {
  226. var jsonString = saveGame.GetLine();
  227. // Creates the helper class to interact with JSON
  228. var json = new Json();
  229. var parseResult = json.Parse(jsonString);
  230. if (parseResult != Error.Ok)
  231. {
  232. GD.Print($"JSON Parse Error: {json.GetErrorMessage()} in {jsonString} at line {json.GetErrorLine()}");
  233. continue;
  234. }
  235. // Get the data from the JSON object
  236. var nodeData = new Godot.Collections.Dictionary<string, Variant>((Godot.Collections.Dictionary)json.Data);
  237. // Firstly, we need to create the object and add it to the tree and set its position.
  238. var newObjectScene = GD.Load<PackedScene>(nodeData["Filename"].ToString());
  239. var newObject = newObjectScene.Instantiate<Node>();
  240. GetNode(nodeData["Parent"].ToString()).AddChild(newObject);
  241. newObject.Set(Node2D.PropertyName.Position, new Vector2((float)nodeData["PosX"], (float)nodeData["PosY"]));
  242. // Now we set the remaining variables.
  243. foreach (var (key, value) in nodeData)
  244. {
  245. if (key == "Filename" || key == "Parent" || key == "PosX" || key == "PosY")
  246. {
  247. continue;
  248. }
  249. newObject.Set(key, value);
  250. }
  251. }
  252. }
  253. Now we can save and load an arbitrary number of objects laid out
  254. almost anywhere across the scene tree! Each object can store different
  255. data depending on what it needs to save.
  256. Some notes
  257. ----------
  258. We have glossed over setting up the game state for loading. It's ultimately up
  259. to the project creator where much of this logic goes.
  260. This is often complicated and will need to be heavily
  261. customized based on the needs of the individual project.
  262. Additionally, our implementation assumes no Persist objects are children of other
  263. Persist objects. Otherwise, invalid paths would be created. To
  264. accommodate nested Persist objects, consider saving objects in stages.
  265. Load parent objects first so they are available for the :ref:`add_child()
  266. <class_node_method_add_child>`
  267. call when child objects are loaded. You will also need a way to link
  268. children to parents as the :ref:`NodePath
  269. <class_nodepath>` will likely be invalid.
  270. JSON vs binary serialization
  271. ----------------------------
  272. For simple game state, JSON may work and it generates human-readable files that are easy to debug.
  273. But JSON has many limitations. If you need to store more complex game state or
  274. a lot of it, :ref:`binary serialization<doc_binary_serialization_api>`
  275. may be a better approach.
  276. JSON limitations
  277. ~~~~~~~~~~~~~~~~
  278. Here are some important gotchas to know about when using JSON.
  279. * **Filesize:**
  280. JSON stores data in text format, which is much larger than binary formats.
  281. * **Data types:**
  282. JSON only offers a limited set of data types. If you have data types
  283. that JSON doesn't have, you will need to translate your data to and
  284. from types that JSON can handle. For example, some important types that JSON
  285. can't parse are: ``Vector2``, ``Vector3``, ``Color``, ``Rect2``, and ``Quaternion``.
  286. * **Custom logic needed for encoding/decoding:**
  287. If you have any custom classes that you want to store with JSON, you will
  288. need to write your own logic for encoding and decoding those classes.
  289. Binary serialization
  290. ~~~~~~~~~~~~~~~~~~~~
  291. :ref:`Binary serialization<doc_binary_serialization_api>` is an alternative
  292. approach for storing game state, and you can use it with the functions
  293. ``get_var`` and ``store_var`` of :ref:`class_FileAccess`.
  294. * Binary serialization should produce smaller files than JSON.
  295. * Binary serialization can handle most common data types.
  296. * Binary serialization requires less custom logic for encoding and decoding
  297. custom classes.
  298. Note that not all properties are included. Only properties that are configured
  299. with the :ref:`PROPERTY_USAGE_STORAGE<class_@GlobalScope_constant_PROPERTY_USAGE_STORAGE>`
  300. flag set will be serialized. You can add a new usage flag to a property by overriding the
  301. :ref:`_get_property_list<class_Object_method__get_property_list>`
  302. method in your class. You can also check how property usage is configured by
  303. calling ``Object._get_property_list``.
  304. See :ref:`PropertyUsageFlags<enum_@GlobalScope_PropertyUsageFlags>` for the
  305. possible usage flags.