class MineGrid { MineSquare[][] grid; int rows, cols; MineGrid(int rows, int cols) { this.rows = rows; this.cols = cols; grid = new MineSquare[rows][cols]; } void populateGrid(int numBombs) { if (numBombs > rows * cols) numBombs = rows * cols; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { grid[i][j] = new MineSquare(); } } for (int i = 0; i < numBombs; i++) { int potBombX = (int) (Math.random() * rows); int potBombY = (int) (Math.random() * cols); boolean bombCheck = false; while (!bombCheck) { bombCheck = grid[potBombX][potBombY].setMine(); potBombX = (potBombX + 1) % rows; if (potBombX == 0) potBombY = (potBombY + 1) % cols; } } assignMineNumbers(); } public boolean checkCoords(int row, int col) { return (row < rows && row >= 0 && col < cols && col >= 0); } void assignMineNumbers() { for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { grid[i][j].neighbourMines = checkNeighbours(i, j); } } } int checkNeighbours(int row, int col) { int res = 0; for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (checkCoords(row + i, col + j) && grid[row + i][col + j].isMine) { res++; } } } return res; } @Override public String toString() { String res = ""; for (int i = 0; i < rows; i++) { for (int j = 0; j < cols; j++) { res += grid[i][j]; } res += "\n"; } return res; } }