Game Development Reference
In-Depth Information
public static void save(FileIO files) {
BufferedWriter out = null ;
try {
out = new BufferedWriter( new OutputStreamWriter(
files.writeFile(".mrnom")));
out.write(Boolean. toString ( soundEnabled ));
for ( int i = 0; i < 5; i++) {
out.write(Integer. toString ( highscores [i]));
}
} catch (IOException e) {
} finally {
try {
if (out != null )
out.close();
} catch (IOException e) {
}
}
}
Next up is a method called save() . It takes the current settings and serializes them to the .mrnom
file on the external storage (that is, /sdcard/.mrnom ). The sound setting and each high-score
entry is stored as a separate line in that file, as expected by the load() method. If something
goes wrong, we just ignore the failure and use the default values defined earlier. In an AAA title,
you might want to inform the user about this loading error.
It is worth noting that, in Android API 8, more specific methods were added for dealing with
managed external storage. The method Context.getExternalFilesDir() was added, which
provides a specific spot in the external storage that doesn't pollute the root directory of the SD
card or internal flash memory, and it also gets cleaned up when the application is uninstalled.
Adding support for this, of course, means that you have to either load a class dynamically for
API 8 and up or set your minimum SDK to 8 and lose backward compatibility. Mr. Nom will use
the old API 1 external storage spot for simplicity's sake, but should you need an example of how
to load a class dynamically, look no further than our TouchHandler code from chapter 5.
public static void addScore( int score) {
for ( int i = 0; i < 5; i++) {
if ( highscores if < score) {
for ( int j = 4; j > i; j--)
highscores [j] = highscores [j - 1];
highscores [i] = score;
break ;
}
}
}
}
The final method, addScore() , is a convenience method. We will use it to add a new score to the
high scores, automatically re-sorting them depending on the value we want to insert.
Search WWH ::




Custom Search