Java 7 for Absolute Beginners

(nextflipdebug5) #1
CHAPTER 7 ■ WRITING A USER INTERFACE

Finally, you probably notice that the cascade method returns one of the values from the gameState
enumeration. Most of the time, that’s gameState.CONTINUE. However, it is possible for a cascade event
to clear the board and win the game, so the method can also return gameState.WIN.
The MineField class has one last non-trivial method, called countAdjacentMines. Listing 7-18 shows
the countAdjacentMines method.


Listing 7-18. The MineSweeper countAdjacentMines method


int countAdjacentMines(int x, int y) {
int count = 0;
for (int i = x - 1; i <= x + 1; i++) {
for (int j = y - 1; j <= y + 1; j++) {
if (i == x && j == y) {
continue;
} else if (i < 0 || j < 0 || i >= rows || j >= columns) {
continue;
} else if (mineField[i][j].hasMine()) {
count++;
}
}
}
return count;
}


When a player clears a location that does not contain a mine, we have to show the number of
adjacent mines in that location. To do that, we need a method of counting the mines adjacent to any
given location. As with the cascade method, we have to check for the edges of the playing field, and we
use identical code to do that. Other than that, the countAdjacentMines method checks each adjacent
(including diagonals) location and adds up the number of mines found.
The Mine class defines an individual location. You might think it's misnamed, because it doesn't
correspond only to locations that have mines. To that end, we thought about changing the name to
Location. Then it occurred to us that, when Explosive Ordnance Disposal specialists (those folks are real
heroes, by the way) check for explosives, they assume every location is mined. So, in a fit of sophistry, I
left the name as Mine. Listing 7-19 shows the Mine class.


Listing 7-19. The Mine class


package com.apress.java7forabsolutebeginners.examples.MineSweeper;


public class Mine {


enum flagState {UNKNOWN, MINE, SUSPECT};
private boolean isCleared = false;
private boolean hasMine = false;
private flagState flag = flagState.UNKNOWN;
boolean hasMine() {
return hasMine;
}

Free download pdf