gpt4 book ai didi

java - 二维阵列扫雷器周围的地雷

转载 作者:太空宇宙 更新时间:2023-11-04 06:47:38 25 4
gpt4 key购买 nike

仍然停留在我之前问过的问题上,但我想我应该发一篇新帖子来清理一下(如果这很麻烦,抱歉)。

我正在努力展示单元格的“周围地雷”。我需要做的是允许用户清除单元格,并且如果附近有地雷,则显示有多少个,例如:我如何能够显示数组输出中单元格周围的地雷:

替换:

 0  1  2  3  4
0| . . . . .
1| . . . . .
2| . . . . *
3| . . * . .
4| * . . * *

与:

   0  1  2  3  4
0| . . . . .
1| . . . 1 1
2| . . 1 2 *
3| 1 2 * 2 2
4| * 1 2 * *

我用来放置地雷的代码是:

    public MineField(int w, int h, int m)
{
Random r = new Random();
mineField = new State[w][h];
surroundingMines = new int[w][h];
initialiseMineField = new int[w][h];
traceOn = true; //set to false before submitting
width = w;
height = h;
mineCount = m;
for (int i = 0; i < w; i++)
{
for (int j = 0; j < h; j++)
{
mineField[i][j] = State.COVERED;
}
}
for (int k = 0; k < m; k++)
{
while (true)
{
int a = r.nextInt(w);
int b = r.nextInt(h);
if (mineField[a][b] != State.MINED)
{
break;
}
}
mineField[r.nextInt(w)][r.nextInt(h)] = State.MINED;
}
}

我通过以下方式显示我的“雷区”:

public void displayField(boolean showTruth)
{
System.out.print(" ");
for (int col = 0; col < width; col++)
{
System.out.print(" " + col);
}
System.out.println();
for (int row = 0; row < height; row++)
{
System.out.print("" + row + "|");
for (int col = 0; col < width; col++)
{
//TODO: You need to complete this method by printing the correct character for the current field cell
if (mineField[row][col] == State.MINED)
{
System.out.print(" " + '*' + " " );
}
if (mineField[row][col] == State.EXPLODED)
{
System.out.print(" " + '+' + " " );
}
if (mineField[row][col] == State.COVERED)
{
System.out.print(" " + '.' + " " );
}
if (mineField[row][col] == State.CLEARED)
{
System.out.print(" " + ' ' + " " );
}
if (mineField[row][col] == State.FLAGGED)
{
System.out.print(" " + 'F' + " " );
}
if (mineField[row][col] == State.MISFLAGGED)
{
System.out.print(" " + 'F' + " " );
}
}
System.out.println();
}
}

非常感谢您的帮助,谢谢!

最佳答案

您可以编写一个方法,在给定特定单元格的坐标的情况下对具有 State.MINED 的单元格进行计数。正如评论中提到的,这可以通过两个 for 循环来完成,迭代一个单元格的邻域。返回某些给定邻居坐标是否“有效”的辅助方法在这里可能会派上用场。所以它大概看起来像这样:

private int countMines(int x, int y) 
{
int counter = 0;
for (int dx=-1; dx<=1; dx++)
{
for (int dy=-1; dy<=1; dy++)
{
if (dx == 0 && dy == 0)
{
continue;
}
int nx = x+dx;
int ny = y+dy;
if (!isValid(nx, ny))
{
continue;
}
if (mineField[nx][ny] == State.MINED)
{
counter++;
}
}
}
return counter;
}

private boolean isValid(int x, int y)
{
if (x < 0 || x >= mineField.length) return false;
if (y < 0 || y >= mineField[x].length) return false;
return true;
}

关于java - 二维阵列扫雷器周围的地雷,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23755919/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com