Search code examples
javaalgorithmminesweeper

Java minesweeper game problem. hiding mines when the game begins?


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++;
   }
  }
    }

Solution

  • 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.