Java Reference
In-Depth Information
displayed and the game is stopped. If he or she chooses to do so, the player can restart the
game from the menu.
Compile and run the code. See if you can win!
11.8 Summary
The chapter presented the case study of creating a full working game. Many Java features
were reviewed: creating subclasses, drawing shapes, different kinds of if and for statements,
enum types, inheritance, event handling, and so on. Most importantly, the chapter demon-
strated how to create the design and implement a non-trivial program. Here is a summary
of the most important principles that were followed.
1. Delegation
Delegate responsibilities to classes and methods. For example, the
Ball class should be responsible for the movement of the ball.
2. Avoid long methods
Every methods is simple and performs just one task. If a
method becomes long, then it is broken down into several methods. For example, the
BreakoutPanel constructor calls the createBricks method to create the bricks.
3. Limit interaction between classes
All data is declared private . Methods
that should be not be accessed outside the class are also declared private . For exam-
ple, the new constructors in the Ball and Brick class were defined private.
4. Test often
Do not write the whole program in one breath. Create a simple feature,
test it, and make sure it works before proceeding to the next feature.
11.9 Syntax
￿
t.setDelay(20);
Changes the delay of the timer t to 20 milliseconds.
￿
startGameMI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK S,
InputEvent.CTRL MASK));
When Ctrl+S is pressed, an ActionEvent will be gen-
erated by the menu item startGameMI .
￿ shape.setFrame(getX() + dx, getY() + dy, getWidth(), getHeight());
Change the surrounding frame of the shape object of type RectangularShape .
￿ shape.getBounds()
Returns the bounds of a shape as an object of type Rectangle .
￿ String s = KeyEvent.getKeyText(e.getKeyCode());
Computes a textual de-
scription of the key that is pressed. For example, the value of s can be “F1”, “Space”,
“Esc”, etc.
￿ Rectangle r3 = r1.add(r2);
Code that adds two rectangles. The result is the
smallest rectangle that encompasses rectangles r1 and r2 .
 
Search WWH ::




Custom Search