saving_games.rst 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157
  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 savenodes = get_tree().get_nodes_in_group("Persist")
  25. for i in savenodes:
  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:`Dictionary.to_json()
  33. <class_Dictionary_to_json>` and :ref:`Dictionary.parse_json()
  34. <class_Dictionary_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 savedict = {
  40. filename=get_filename(),
  41. parent=get_parent().get_path(),
  42. posx=get_pos().x, #Vector2 is not supported by json
  43. posy=get_pos().y,
  44. attack=attack,
  45. defense=defense,
  46. currenthealth=currenthealth,
  47. maxhealth=maxhealth,
  48. damage=damage,
  49. regen=regen,
  50. experience=experience,
  51. TNL=TNL,
  52. level=level,
  53. AttackGrowth=AttackGrowth,
  54. DefenseGrowth=DefenseGrowth,
  55. HealthGrowth=HealthGrowth,
  56. isalive=isalive,
  57. last_attack=last_attack
  58. }
  59. return savedict
  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 savegame = File.new()
  76. savegame.open("user://savegame.save", File.WRITE)
  77. var savenodes = get_tree().get_nodes_in_group("Persist")
  78. for i in savenodes:
  79. var nodedata = i.save()
  80. savegame.store_line(nodedata.to_json())
  81. savegame.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 savegame = File.new()
  91. if !savegame.file_exists("user://savegame.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 savenodes = get_tree().get_nodes_in_group("Persist")
  96. for i in savenodes:
  97. i.queue_free()
  98. # Load the file line by line and process that dictionary to restore the object it represents
  99. var currentline = {} # dict.parse_json() requires a declared dict.
  100. savegame.open("user://savegame.save", File.READ)
  101. currentline.parse_json(savegame.get_line())
  102. while (!savegame.eof_reached()):
  103. # First we need to create the object and add it to the tree and set its position.
  104. var newobject = load(currentline["filename"]).instance()
  105. get_node(currentline["parent"]).add_child(newobject)
  106. newobject.set_pos(Vector2(currentline["posx"],currentline["posy"]))
  107. # Now we set the remaining variables.
  108. for i in currentline.keys():
  109. if (i == "filename" or i == "parent" or i == "posx" or i == "posy"):
  110. continue
  111. newobject.set(i, currentline[i])
  112. currentline.parse_json(savegame.get_line())
  113. savegame.close()
  114. And now we can save and load an arbitrary number of objects laid out
  115. almost anywhere across the scene tree! Each object can store different
  116. data depending on what it needs to save.
  117. Some notes
  118. ----------
  119. We may have glossed over a step, but setting the game state to one fit
  120. to start loading data can be very complicated. This step will need to be
  121. heavily customized based on the needs of an individual project.
  122. This implementation assumes no Persist objects are children of other
  123. Persist objects. Doing so would create invalid paths. If this is one of
  124. the needs of a project this needs to be considered. Saving objects in
  125. stages (parent objects first) so they are available when child objects
  126. are loaded will make sure they're available for the add_child() call.
  127. There will also need to be some way to link children to parents as the
  128. nodepath will likely be invalid.