Game Development Reference
In-Depth Information
public ArcadeGame(Context context) {
super(context);
mContex = context;
}
public ArcadeGame(Context context, AttributeSet attrs) {
super(context, attrs);
mContex = context;
}
Note that
ArcadeGame
extends
LinearLayout
and sends its arguments to the parent via
super(context)
and
super(context, attrs)
. This class also overloads the parent's method
onLayout()
,
which fires when the view should assign a size and position to each of its children:
/**
* Fires on layout
*/
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
try {
// Init game
initialize();
/**
* start update task. Which will fire onDraw in the future
*/
startUpdateTimer();
} catch (Exception e) {
// bug
e.printStackTrace();
}
}
onLayout
is in charge of initializing the game and starting the update timer. Note that
initialize()
is an abstract method that must be overloaded by the child class (
SpaceBlasterGame
) to perform
initialization. The update timer, on the other hand, will be defined within
AbstractGame
. To define a
game loop, we can use a simple
TimerTask
that will update itself using a period, as shown in Listing 3-4.
Listing 3-4.
Defining a Game Loop Using a Timer Task
// Timer period
private long mPeriod = 1000;
/**
* Canvas update task
*
* @author vsilva
*
*/
private class UpdateTask extends TimerTask {
@Override