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

Structuring Sub' Hunter with methods

As we add the method definitions to the code it shouldn't come as much surprise where each of the methods will go. The draw method will go after the comment about … do all the drawing… and so on.

Add the newGame method definition after the appropriate comment as shown next.

/*
   This code will execute when a new
   game needs to be started. It will
   happen when the app is first started
   and after the player wins a game.
 */
void newGame(){

}

Add the draw method definition after the appropriate comment as highlighted.

/*
   Here we will do all the drawing.
   The grid lines, the HUD,
   the touch indicator and the
   "BOOM" when a sub' is hit
*/
void draw() {

}

Add the onTouchEvent definition after this comment.

/*
   This part of the code will
   handle detecting that the player
   has tapped the screen
 */
@Override
public boolean onTouchEvent(MotionEvent motionEvent) {

}

You have probably noticed that the onTouchEvent method is another overridden method. Android provides this method for our benefit and when the player touches the screen it will call this method. All we need to do is work out how to handle a touch when the onTouchEvent method gets called. There is also an error in this code we will resolve this when we get introduced to object-oriented programming in a minute.

Add the takeShot definition after the comment shown next.

/*
   The code here will execute when
   the player taps the screen It will
   calculate the distance from the sub'
   and determine a hit or miss
 */
void takeShot(){

}

Add the boom method definition after // This code says "BOOM!".

// This code says "BOOM!"
void boom(){

}

Add the printDebuggingText definition after the comment about debugging text.

// This code prints the debugging text
void printDebuggingText(){

}

As the project progresses we will add code into each of the method definitions because at the moment they don't do anything. Furthermore, as we learn more about methods the postfix and prefix to the method names will also evolve as well as become more understandable.

Very closely related to methods and part of what we need to know to understand them better is Object-Oriented Programming.