minesweeper/src/main/java/org/apidesign/demo/minesweeper/MinesModel.java
author Jaroslav Tulach <jtulach@netbeans.org>
Fri, 07 Feb 2014 20:22:14 +0100
branchminesweeper
changeset 69 28cc45444d44
parent 68 d41833895448
child 70 5f851f669a15
permissions -rw-r--r--
Don't needlessly manipulate the state of UI model to speed things up
     1 /**
     2  * The MIT License (MIT)
     3  *
     4  * Copyright (C) 2013 Jaroslav Tulach <jaroslav.tulach@apidesign.org>
     5  *
     6  * Permission is hereby granted, free of charge, to any person obtaining a copy
     7  * of this software and associated documentation files (the "Software"), to deal
     8  * in the Software without restriction, including without limitation the rights
     9  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
    10  * copies of the Software, and to permit persons to whom the Software is
    11  * furnished to do so, subject to the following conditions:
    12  *
    13  * The above copyright notice and this permission notice shall be included in
    14  * all copies or substantial portions of the Software.
    15  *
    16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    18  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    19  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    21  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    22  * THE SOFTWARE.
    23  */
    24 package org.apidesign.demo.minesweeper;
    25 
    26 import java.util.ArrayList;
    27 import java.util.List;
    28 import java.util.Random;
    29 import net.java.html.json.ComputedProperty;
    30 import net.java.html.json.Function;
    31 import net.java.html.json.Model;
    32 import net.java.html.json.ModelOperation;
    33 import net.java.html.json.Property;
    34 
    35 /** Model of the mine field.
    36  */
    37 @Model(className = "Mines", properties = {
    38     @Property(name = "state", type = MinesModel.GameState.class),
    39     @Property(name = "rows", type = Row.class, array = true),
    40 })
    41 final class MinesModel {
    42     enum GameState {
    43         IN_PROGRESS, WON, LOST;
    44     }
    45     
    46     @Model(className = "Row", properties = {
    47         @Property(name = "columns", type = Square.class, array = true)
    48     })
    49     static class RowModel {
    50     }
    51 
    52     @Model(className = "Square", properties = {
    53         @Property(name = "state", type = SquareType.class),
    54         @Property(name = "mine", type = boolean.class)
    55     })
    56     static class SquareModel {
    57         @ComputedProperty static String text(SquareType state) {
    58             if (state == null) return " ";
    59             switch (state) {
    60                 case EXPLOSION: return "B";
    61                 case UNKNOWN: return "?";
    62                 case N_0: return " ";
    63             }
    64             return "" + state.ordinal();
    65         }
    66         
    67         @ComputedProperty static String style(SquareType state) {
    68             return state == null ? null : state.toString();
    69         }
    70     }
    71     
    72     enum SquareType {
    73         N_0, N_1, N_2, N_3, N_4, N_5, N_6, N_7, N_8,
    74         UNKNOWN, EXPLOSION, DISCOVERED;
    75         
    76         final boolean isVisible() {
    77             return name().startsWith("N_");
    78         }
    79 
    80         final SquareType moreBombsAround() {
    81             switch (this) {
    82                 case EXPLOSION:
    83                 case UNKNOWN:
    84                 case DISCOVERED:
    85                 case N_8:
    86                     return this;
    87             }
    88             return values()[ordinal() + 1];
    89         }
    90     }
    91     
    92     @ModelOperation static void init(Mines model, int width, int height, int mines) {
    93         List<Row> rows = new ArrayList<Row>(height);
    94         for (int y = 0; y < height; y++) {
    95             Square[] columns = new Square[width];
    96             for (int x = 0; x < width; x++) {
    97                 columns[x] = new Square(SquareType.UNKNOWN, false);
    98             }
    99             rows.add(new Row(columns));
   100         }
   101         
   102         Random r = new Random();
   103         while (mines > 0) {
   104             int x = r.nextInt(width);
   105             int y = r.nextInt(height);
   106             final Square s = rows.get(y).getColumns().get(x);
   107             if (s.isMine()) {
   108                 continue;
   109             }
   110             s.setMine(true);
   111             mines--;
   112         }
   113 
   114         model.setState(GameState.IN_PROGRESS);
   115         model.getRows().clear();
   116         model.getRows().addAll(rows);
   117     }
   118     
   119     @ModelOperation static void computeMines(Mines model) {
   120         List<Integer> xBombs = new ArrayList<Integer>();
   121         List<Integer> yBombs = new ArrayList<Integer>();
   122         final List<Row> rows = model.getRows();
   123         boolean emptyHidden = false;
   124         SquareType[][] arr = new SquareType[rows.size()][];
   125         for (int y = 0; y < rows.size(); y++) {
   126             final List<Square> columns = rows.get(y).getColumns();
   127             arr[y] = new SquareType[columns.size()];
   128             for (int x = 0; x < columns.size(); x++) {
   129                 Square sq = columns.get(x);
   130                 if (sq.isMine()) {
   131                     xBombs.add(x);
   132                     yBombs.add(y);
   133                 }
   134                 if (sq.getState().isVisible()) {
   135                     arr[y][x] = SquareType.N_0;
   136                 } else {
   137                     if (!sq.isMine()) {
   138                         emptyHidden = true;
   139                     }
   140                 }
   141             }
   142         }
   143         for (int i = 0; i < xBombs.size(); i++) {
   144             int x = xBombs.get(i);
   145             int y = yBombs.get(i);
   146             
   147             incrementAround(arr, x, y);
   148         }
   149         for (int y = 0; y < rows.size(); y++) {
   150             final List<Square> columns = rows.get(y).getColumns();
   151             for (int x = 0; x < columns.size(); x++) {
   152                 Square sq = columns.get(x);
   153                 final SquareType newState = arr[y][x];
   154                 if (newState != null && newState != sq.getState()) {
   155                     sq.setState(newState);
   156                 }
   157             }
   158         }
   159         
   160         if (!emptyHidden) {
   161             model.setState(GameState.WON);
   162             showAllBombs(model, SquareType.DISCOVERED);
   163         }
   164     }
   165     
   166     private static void incrementAround(SquareType[][] arr, int x, int y) {
   167         incrementAt(arr, x - 1, y - 1);
   168         incrementAt(arr, x - 1, y);
   169         incrementAt(arr, x - 1, y + 1);
   170 
   171         incrementAt(arr, x + 1, y - 1);
   172         incrementAt(arr, x + 1, y);
   173         incrementAt(arr, x + 1, y + 1);
   174         
   175         incrementAt(arr, x, y - 1);
   176         incrementAt(arr, x, y + 1);
   177     }
   178     
   179     private static void incrementAt(SquareType[][] arr, int x, int y) {
   180         if (y >= 0 && y < arr.length) {
   181             SquareType[] r = arr[y];
   182             if (x >= 0 && x < r.length) {
   183                 SquareType sq = r[x];
   184                 if (sq != null) {
   185                     r[x] = sq.moreBombsAround();
   186                 }
   187             }
   188         }
   189     }
   190     
   191     static void showAllBombs(Mines model, SquareType state) {
   192         for (Row row : model.getRows()) {
   193             for (Square square : row.getColumns()) {
   194                 if (square.isMine()) {
   195                     square.setState(state);
   196                 }
   197             }
   198         }
   199     }
   200     
   201     @Function static void click(Mines model, Square data) {
   202         if (model.getState() != GameState.IN_PROGRESS) {
   203             return;
   204         }
   205         
   206         switch (data.getState()) {
   207             case UNKNOWN: 
   208                 if (data.isMine()) {
   209                     showAllBombs(model, SquareType.EXPLOSION);
   210                     model.setState(GameState.LOST);
   211                 } else {
   212                     expandKnown(model, data);
   213                 }
   214             break;
   215         }
   216     }
   217     private static void expandKnown(Mines model, Square data) {
   218         final List<Row> rows = model.getRows();
   219         for (int y = 0; y < rows.size(); y++) {
   220             final List<Square> columns = rows.get(y).getColumns();
   221             for (int x = 0; x < columns.size(); x++) {
   222                 Square sq = columns.get(x);
   223                 if (sq == data) {
   224                     expandKnown(model, x, y);
   225                     return;
   226                 }
   227             }
   228         }
   229     }
   230     private static void expandKnown(Mines model, int x , int y) {
   231         if (y < 0 || y >= model.getRows().size()) {
   232             return;
   233         }
   234         final List<Square> columns = model.getRows().get(y).getColumns();
   235         if (x < 0 || x >= columns.size()) {
   236             return;
   237         }
   238         final Square sq = columns.get(x);
   239         if (sq.getState() == SquareType.UNKNOWN) {
   240             sq.setState(SquareType.N_0);
   241             model.computeMines();
   242             if (sq.getState() == SquareType.N_0) {
   243                 expandKnown(model, x - 1, y - 1);
   244                 expandKnown(model, x - 1, y);
   245                 expandKnown(model, x - 1, y + 1);
   246                 expandKnown(model, x , y - 1);
   247                 expandKnown(model, x, y + 1);
   248                 expandKnown(model, x + 1, y - 1);
   249                 expandKnown(model, x + 1, y);
   250                 expandKnown(model, x + 1, y + 1);
   251             }
   252         }
   253     }
   254 }