Saving data
Before working on the sounds, I still have few things to do, in order to have a game fully playable :
- Saving data : For this game we'll only save the number of levels we completed, so we won't need to start the game from start every time we play.
- Create a level selection screen
Saving data
Storing and loading small data, like a level number, is very easy in libGDX with the Preferences.
Firs, let's create the Data.java :
public class Data { public static Preferences prefs; public static void Load(){ prefs = Gdx.app.getPreferences("Data"); if (!prefs.contains("Level")) { prefs.putInteger("Level", 1); } } public static void setLevel(int val) { prefs.putInteger("Level", val); prefs.flush(); //Mandatory to save the data } public static int getLevel() { return prefs.getInteger("Level"); } }
In the Load() function, we check if the field "Level" exits. If not, we create it and attribute it a default value. Then, in the game we can access to this value with the getLevel() function and we can modify its value with the setLevel() function.
Loading the data
Before accessing the data "Level", we need to load the Preference file. We'll do that in the main activity, MyGdxGame.java, simply by using this line in the create() :
Data.Load();
Accessing the data
Then, when we need to know which level we unlocked, we can access to this number with the line :
Data.getLevel();
Saving data
At the end of a level, when we want to increment the number of the level we unlocked we only need to do :
Data.setLevel(Data.getLevel()++);