The Ball Sprite

I begin with a textual specification of what a ball sprite should do, then I will translate this into a statechart, and then manually convert it into BallSprite, a subclass of Sprite.

Textual Specification

In the following discussion, I'll refer to the ant sprite as the bat, since that's its function: the ant is used to knock away balls, preventing them from reaching the floor.

The ball drops from the top of the panel at varying speeds and angles of trajectory. It'll bounce off a wall if it hits one, reversing its x-axis direction. If the ball hits the bat, it will rebound and disappear off the top of the panel. If the ball passes the bat, it will disappear through the panel's base.

Tip

Remember, bat refers to the ant—which could be drawn as anything, but always functions as a bat.

After leaving the panel, the ball is reused: it's placed back at the top of the panel and put into motion again. The image associated with the ball is changed.

The number of returned balls is incremented when the ball bounces off the bat (numRebounds is incremented). When the ball drops off the bottom, numRebounds is decremented. If numRebounds reaches MAX_BALLS_RETURNED, the game is over. If numRebounds reaches 0, the game also terminates.

Sound effects are played when the ball hits the walls and the bat.

Statechart Specification

The statechart in Figure 11-5 specifies the actions of the ball sprite.

Figure 11-5. The BallSprite statechart

The statechart uses an update superstate, which is a state ...

Get Killer Game Programming in Java 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.