我正在构建扫雷器背后的逻辑,而不是实际的游戏,在游戏中,我只是使用默认的value=0设置一个4*4 mineField数组,并使用value=1在其中随机生成4个炸弹。
[ ][ ][ ]
[ ][x][ ]
[ ][ ][ ]然后数一数有多少炸弹,这个数字被存储在一个“并行数组”中,然后显示在屏幕上。
现在,我可以用4个随机生成的炸弹创建字段,如下所示:公共类MineSweeper {
public static int[][] afterCheck=new int[4][4];
public static int[][] mineField=new int[4][4];
public static int bombNumber=4;
public static void setBombs()
{
//bombNumber variable will decide the number of loops
for(int i=0;i<bombNumber;)
{
int firstRandom=(int)(Math.random()*4);
int secondRandom=(int)(Math.random()*4);
if(mineField[firstRandom][secondRandom]== 0)
{
mineField[firstRandom][secondRandom]=1;
i++;
}但是到目前为止,对于checkBomb()方法,我已经编写了两个不同的代码,但都不起作用。code1:公共静态空checkBombs() {
for(int i=0;i<4;i++)
{
int counter=0;
try{
for(int y=0;y<4;y++)
{
if (mineField[i][y + 1] == 1)
counter++;
if (mineField[i][y - 1] == 1)
counter++;
if (mineField[i - 1][y] == 1)
counter++;
if (mineField[i - 1][y + 1] == 1)
counter++;
if (mineField[i - 1][y - 1] == 1)
counter++;
if (mineField[i + 1][y] == 1)
counter++;
if (mineField[i + 1][y + 1] == 1)
counter++;
if (mineField[i + 1][y - 1] == 1)
counter++;
afterCheck[i][y] = counter;
}
} catch(Exception e){}
}
}第二个代码:
public static void checkBombs()
{
for(int i=0;i<4;i++)
{
int counter=0;
try{
for(int y=0;y<4;y++)
{
for(int a=i-1;a<i+1;a++)
{
for (int b=y-1;b<y+1;b++)
{
if(mineField[a][b]==1)
counter++;
}
}
*/
afterCheck[i][y] = counter;
}
} catch(Exception e){}
}
}我需要你们的帮助。
发布于 2015-02-28 20:48:03
介绍一种安全处理电路板边缘的方法:
int bombCount(int i, int j) {
if (i < 0 || j < 0 || i >= mineField.length || j >= mineField[i].length)
return 0;
return mineField[i][j];
}然后,您可以使用您的第二个版本,使用for循环,通过替换
mineField[i][j]使用
bombCount(i, j)你也可以消除那里的所有if-ology,只需使用
counter += bombCount(i,j);只是为了引起兴趣,这是一个“不好的做法”,但是正确的,等同于上面的方法
int bombCount(int i, int j) {
try { return mineField[i][j]; }
catch (ArrayIndexOutOfBoundsException _) { return 0; }
}上面的代码和您的代码之间的区别在于,对于每个数组访问,都会单独捕获异常,而您的方法会在遇到第一个不正常的情况时缩短其余的计算过程。
最后,顺便说一句,这些天HotSpot已经对糟糕的实践变体进行了优化,所以这种习惯用法实际上不会对性能造成太大影响。大多数Java专家都会对此不以为然。
https://stackoverflow.com/questions/28781766
复制相似问题