saving_games.rst 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154
  1. .. _doc_saving_games:
  2. Saving games
  3. ============
  4. Introduction
  5. ------------
  6. Save games can be complicated. It can be desired to store more
  7. information than the current level or number of stars earned on a level.
  8. More advanced save games may need to store 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. Identify persistent objects
  12. ---------------------------
  13. First we should identify what objects we want to keep between game
  14. sessions and what information we want to keep from those objects. For
  15. this tutorial, we will use groups to mark and handle objects to be saved
  16. but other methods are certainly possible.
  17. We will start by adding objects we wish to save to the "Persist" group.
  18. As in the :ref:`doc_scripting_continued` tutorial, we can do this through
  19. the GUI or through script. Let's add the relevant nodes using the GUI:
  20. .. image:: img/groups.png
  21. Once this is done when we need to save the game we can get all objects
  22. to save them and then tell them all to save with this script:
  23. ::
  24. var save_nodes = get_tree().get_nodes_in_group("Persist")
  25. for i in save_nodes:
  26. # Now we can call our save function on each node.
  27. Serializing
  28. -----------
  29. The next step is to serialize the data. This makes it much easier to
  30. read and store to disk. In this case, we're assuming each member of
  31. group Persist is an instanced node and thus has a path. GDScript
  32. has helper functions for this, such as :ref:`to_json()
  33. <class_@GDScript_to_json>` and :ref:`parse_json()
  34. <class_@GDScript_parse_json>`, so we will use a dictionary. Our node needs to
  35. contain a save function that returns this data. The save function will look
  36. like this:
  37. ::
  38. func save():
  39. var save_dict = {
  40. "filename" : get_filename(),
  41. "parent" : get_parent().get_path(),
  42. "pos_x" : position.x, # Vector2 is not supported by JSON
  43. "pos_y" : position.y,
  44. "attack" : attack,
  45. "defense" : defense,
  46. "current_health" : current_health,
  47. "max_health" : max_health,
  48. "damage" : damage,
  49. "regen" : regen,
  50. "experience" : experience,
  51. "tnl" : tnl,
  52. "level" : level,
  53. "attack_growth" : attack_growth,
  54. "defense_growth" : defense_growth,
  55. "health_growth" : health_growth,
  56. "is_alive" : is_alive,
  57. "last_attack" : last_attack
  58. }
  59. return save_dict
  60. This gives us a dictionary with the style
  61. ``{ "variable_name":that_variables_value }`` which will be useful when
  62. loading.
  63. Saving and reading data
  64. -----------------------
  65. As covered in the :ref:`doc_filesystem` tutorial, we'll need to open a file
  66. and write to it and then later read from it. Now that we have a way to
  67. call our groups and get their relevant data, let's use to_json() to
  68. convert it into an easily stored string and store them in a file. Doing
  69. it this way ensures that each line is its own object so we have an easy
  70. way to pull the data out of the file as well.
  71. ::
  72. # Note: This can be called from anywhere inside the tree. This function is path independent.
  73. # Go through everything in the persist category and ask them to return a dict of relevant variables
  74. func save_game():
  75. var save_game = File.new()
  76. save_game.open("user://savegame.save", File.WRITE)
  77. var save_nodes = get_tree().get_nodes_in_group("Persist")
  78. for i in save_nodes:
  79. var node_data = i.save()
  80. save_game.store_line(to_json(node_data))
  81. save_game.close()
  82. Game saved! Loading is fairly simple as well. For that we'll read each
  83. line, use parse_json() to read it back to a dict, and then iterate over
  84. the dict to read our values. But we'll need to first create the object
  85. and we can use the filename and parent values to achieve that. Here is our
  86. load function:
  87. ::
  88. # Note: This can be called from anywhere inside the tree. This function is path independent.
  89. func load_game():
  90. var save_game = File.new()
  91. if not save_game.file_exists("user://save_game.save"):
  92. return # Error! We don't have a save to load.
  93. # We need to revert the game state so we're not cloning objects during loading. This will vary wildly depending on the needs of a project, so take care with this step.
  94. # For our example, we will accomplish this by deleting savable objects.
  95. var save_nodes = get_tree().get_nodes_in_group("Persist")
  96. for i in save_nodes:
  97. i.queue_free()
  98. # Load the file line by line and process that dictionary to restore the object it represents
  99. save_game.open("user://savegame.save", File.READ)
  100. while not save_game.eof_reached():
  101. var current_line = parse_json(save_game.get_line())
  102. # First we need to create the object and add it to the tree and set its position.
  103. var new_object = load(current_line["filename"]).instance()
  104. get_node(current_line["parent"]).add_child(new_object)
  105. new_object.position = Vector2(current_line["pos_x"], current_line["pos_y"]))
  106. # Now we set the remaining variables.
  107. for i in current_line.keys():
  108. if i == "filename" or i == "parent" or i == "pos_x" or i == "pos_y":
  109. continue
  110. new_object.set(i, current_line[i])
  111. save_game.close()
  112. And now we can save and load an arbitrary number of objects laid out
  113. almost anywhere across the scene tree! Each object can store different
  114. data depending on what it needs to save.
  115. Some notes
  116. ----------
  117. We may have glossed over a step, but setting the game state to one fit
  118. to start loading data can be very complicated. This step will need to be
  119. heavily customized based on the needs of an individual project.
  120. This implementation assumes no Persist objects are children of other
  121. Persist objects. Doing so would create invalid paths. If this is one of
  122. the needs of a project this needs to be considered. Saving objects in
  123. stages (parent objects first) so they are available when child objects
  124. are loaded will make sure they're available for the add_child() call.
  125. There will also need to be some way to link children to parents as the
  126. NodePath will likely be invalid.