Using the apple

The Apple class is done, and we can now put it to work in SnakeEngine.

Add the code to initialize the apple object in the constructor at the end as shown.

// Call the constructors of our two game objects
mApple = new Apple(context,
   new Point(NUM_BLOCKS_WIDE,
               mNumBlocksHigh),
               blockSize);

Notice we pass in all the data required by the Apple constructor so it can set itself up.

We can now spawn an apple as shown next in the newGame method by calling the spawn method that we added when we coded the Apple class previously. Add the highlighted code to the newGame method.

// Called to start a new game
public void newGame() {

   // reset the snake


   // Get the apple ready for dinner
   mApple.spawn(); // Reset the mScore mScore = 0; // Setup mNextFrameTime ...

Get Learning Java by Building Android Games - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.