The Settings Class

As with the Assets class we can again reuse what we have written for the previous games to some extent. We now store an additional boolean that tells us whether the user wants to use the touchscreen or the accelerometer for moving the ship. We also drop the high-score support, as we don't keep track of those. As an exercise you can of course reintroduce both the high-score screen and the saving of those scores to the SD card. Listing 12-2 shows you the code.

Listing 12-2., Same Old, Same Old package com.badlogic.androidgames.droidinvaders;

import; import; import; import; import;

import com.badlogic.androidgames.framework.FileIO;

public class Settings {

public static boolean soundEnabled = true; public static boolean touchEnabled = true; public final static String file = ".droidinvaders";

We store whether sounds are enabled as well as whether the user wants to use touch input to navigate the ship or not. The settings will be stored in the file .droidinvaders on the SD card.

public static void load(FileIO files) { BufferedReader in = null; try {

in = new BufferedReader(new InputStreamReader(files.readFile(file))); soundEnabled = Boolean.parseBoolean(in.readLine()); touchEnabled = Boolean.parseBoolean(in.readLine());

// :( It's ok we have defaults } catch (NumberFormatException e) {

// :/ It's ok, defaults save our day } finally { try {

There is nothing in this section we need to go into really; we've done this before. We try to read the two booleans from the file on the SD card. If that fails, we fall back to the default values.

public static void save(FileIO files) { BufferedWriter out = null; try {

out = new BufferedWriter(new OutputStreamWriter(

files.writeFile(file))); out.write(Boolean.toString(soundEnabled)); out.write("\n");

out.write(Boolean.toString(touchEnabled)); } catch (IOException e) { } finally { try {

Saving is again very boring. We just store whatever we have and if that fails ignore the error silently. This is another good place for improvement, as you'll probably want to let the user know that something went wrong.

0 0

Post a comment