请问我可以通过我的java程序得到一些建议吗?无效返回?
问题描述:
请帮我用我的Java程序,我创建了下面的方法,我只是想知道如何将下面的代码应用到我的程序中。请问我可以通过我的java程序得到一些建议吗?无效返回?
模型类中最后要做的事情是向雷区添加更多值,以确定有多少地雷与任何给定的平方相邻。创建一个名为addNumbers的公共方法,该方法具有void返回值并且不带参数。以前,the_minefield中的值只有两个值,0(EMPTY_SQUARE)和10(MINE_SQUARE)。现在,任何与一个矿井正方形相邻的空方格将不再具有零值 - 现在存储其旁边的地雷数量。这可以是1(仅一个地雷)和8(完全包围)之间的任何值。包含地雷的方格仍然有十个值(MINE_SQUARE),无论旁边有什么。
//平方较早前在程序的声明:
public static int MINE_SQUARE = 10;
public static int EMPTY_SQUARE = 0;
//的需要调整的方法。
public void addNumbers() {
}
答
当你上面的方法被调用,它通过周围的细胞是当前细胞周围,并增加当前单元格的数目,如果邻居是我的迭代。因此,在伪代码:
public void addNumbers() {
loop from current row - 1 to current row + 1 taking care of *edge* cases
loop from current col - 1 to current col + 1 taking care of *edge* cases
if row and col are not both current row and current column
if cell represented by row and col has a mine
increment the current cell's number
}
请注意,您必须照顾与边缘的情况下 - 这意味着你需要知道该怎么办时,当前单元格是在第0行或山坳或者在最大高度行或最大列数。当我为我的MineSweeper应用程序完成此操作时,我将声明int作为for循环上方的嵌套for循环的起点和起点,并使用Math.min,Math.max来帮助选择我的for循环限制。因此,新的方法是这样的:
public void addNumbers() {
declare int rowMin. Use Math.max to compare 0 and row - 1 to assign rowMin
likewise for colMin
likewise for rowMax, but use Math.min instead
likewise for colMax
loop from row = rowMin to rowMax
loop from col = colMin to colMax
if row and col are not both current row and current column
if cell represented by row and col has a mine
increment the current cell's number
}
注意,对于我的扫雷程序,我做了完全相反的:我经历了所有的细胞中循环,如果我发现一个开采细胞,我增加了我的计所有的邻居,但最终结果是一样的:
public void reset() {
buttonsRemaining = (maxRows * maxCols) - mineNumber;
// randomize the mine location
Collections.shuffle(mineList);
// reset the model grid and set mines
for (int r = 0; r < cellModelGrid.length; r++) {
for (int c = 0; c < cellModelGrid[r].length; c++) {
cellModelGrid[r][c].reset();
cellModelGrid[r][c].setMined(mineList.get(r
* cellModelGrid[r].length + c));
}
}
// advance value property of all neighbors of a mined cell
for (int r = 0; r < cellModelGrid.length; r++) {
for (int c = 0; c < cellModelGrid[r].length; c++) {
if (cellModelGrid[r][c].isMined()) {
int rMin = Math.max(r - 1, 0);
int cMin = Math.max(c - 1, 0);
int rMax = Math.min(r + 1, cellModelGrid.length - 1);
int cMax = Math.min(c + 1, cellModelGrid[r].length - 1);
for (int row2 = rMin; row2 <= rMax; row2++) {
for (int col2 = cMin; col2 <= cMax; col2++) {
cellModelGrid[row2][col2].incrementValue();
}
}
}
}
}
}
我的代码链接是在这里:Minesweeper Action Events
什么是方形的?什么是“雷区”? – 2013-03-16 11:31:04
一个雷区是一组正方形在一起,比如扫雷游戏等,然后每个单独的方格用来组成网格本身。 – user2175379 2013-03-16 11:34:15