1.1 --- a/minesweeper/src/main/java/org/apidesign/demo/minesweeper/MinesModel.java Fri Feb 07 14:47:07 2014 +0100
1.2 +++ b/minesweeper/src/main/java/org/apidesign/demo/minesweeper/MinesModel.java Fri Feb 07 15:21:54 2014 +0100
1.3 @@ -66,8 +66,20 @@
1.4 }
1.5
1.6 enum SquareType {
1.7 +
1.8 N_0, N_1, N_2, N_3, N_4, N_5, N_6, N_7, N_8,
1.9 - UNKNOWN, MINE
1.10 + UNKNOWN, MINE;
1.11 +
1.12 + final boolean isVisible() {
1.13 + return name().startsWith("N_");
1.14 + }
1.15 +
1.16 + final SquareType moreBombs() {
1.17 + if (this == MINE || this == UNKNOWN) {
1.18 + return this;
1.19 + }
1.20 + return values()[ordinal() + 1];
1.21 + }
1.22 }
1.23
1.24 @ModelOperation static void init(Mines model, int width, int height, int mines) {
1.25 @@ -97,6 +109,54 @@
1.26 model.getRows().addAll(rows);
1.27 }
1.28
1.29 + @ModelOperation static void computeMines(Mines model) {
1.30 + List<Integer> xBombs = new ArrayList<Integer>();
1.31 + List<Integer> yBombs = new ArrayList<Integer>();
1.32 + final List<Row> rows = model.getRows();
1.33 + for (int y = 0; y < rows.size(); y++) {
1.34 + final List<Square> columns = rows.get(y).getColumns();
1.35 + for (int x = 0; x < columns.size(); x++) {
1.36 + Square sq = columns.get(x);
1.37 + if (sq.isMine()) {
1.38 + xBombs.add(x);
1.39 + yBombs.add(y);
1.40 + }
1.41 + if (sq.getState().isVisible()) {
1.42 + sq.setState(SquareType.N_0);
1.43 + }
1.44 + }
1.45 + }
1.46 + for (int i = 0; i < xBombs.size(); i++) {
1.47 + int x = xBombs.get(i);
1.48 + int y = yBombs.get(i);
1.49 +
1.50 + incrementAround(model, x, y);
1.51 + }
1.52 + }
1.53 +
1.54 + private static void incrementAround(Mines model, int x, int y) {
1.55 + incrementAt(model, x - 1, y - 1);
1.56 + incrementAt(model, x - 1, y);
1.57 + incrementAt(model, x - 1, y + 1);
1.58 +
1.59 + incrementAt(model, x + 1, y - 1);
1.60 + incrementAt(model, x + 1, y);
1.61 + incrementAt(model, x + 1, y + 1);
1.62 +
1.63 + incrementAt(model, x, y - 1);
1.64 + incrementAt(model, x, y + 1);
1.65 + }
1.66 +
1.67 + private static void incrementAt(Mines model, int x, int y) {
1.68 + if (y >= 0 && y < model.getRows().size()) {
1.69 + Row r = model.getRows().get(y);
1.70 + if (x >= 0 && x < r.getColumns().size()) {
1.71 + Square sq = r.getColumns().get(x);
1.72 + sq.setState(sq.getState().moreBombs());
1.73 + }
1.74 + }
1.75 + }
1.76 +
1.77 static void showAllBombs(Mines model) {
1.78 for (Row row : model.getRows()) {
1.79 for (Square square : row.getColumns()) {
1.80 @@ -119,6 +179,7 @@
1.81 model.setState(GameState.LOST);
1.82 } else {
1.83 data.setState(SquareType.N_0);
1.84 + model.computeMines();
1.85 }
1.86 break;
1.87 }