0
\$\begingroup\$

My game uses lots of complex objects to store game data. (Each block and entity has its own instance of a class)

I am trying to create a saving and loading system, where the user can save game progress to a text file.

But a simple JSON.stringify won't cut it. These objects are very complex and nested, with instances of different classes contained within. (For example, one instance of the Block class may contain multiple instances of the Text class)

I need a way to boil all this meta data down into text. I've tried multiple libraries, but those don't work with my custom classes.

Any advice on this would be super appreciated!

EDIT: An attempt at writing my own method for doing this

function superString(obj) {
let result = "";
for(var property in obj) {
if(Array.isArray(property)) {
  result += superString(property)
}
else if(property instanceof Block) {
  console.log("EXPORTING BLOCK")
  result += property.exportString();
}
else if(property instanceof Entity) {
  result += property.exportString();
}
else if(typeof property === 'object' && property !== null) {
  result += superString(property)
}

else result += JSON.stringify(property)
}return result;
}
\$\endgroup\$
3
  • 2
    \$\begingroup\$ Keep in mind that the data you need to write to disc to save the game state, or read from disc to restore the game state, is not necessarily the same data you need in memory to use the game state. For example, if you have a block that serves as a sign that has a text rendering object in it, you don't need to save the whole block instance and the whole text rendering instance: your game code already knows sign blocks have both those things. The only novel information is blockType = "Sign" and signText = "some text string" - your loading method can build the rest and populate the variables \$\endgroup\$ Commented Aug 29, 2020 at 15:25
  • \$\begingroup\$ @DMGregory Good point. But sometimes I have blocks which contain blocks. Maybe I could recursively export/import them somehow? By traveling through each tree recursively? \$\endgroup\$ Commented Aug 29, 2020 at 21:53
  • \$\begingroup\$ How does the behaviour of your code so far differ from what you need? The more explicitly you can define the problem, the more useful answers you'll tend to get, faster. \$\endgroup\$ Commented Aug 29, 2020 at 22:56

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.