Java Reference
In-Depth Information
the location. If the mine has not been cleared, we enter the outer else block. I say, “outer,” because it
contains other else blocks (after if blocks, of course). Because the location has not been cleared, we
have to make sure the mine and suspect icons are properly set. Finally, if the player has removed (or
never set) the mine and suspect icons on this location, we have to make sure no icon is present. That's
why we set the location's icon to null in that last line (not counting the lines with the closing braces).
In essence, the updateLabels method manages the appearance of the minefield, setting the colors
and icons for all the locations. There's a good design tip in there for you: Always make sure each method
has a single, well-defined task. If a method has to do several things, break it up into several methods and
have one method do nothing but (or at least not much more than) call the others. We see an example of
this kind of method when we get to the newGame method.
Next up, we get to the showAll method, shown in Listing 7-24.
Listing 7-24. The MineSweeperHelper showAll method
void showAll() {
for (int i = 0; i < mineSweeper.rows; i++) {
for (int j = 0; j < mineSweeper.columns; j++) {
boolean mine = mineSweeper.mineField.isMine(i, j);
if (mine) {
mineSweeper.mineButtons[i][j].setIcon(MineIcon.getMineIcon());
} else {
JButton thisButton = mineSweeper.mineButtons[i][j];
thisButton.removeMouseListener(mineSweeper.mouseListener);
thisButton.setBackground(Color.WHITE);
thisButton.setIcon(null);
int count = mineSweeper.mineField.countAdjacentMines(i, j);
if (count > 0) {
thisButton.setIcon(MineIcon.getNumberIcon(count));
}
}
}
}
}
The showAll method .has the simple task of revealing everything and removing the mouse listener
from all the locations. It gets called only when the game ends, whether the player won or lost. Why show
everything if the player won? The player might not have set mine icons on all of the locations that have
mines and might even have won in spite of being wrong. We want a complete representation of the true
state of the game at the end, so we clear and set the proper number icons (including no icon) for all the
locations that don't have mines and set the mine icon for all the locations that do have mines. If the
player won, doing so confirms the player's accuracy. If the player lost, showing the true state of the game
reveals mistakes, possibly letting the player learn to better play the game.
Notice that there's no instance of the MineIcon class, but we can get icons out of it anyway. We see
how that works when we get to the MineIcon class. For now, let's move on to the endGame method.
Listing 7-25 shows the endGame method.
Search WWH ::




Custom Search