Java Reference
In-Depth Information
Minesweeper apps already exist for Android—most of my projects are for fun and my own learning).
Also, it's the kind of abstraction that makes for good design. When the real-world situation you model
has discrete objects, it's good practice to create a class for each of those objects. In this case, a mine is a
discrete real-world object (to which the game adds another layer of abstraction, in fact), so a Mine class is
a good choice. The same applies to a minefield, so the MineField class is also a good design idea.Now,
let's move on to the MineField class. Like the MineSweeper class, it's a bigger class than anything else
we've seen earlier in the topic. Again, please read through it as closely as you can, but don't be
concerned if parts of it don't make sense right now. We take it apart method by method after you see the
whole thing. Listing 7-12 shows the entire MineField class.
Listing 7-12. The MineField class
package com.apress.java7forabsolutebeginners.examples.MineSweeper;
public class MineField {
private Mine[][] mineField;
private int rows;
private int columns;
private int mines;
private int minesFound = 0;
private int minesRemaining;
private int emptiesRemaining;
enum gameState {WIN, LOSE, CONTINUE};
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();
}
private void init() {
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++) {
mineField[i][j] = new Mine();
}
}
}
gameState resolveClick(int x, int y, boolean left) {
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++) {
if (i == x && j == y) {
Mine thisMine = mineField[i][j];
if (left) {
if (thisMine.getFlagState() ==
Search WWH ::




Custom Search