Game Development Reference
In-Depth Information
super.onRestart();
((ArcadeGame) view).resume();
}
}
The class keeps a reference to the layout (using the
view
class variable). This variable is used to halt
the game when the user exists or restart it, as shown in the
onStop
and
onRestart
methods. To manually
load the user-defined layout, we use the
LayoutInfalter
class:
LayoutInflater factory = LayoutInflater.from(this);
// Set game layout
view = factory.inflate(R.layout.main, null);
setContentView(view);
Two important lines are used to cascade key and touch events to the inner layout:
view.setFocusable(true);
view.setFocusableInTouchMode(true);
setFocusable
tells the view (the user-defined layout) that it can receive focus and thus events in key
or touch modes. These two lines are critical; if they are commented out, the game will not receive events.
Creating the Game Layout
As mentioned before, the class
SpaceBlasterGame
extends
ArcadeGame
, which in turn extends the Android
layout
LinearLayout
. In this way, we can define a game thread to update the state of the game and simply
draw sprites in the
onDraw
method of
LinearLayout
, thus gaining a finer control over the drawing process.
SpaceBlasterGame
performs the drawing, and it has all the game logic. This class is relatively complex
compared to the others, but before we take a look at it, let's see how the game thread is handled by
ArcadeGame
.
ArcadeGame
is the abstract base class for
SpaceBlasterGame
, and it deals with the game loop. This
loop is infinite and invalidates the view to force a redraw of the display (see Listing 3-3).
Listing 3-3.
Abstract Class ArcadeGame
package ch03.game.sb;
import java.util.Timer;
import java.util.TimerTask;
import ch03.common.AudioClip;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.widget.LinearLayout;
/**