Starting a New Game

If you've played any Sudoku games, you know that some are easy and some are maddeningly hard. So when the user selects New Game, we want to pop up a dialog box asking them to select between three difficulty levels. Selecting from a list of things is easy to do in Android.

Sudoku settings



Play background music



Show hints during play


Figure 3.11: It's not much to look at, but we got it for free.

First we'll need a few more strings in res/values/strings.xml:

Download Sudokuv1/res/values/strings.xml

<string name="new_game_title">Difficulty</string> <string name="easy_label">Easy</string> <string name="medium_label">Medium</string> <string name="hard_label">Hard</string>

Create the list of difficulties as an array resource in res/values/arrays.xml:

Download Sudokuv1/res/values/arrays.xml

<?xml version="1.0" encoding="utf-8"?> <resources>

<array name="difficulty">

<item>@string/easy_label</item> <item>@string/medium_label</item> <item>@string/hard_label</item> </array> </resources>

Figure 3.12: Difficulty selection dialog box

We'll need a few more imports in the Sudoku class:

Download Sudokuv1/src/org/example/sudoku/

import; import android.content.DialogInterface; import android.util.Log;

Add code in the switch statement of the onClick() method to handle clicking the New Game button:

Download Sudokuv1/src/org/example/sudoku/

case openNewGameDialog(); break;

The openNewGameDialog() method takes care of creating the user interface for the difficulty list.

Download Sudokuv1/src/org/example/sudoku/ private static final String TAG = "'Sudoku";

private void openNewGameDialog() { new AlertDialog.Builder(this)

. setTitle(R.string.new_game_title)

.setItems(R.array.difficulty, new DialogInterface.OnClickListenerO {

public void onClick(DialogInterface dialoginterface, int i) { startGame(i);

private void startGame(int i) { Log.d(TAG, "'clicked on " + i); // Start game here...

The setltems() method takes two parameters: the resource ID of the item list and a listener that will be called when one of the items is selected.

When you run the program now and press New Game, you'll get the dialog box in Figure 3.12, on the previous page.

We're not actually going to start the game yet, so instead when you select a difficulty level, we just print a debug message using the Log.d() method, passing it a tag string and a message to print.

0 0

Post a comment