Browse Source

Add bomb placement

feature_Minesweeper_Playfield
kfkama 2 years ago
parent
commit
1dc0576f7b
  1. 34
      src/main/java/Minesweeper/MinesweeperGame.java
  2. 41
      src/test/java/Minesweeper/MinesweeperGameTest.java

34
src/main/java/Minesweeper/MinesweeperGame.java

@ -10,12 +10,14 @@ public class MinesweeperGame extends JPanel {
private static final int WIDTH = 600, HEIGTH = 600;
private static final int CELLSIZE = 40;
private int playfieldSize;
private int bombAmount;
public Cell[][] playfield;
public MinesweeperGame(int _playfieldSize) {
public MinesweeperGame(int _playfieldSize, int _bombAmount) {
this.setSize(WIDTH, HEIGTH);
playfieldSize = _playfieldSize;
bombAmount = _bombAmount;
setLayout(null);
initPlayfield();
@ -25,19 +27,39 @@ public class MinesweeperGame extends JPanel {
playfield = new Cell[playfieldSize][playfieldSize];
int[] bPlacment = new int[bombAmount];
for (int i = 0; i < bPlacment.length; i++) {
bPlacment[i] = (int) (Math.random() * playfieldSize * playfieldSize);
for (int j = 0; j < i; j++) {
if (bPlacment[i] == bPlacment[j]) {
i--;
break;
}
}
}
for (int i = 0; i < playfieldSize; i++) {
for (int j = 0; j < playfieldSize; j++) {
Cell c = new Cell(CellType.Number);
c.setBounds(j * CELLSIZE + (WIDTH / 2 - playfieldSize * CELLSIZE / 2), i * CELLSIZE + (HEIGTH / 2 - playfieldSize * CELLSIZE / 2), CELLSIZE,
CELLSIZE);
add(c);
playfield[i][j] = new Cell(CellType.Number);
playfield[i][j].setBounds(j * CELLSIZE + (WIDTH / 2 - playfieldSize * CELLSIZE / 2),
i * CELLSIZE + (HEIGTH / 2 - playfieldSize * CELLSIZE / 2), CELLSIZE, CELLSIZE);
add(playfield[i][j]);
for (int k = 0; k < bPlacment.length; k++) {
if (bPlacment[k] == i * playfieldSize + j) {
playfield[i][j].type = CellType.Bomb;
break;
}
}
}
}
}
public static void main(String[] args) {
JFrame f = new JFrame();
MinesweeperGame ttt = new MinesweeperGame(8);
MinesweeperGame ttt = new MinesweeperGame(8, 10);
f.add(ttt);
f.setSize(WIDTH, HEIGTH);

41
src/test/java/Minesweeper/MinesweeperGameTest.java

@ -0,0 +1,41 @@
package Minesweeper;
import static org.junit.jupiter.api.Assertions.*;
import java.util.stream.Stream;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class MinesweeperGameTest {
@ParameterizedTest
@MethodSource("testBombs")
void testBombPlacement(int _playfieldSize, int _bombAmount) {
MinesweeperGame m = new MinesweeperGame(_playfieldSize, _bombAmount);
int bombCounter = 0;
for(Cell[] row : m.playfield){
for (Cell c : row) {
if(c.type == CellType.Bomb) {
bombCounter++;
}
}
}
assertEquals(_bombAmount, bombCounter);
}
private static Stream<Arguments> testBombs(){
return Stream.of(
Arguments.of(8, 10),
Arguments.of(8, 0),
Arguments.of(4, 12),
Arguments.of(10, 100),
Arguments.of(5, 1)
);
}
}
Loading…
Cancel
Save