Reputation: 117
I've been able to successfully initiate a minefield when the game begins with 10 mines randomly scattered over the field. However, I'm having problems hiding these mines from the user when the game begins. As you know, the point of minesweeper is to find where the mines are WITHOUT being able to see them. I need help figuring out how to hide the mines.
Below is the code I have written for my Grid class which initiates the grid and includes a method which fills it with mines. How can I hide these mines and only reveal them when they are clicked on? Thanks for the help!
public class Grid {
private int[][] grid;
private boolean isHidden;
private int rows;
private final int columns;
private final int mines;
public Grid() {
this.rows = 8;
this.columns = 8;
this.mines = 10;
this.grid = new int[rows][columns];
}
public int[][] getGrid() {
return grid;
}
public int getRows() {
return rows;
}
public int getColumns() {
return columns;
}
public void fillGrid() {
Random ranGen = new Random();
for(int i = 0; i < this.mines; ) {
int row = ranGen.nextInt(this.rows - 1);
int column = ranGen.nextInt(this.columns - 1);
if(grid[row][column] != MinesweeperGUI.MINE) {
grid[row][column] = MinesweeperGUI.MINE;
i++;
}
}
}
Upvotes: 0
Views: 2639
Reputation: 5719
You should have two matrices: One for the mines (MineMatrix
) and one to track the user clicks (UserClickMatrix
).
You should only show the end user UserClickMatrix
and initialize all the cells with NotClicked
at the start of the game. Whenever the user clicks on a cell, change the status of the cell to Clicked
. Then, grab the cell indices from UserClickMatrix
and check against MineMatrix (MineMatrix[clickedRow][clickedColumn] == MINE
). If the condition evaluates to TRUE, game ends.
Upvotes: 1
Reputation: 1347
Why doesn't your grid matrix contains elements of the class GridElement? This GridElement class could have an property "bool visibile". An grid matrix of int's isn't so good. Think more OO.
Upvotes: 0
Reputation: 6043
Lots of methods. Easiest to implement here would be a 2d array of booleans: Opened and unopened. If not opened, show a closed square. Else, show what's there.
An alternative method would be to turn this more object oriented, and make a Tile class: it holds a boolean for a mine, and a enum for open/closed/flagged/question mark.
Upvotes: 4