我试图创建一个扫雷游戏,我有以下的代码,其中有许多嵌套的ifs,我想改变代码,以删除嵌套的ifs,并使它更好地阅读。但是,我在如何更改嵌套的ifs方面陷入了困境。任何帮助都会很好。谢谢
/*method to check cells around a cell and set its value.*/
public void setCellValues(){
for(int i = 0; i<side; i++){
for(int j = 0; j<side; j++){
if(cells[i][j].getValue() != -1){
if(j>=1 && cells[i][j-1].getValue() == -1) cells[i][j].incrementValue();
if(j<= limit && cells[i][j+1].getValue() == -1) cells[i][j].incrementValue();
if(i>=1 && cells[i-1][j].getValue() == -1) cells[i][j].incrementValue();
if(i<= limit && cells[i+1][j].getValue() == -1) cells[i][j].incrementValue();
if(i>=1 && j>= 1 && cells[i-1][j-1].getValue() == -1) cells[i][j].incrementValue();
if(i<= limit && j<= limit && cells[i+1][j+1].getValue() == -1) cells[i][j].incrementValue();
if(i>=1 && j<= limit && cells[i-1][j+1].getValue() == -1) cells[i][j].incrementValue();
if(i<= limit && j>= 1 && cells[i+1][j-1].getValue() == -1) cells[i][j].incrementValue();
}
}
}
}
/*This method starts chain reaction. When user click on particular cell, if cell is empty (value = 0) this
method look for other empty cells next to activated one. If finds one, it call checkCell and in effect,
start next scan on its closest area.
*/
public void scanForEmptyCells(){
for(int i = 0; i<side; i++){
for(int j = 0; j<side; j++){
if(!cells[i][j].isNotChecked()){
if(j>=1 && cells[i][j-1].isEmpty()) cells[i][j-1].checkCell();
if(j<= limit && cells[i][j+1].isEmpty()) cells[i][j+1].checkCell();
if(i>=1 && cells[i-1][j].isEmpty()) cells[i-1][j].checkCell();
if(i<= limit && cells[i+1][j].isEmpty()) cells[i+1][j].checkCell();
if(i>=1 && j>= 1 && cells[i-1][j-1].isEmpty()) cells[i-1][j-1].checkCell();
if(i<= limit && j<= limit && cells[i+1][j+1].isEmpty()) cells[i+1][j+1].checkCell();
if(i>=1 && j<= limit && cells[i-1][j+1].isEmpty()) cells[i-1][j+1].checkCell();
if(i<= limit && j>= 1 && cells[i+1][j-1].isEmpty()) cells[i+1][j-1].checkCell();
}
}
}
}发布于 2016-04-05 16:53:38
我通常建议你这样做,这样你就不用做很多检查了。此外,我认为,当你发现一个地雷时,迭代单元格和更新轮廓在逻辑上比为每个单元检测相邻的地雷更简单。
我不会为您编写代码(最后您正在尝试学习一些东西),但我将概述整个算法,并提供一种面向对象的方法来解决这个问题--与您当前的解决方案相比,该方法具有更小的检查功能,并且可读性更强。
为每个角落写一个if语句。如果是地雷,更新周围的三个单元,如果它们不是地雷。
在这四个边界上迭代(4个循环),更新5个相邻的单元格(如果它们不是地雷)。
的中心
对于中心的每个单元,如果它是一个地雷,更新所有的8个周围的细胞,如果他们不是地雷。
让每个单元格都是类Cell1的实例。Cell知道(并公开)它是否是地雷。它还有一个公共方法incrementNeighborCounter()2。
好了。
真的,我们结束了。(是的,您需要实现Cell,但是编程设计的基本部分已经完成,您似乎有能力编写Cell代码)。
它怎麽工作?你通过董事会一次,使用上述“程序方式”描述的模式。但是,在告诉单元格增加其计数器之前,不检查单元格是否是地雷(因为这已委托给Cell如何显示自己为地雷现在甚至可以计算它们周围的地雷了。),您只需调用incrementNeighborCounter()并继续前进。部分逻辑现在在Cell中,您的代码更简单、更轻巧,并且不太可能包含bug。
它可以是一个接口或抽象类,只是不要过火,增加不必要的复杂性。
随便你怎么说,这不是一门精确的科学。只需尝试描述和使用名称作为文档。
万一您想知道,一个非常简单的Cell实现可以使用一个布尔值来表示它是否是一个地雷,一个整数用来计算它有多少个地雷邻居。
https://codereview.stackexchange.com/questions/124845
复制相似问题