Saving
When a game ends, its variables are gone. To keep a high score, a level or the player's settings for next time, save them.
What to save: a data class
Put everything you want to keep into a class of its own, with public fields:
public class Progress {
public int level = 1;
public int highScore = 0;
}
The values after = are what a new player starts with.
Saving and loading
SaveData saves one such object for your game. Collect coins with the arrow
keys, then press ▶ again: the high score is still there.
new SaveData<>("org.example.coins", "main", Progress.class):-
"org.example.coins"is an ID for your game. Choose it once and never change it, or the old saves are lost. Use your own name or school in it. "main"is the slot. Use"slot1","slot2", … for several save games.Progress.classis the class of what is saved.
-
-
loadOrDefault(() -> new Progress())loads the save, or makes a newProgresswhen there is none yet. -
save(progress)writes it. Save at moments that matter, like a new high score or the end of a level, not in every frame.
When saving fails
A disk can be full, or a file broken. That is why Java wants try and catch
around loadOrDefault and save: the code in catch runs only when it went
wrong. On your own computer, add import java.io.IOException; at the top of the
file.
Where the saves are
- In the browser: in the browser's storage, on this computer only. Clearing the browser data deletes them.
- On a computer: in the user's data folder, not in the project. The save stays when the game is updated or moved.
Settings like volume or full screen are saved the same way, in a class of their
own and a slot like "settings". Chosen keys have their own method, see
Players choose their keys.
Reading your own data files
File.load reads a JSON file of your project into an object, for example a
list of levels or questions:
Quiz quiz = File.load("assets/quiz.json", Quiz.class);
File.save("results.json", quiz) writes one. Use it for files you make
yourself. For a player's progress, use SaveData.
Next
- Save slots example: three save games and a menu to choose one
- SaveData and File in the reference