Learning Java by Building Android  Games
上QQ阅读APP看书,第一时间看更新

Declaring the variables

In Android Studio add the following highlighted variable declarations.

Note

The complete code as it stands at the end of this chapter can be found in the download bundle in the Chapter 3 folder.

Notice they are declared inside the SubHunter class declaration and before the onCreate method declaration.

public class SubHunter extends Activity {

 // These variables can be "seen"
 // throughout the SubHunter class
 int numberHorizontalPixels;
 int numberVerticalPixels;
 int blockSize;
 int gridWidth = 40;
 int gridHeight;
 float horizontalTouched = -100;
 float verticalTouched = -100;
 int subHorizontalPosition;
 int subVerticalPosition;
 boolean hit = false;
 int shotsTaken;
 int distanceFromSub;
 boolean debugging = true;

/*
   Android runs this code just before
   the app is seen by the player.
   This makes it a good place to add
   the code that is needed for
   the one-time setup.
*/

Notice in the previous code that we declare the variables as we have learned to do earlier in the chapter and that we also initialize a few of them too.

Most of the variables will be initialized later in the code but you can see that gridWidth has been initialized with the value 40. This is a fairly arbitrary number and once Sub' Hunter is complete you can play around with this value. However, giving gridWidth a value works as a kind of starting point when working out the grid size and, of course, the gridHeight value. We will see exactly how we do these calculations soon.

We also initialized the horizontalTouched and verticalTouched variables to -100. This again is arbitrary; the point is that the screen has not been touched yet so having far out values like this makes it plain.