saving_your_game.rst 6.1 KB

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