Java Reference
In-Depth Information
Listing 7-14. The MineField construcor
MineField(int rows, int columns, int mines) {
this.rows = rows;
this.columns = columns;
this.mines = mines;
minesRemaining = mines;
emptiesRemaining = rows * columns - mines;
mineField = new Mine[rows][columns];
init();
populate();
}
Like most constructors, the MineField constructor first populates the fields with the values of the
current game. Then it calls a method called init (which we examine next). Finally, it calls the populate
method that has no constructors (there are two populate methods—we go over why that is shortly). The
pattern of a constructor doing some simple work and then calling other methods to do more complex
work is common, by the way. It offers a way to isolate complexity, which makes the code easier to read
and easier to debug when problems arise.
Now let's look at the init method, shown in Listing 7-15.
Listing 7-15. The MineField init method
private void init() {
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++) {
mineField[i][j] = new Mine();
}
}
}
As you can see, it's a simple method. It populates the minefield with the right number of Mine
objects. The two populate methods do the heavy lifting of figuring out where the mines reside. If you're a
clever reader (and I know you are), you're wondering how there can be a Mine object in every possible
location; we tackle that mystery when we get to the Mine object itself.
For now, let's press on into the two populate methods., which I've put together in Listing 7-16.
Listing 7-16. The two populate methods
private void populate() {
populate(0);
}
private void populate(int mineCount) {
int currentCount = mineCount;
double mineChance = (double) mines / (double) (rows * columns);
for (int i = 0; i < rows; i++) {
for (int j = 0; j < columns; j++) {
Mine thisMine = mineField[i][j];
if (!thisMine.hasMine()) {
if (Math.random() < mineChance) {
thisMine.setMine();
Search WWH ::




Custom Search