SAVE/LOAD: How to Save Load data?

Hi guyz, how do I save my game data - gold, score, points, powerups?
anyone got a comprehensive tutorial?

im using:
cocos2d-x v2.2.5
im coding in Xcode but plan to release for Android first, so I’m using Eclipse

You can using CCUserDefault.
http://www.cocos2d-x.org/reference/native-cpp/V2.2/d0/d79/classcocos2d_1_1_c_c_user_default.html

Hope this help!

1 Like

hey thanks appreciate it, will review this now :slight_smile:

On Android using CCUserDefault works, but the sqlite DB will be erased when the app
get’s an update using Cocos2d-x 3.3

UserDefaults is useful, and it might be enough for you, but if you’re doing anything moderately complex, it might be better to do something like the following. The way I created save data is fairly straight forward and platform independent.

  1. Use ofstream to create a file in a writable path. With cocos2d-x you can do something like the following to get a file path:

    string savePath = FileUtils::getInstance()->getWritablePath() + “savedata.tpk”;

  2. Create a SaveDataHeader struct or class, which contains non-dynamic members and is in itself a fixed size. Having SCORE, GOLD, LEVEL numbers in the header can work because they are probably just 3 different integers. This SaveDataHeader object will be the first thing you write to the save file.

  3. For the dynamic save data elements (inventory items, power ups etc), I stored how many of each the player has in the SaveDataHeader. Then I loop through the items/powerups and write out an ID or code, or anything you can read back and recreate the item in the player’s inventory during the LOAD. This happens in a loop using the write() method on the ofstream object.

  4. flush() and close() the file and thats it!

  5. For the LOAD operation, read the SaveDataHeader into a blank object and then use loops to read back the IDs/Codes of the inventory/powerups and recreate the game state. You can use ifstream and its read() method to read data. This isn’t a direct paste from my code, but this is roughly how I do it:

    SaveDataHeader saveHeader;
    ifstream saveFile(GameDirector::getInstance().getSaveFilePath(), ios::binary);
    saveFile.read((char *)&saveHeader, sizeof(saveHeader));

Hope this helps.

@Nick_E has a good idea here. I don’t think it gets erased between 2.2.5 and 3.3 I think the getWritablePath() returns a different location? I haven’t tested that but I think I recall seeing that someplace…

As long as getWritablePath() returns a writeable path, I’m not too worried.

Just want to confirm On Updating app (not cocos2dx version) saved data is not deleted if using UserDefault ?

There is no problem. confirmed. :grinning:

1 Like

Had someone used protobuf or flatbuffers for savegames?

I used protobuf. Working as charm, I recommend! :slight_smile:
It was used in 100k+ (downloads) cocos2d-x games.

1 Like

Is the game still available?

Yeap still running fine.