Java Reference
In-Depth Information
// game over? (part of step 2 in a game loop)
// the rest of step 2 (processing the game logic)
// is in the TargetClickPanel and Target classes
if (score == gameLength) {
endGame();
}
// redraw the playing field (step 3 in a game loop)
targetClickPanel.repaint();
}
// A convenience method for showing the time and score
private void updateScorePanel() {
elapsedTime = System.currentTimeMillis() - startTime;
timeDisplayLabel.setText(Long.toString(elapsedTime / 1000));
scoreDisplayLabel.setText(Integer.toString(score));
}
// What to do when the game ends - part of the game logic
private void endGame() {
timer.stop();
String scoreString = "You clicked " + gameLength +
" targets in " + (elapsedTime / 1000) + " seconds";
int option;
option = JOptionPane.showConfirmDialog(frame, scoreString
+ " Play again?", "Game Over",
JOptionPane.YES_NO_OPTION);
if (option == 1) {
System.exit(0);
} else {
newGame();
}
}
// What to do when the user starts a new game
private void newGame() {
score = 0;
scoreDisplayLabel.setText("0");
startTime = System.currentTimeMillis();
timeDisplayLabel.setText("0");
if (!timer.isRunning()) {
timer.start();
}
}
}
Nearly all of the TargetClick class creates and manages the user interface. The actionPerformed
method contains part of the game logic (with the rest in the TargetClickPanel and Target classes, which
we'll soon see). The endGame and startGame methods show those places where user interface code
meshes with game logic. The endGame method has just enough logic to stop the timer. The rest of the
endGame method provides the user with a way to either start a new game or exit. The newGame method
resets everything (including the user interface) and starts a new game.
Search WWH ::




Custom Search