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

Preparing to draw

Add the declaration of all the graphics related reference variables we will need. The new code is highlighted amongst the previous code.

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;

 // Here are all the objects(instances)
 // of classes that we need to do some drawing
 ImageView gameView;
 Bitmap blankBitmap;
 Canvas canvas;
 Paint paint;


    /*
        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.
     */

We have just declared one of each of the required reference variables for each object just as we did in the Canvas demo. We have named the objects slightly differently so be sure to read the code and identify the names of the different objects.

Now we can add some more code to onCreate to initialize our Canvas and other drawing objects.