我为我的java扫雷游戏编写了这个方法,它应该检查一组坐标周围的点,然后计算附近有多少炸弹。
public void numberMines(){
int count = 0;
int x = 0;
int y = 0;
int xMin = x-1;
int xMax = x+1;
int yMin = y-1;
int yMax = y+1;
if (x == 0){
xMin = 0;
}
if (y == 0){
yMin = 0; //these restrictions take care of the spots in the edges
}
if (x == rows){
xMax = rows;
}
if (y == columns){
yMax = columns;
}
//first 2 loops go through every spot on the board
for (x=0; x<rows; x++){
for (y=0; y<columns; y++){
//if the spot selected is not a bomb, for loops check spaces surrounding it
if (mineBoard[x][y] != bomb){
for (int i = xMin; i <=xMax; i++){
for (int j = yMin; j <=yMax; j++){
if (mineBoard[i][j] == bomb){
count++;
}
}
}
}
if (count > 0){ //converts them characters
mineBoard[x][y] = (char)(count + '0');
count = 0;
}
}
}
}
每次我运行这个方法时它返回3,2,1,或者为空,所以它确实计算了多少枚炸弹,但由于某种原因,它过度循环并为每个不是炸弹的地点返回相同的东西在第一个之后。我真的不知道我搞砸了哪里,请帮忙!
答案 0 :(得分:1)
移动这段代码:
int xMin = x-1;
int xMax = x+1;
int yMin = y-1;
int yMax = y+1;
if (x == 0){
xMin = 0;
}
if (y == 0){
yMin = 0; //these restrictions take care of the spots in the edges
}
if (x == rows){
xMax = rows;
}
if (y == columns){
yMax = columns;
}
你的for循环内部:
for (x=0; x<rows; x++){
for (y=0; y<columns; y++){
//Insert code here <---
因为目前你正在进行一次的计算,对于x = 0,y = 0。
如果您在count
,i
循环之前将j
的设置移动到0,并且在所有循环开始之前没有完成一次,则代码可能看起来更干净,再次在显示结果的条件内。
根据您的评论 - 我认为您的有效索引范围为0..(rows-1)
和0..(columns-1)
- 因此您也有一个fencepost错误。修改这些行:
if (x == rows-1){
xMax = rows-1;
}
if (y == columns-1){
yMax = columns-1;
}
但仍然在x
/ y
循环中包含整个块。当他们在外面时,您不会收到越界错误,因为当xMax
和yMax
处于最大值时,您永远不会计算x
和y
。
答案 1 :(得分:0)
避免在方法开头声明所有变量,最好在使用时将它们声明为接近。要解决您的问题,您需要在循环中计算count,xMin,xMax,yMin和yMax,如下所示:
public void numberMines(){
//first 2 loops go through every spot on the board
for (int x=0; x<rows; x++){
for (int y=0; y<columns; y++){
int count = 0;
//if the spot selected is not a bomb, for loops check spaces surrounding it
if (mineBoard[x][y] != bomb){
for (int i = (x == 0 ? 0 : x-1); i <= (x == rows ? rows : x+1); i++){
for (int j = (y == 0 ? 0 : y-1); j <= (y == rows ? rows : y+1); j++){
if (mineBoard[i][j] == bomb){
count++;
}
}
}
}
if (count > 0){ //converts them characters
mineBoard[x][y] = (char)(count + '0');
}
}
}
}
我已经内联了边界检查,这是不必要的,但是这里的代码更短。