I'm making Java Minesweeper for as a simple project, but the program can never count the correct number of bombs. Here is the function, I've written, numFunction() that finds all possible combinations of touching x and y cords and iterates over all of them together. Note that I've used try/catch here to eliminate any index errors:
public static int numTouching(int x, int y){
int n=0;
//define every possible coordinate touching the bomb
//iterate through the lists of coordinates to count the number of touching bombs
int[]xCords = {x-1, x, x+1};
int[]yCords = {y-1, y, y+1};
if(board[x][y] != "B"){
try{
for(int i=0; i<xCords.length; i++){
for(int j=0; j<yCords.length; j++){
int xPos = xCords[i];
int yPos= yCords[j];
if(board[xPos][yPos]=="B" && board[xPos][yPos]!=board[x][y]){
n++;
board[x][y]=n;
}
}
}
}
catch(Exception e){}
}
return n;
}
Here is the sample output for this program (I want to make it so that all of the elements touching B are set to 1):
Column count = 3
0 0 0
0 B 0
0 1 1
Num touching (0,1): 0
Num touching (1,0): 0
0 0 0
0 B 0
0 1 1
The weird thing is that it changes depending on the order of the elements in xCords and yCords (it seems that only the first two values of each array matters). For instance if xCords = {x, x-1, x+1}, and yCords = {y, y-1, y+1}, this is the sample output:
Column count = 3
0 0 0
0 B 1
0 1 0
Num touching (0,1): 0
Num touching (1,0): 0
0 0 0
0 B 1
0 1 0
Thanks in advance.