Game Development Reference
In-Depth Information
Listing 6-3. Settings.java; Stores Our Settings and Loads/Saves Them
package
com.badlogic.androidgames.mrnom;
import
java.io.BufferedReader;
import
java.io.BufferedWriter;
import
java.io.IOException;
import
java.io.InputStreamReader;
import
java.io.OutputStreamWriter;
import
com.badlogic.androidgames.framework.FileIO;
public class
Settings {
public static boolean
soundEnabled
=
true
;
public static int
[]
highscores[i]
=
new int
[] { 100, 80, 50, 30, 10 };
Whether sound effects are played back is determined by a public static Boolean called
soundEnabled
. The high scores are stored in a five-element integer array, sorted from highest to
lowest. We define sensible defaults for both settings. We can access these two members the
same way we accessed the members of the
Assets
class.
public static void
load(FileIO files) {
BufferedReader in =
null
;
try
{
in =
new
BufferedReader(
new
InputStreamReader(
files.readFile(".mrnom")));
soundEnabled
= Boolean.
parseBoolean
(in.readLine());
for
(
int
i = 0; i < 5; i++) {
highscores[i]
[i] = Integer.
parseInt
(in.readLine());
}
}
catch
(IOException e) {
// :( It's ok we have defaults
}
catch
(NumberFormatException e) {
// :/ It's ok, defaults save our day
}
finally
{
try
{
if
(in !=
null
)
in.close();
}
catch
(IOException e) {
}
}
}
The static
load()
method tries to load the settings from a file called
.mrnom
from the external
storage. It needs a
FileIO
instance for that, which we pass to the method. It assumes that the
sound setting and each high-score entry is stored on a separate line and simply reads them in. If
anything goes wrong (for example, if the external storage is not available or there is no settings
file yet), we simply fall back to our defaults and ignore the failure.