Java Reference
In-Depth Information
the game is over (because the player won or lost) or the game should continue. If the user clicked any
other button (most likely the right button), this method still calls the resolveClick method, but with the
button flag indicating that a button other than the left button was clicked. The resolveClick method
then toggles the mine, suspect, and unknown icons on that location. Finally, the mouseClicked method
uses the value returned by the resolveClick method to end the game (the player won or lost) or
continue the game. If the game didn't end, we update the buttons in the minefield. Finally, once all the
other processing has been done, the mouseClicked method updates the labels.
The MineSweeperMouseListener class isn't complex, but it is worth moving this functionality into its
own class, to simplify the MineSweeper class. It also follows the design principle that each object should
have a clear purpose. In this case, we create a class with the clear mission of listening for clicks in the
minefield, and removing that functionality (and moving other bits to other classes) lets the MineSweeper
focus purely on showing the user interface.
Let's finish up this long journey through the MineSweeper game by looking at the last class in the
MineSweeper package. Listing 7-29 shows the MineSweeperActionListener class.
Listing 7-29. The MineSweeperActionListener class
package com.apress.java7forabsolutebeginners.examples.MineSweeper;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class MineSweeperActionListener implements ActionListener {
private MineSweeper mineSweeper;
private MineSweeperHelper mineSweeperHelper;
public MineSweeperActionListener(MineSweeper mineSweeper, MineSweeperHelper helper) {
this.mineSweeper = mineSweeper;
mineSweeperHelper = helper;
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getActionCommand().equals("Exit")) {
System.exit(0);
}
if (e.getActionCommand().equals("New Game")) {
mineSweeperHelper.newGame(mineSweeper.rows, mineSweeper.columns);
return;
}
if (e.getActionCommand().equals("Small (8 x 8, 10 mines)")) {
int previousRows = mineSweeper.rows;
int previousColumns = mineSweeper.columns;
mineSweeper.rows = 8;
mineSweeper.columns = 8;
mineSweeper.numberOfMines = 10;
mineSweeperHelper.newGame(previousRows, previousColumns);
return;
}
Search WWH ::




Custom Search