package Minesweeper; import java.awt.Point; public class Playfield { private static final int CELLSIZE = 50; public int Size; private MinesweeperGame MsG; public Cell[][] cells; public Playfield(MinesweeperGame _MsG, int _Size, int _bombAmount) { MsG = _MsG; Size = _Size; generatePlayfield(_bombAmount); } public void generatePlayfield(int _bombAmount) { cells = new Cell[Size][Size]; int[] bPlacement = new int[_bombAmount]; for (int i = 0; i < bPlacement.length; i++) { bPlacement[i] = (int) (Math.random() * Size * Size); for (int j = 0; j < i; j++) { if (bPlacement[i] == bPlacement[j]) { i--; break; } } } for (int i = 0; i < Size; i++) { for (int j = 0; j < Size; j++) { cells[i][j] = new Cell(CellType.Number, this, new Point(j, i)); cells[i][j].setBounds(j * CELLSIZE + (MsG.WIDTH / 2 - Size * CELLSIZE / 2), i * CELLSIZE + (MsG.HEIGTH / 2 - Size * CELLSIZE / 2), CELLSIZE, CELLSIZE); MsG.add(cells[i][j]); for (int k = 0; k < bPlacement.length; k++) { if (bPlacement[k] == i * Size + j) { cells[i][j].type = CellType.Bomb; cells[i][j].update(); break; } } } } for (int i = 0; i < Size; i++) { for (int j = 0; j < Size; j++) { if (cells[i][j].type == CellType.Number) { calculateBombProximity(i, j); } } } } public void calculateBombProximity(int row, int column) { if (row > 0) { if (column > 0) { if (cells[row - 1][column - 1].type == CellType.Bomb) { cells[row][column].value++; } } if (cells[row - 1][column].type == CellType.Bomb) { cells[row][column].value++; } if (column < cells.length - 1) { if (cells[row - 1][column + 1].type == CellType.Bomb) { cells[row][column].value++; } } } if (row < cells.length - 1) { if (column > 0) { if (cells[row + 1][column - 1].type == CellType.Bomb) { cells[row][column].value++; } } if (cells[row + 1][column].type == CellType.Bomb) { cells[row][column].value++; } if (column < cells.length - 1) { if (cells[row + 1][column + 1].type == CellType.Bomb) { cells[row][column].value++; } } } if (column > 0) { if (cells[row][column - 1].type == CellType.Bomb) { cells[row][column].value++; } } if (column < cells.length - 1) { if (cells[row][column + 1].type == CellType.Bomb) { cells[row][column].value++; } } cells[row][column].update(); } }