Reputation: 55
Me and my brother am making a minesweeper game. We have made almost everything, but we have a problem with the find how many mines that are next to it. My brother tried to do it with if and else if statments, but I think it is better to use a loop. I made a loop, but I have a problem. It counts the left and right side. How should I fix it. Here is my code:
int p_col = col - 1;
int p_row = row - 1;
for (int j = 0; j < 3; j++){
if (p_col + j >= 0){
if (p_row + j >= 0){
if (row + j <= height){
if (isTileMine(p_row + j, p_col))
miner++;
if (isTileMine(p_row + j, p_col + 1)){
//Teller ikke seg selv
if (p_row + j == p_row + 1){}
else{
miner++;
}
}
if (isTileMine(p_row + j, p_col + 2))
miner++;
}
}
}
}
Upvotes: 0
Views: 117
Reputation: 118435
This algorithm has a bunch of obvious bugs, not including the least the fact that, when the current position is on the right edge of the playing field, it will likely result in undefined behavior due to failed bounds checking.
You need two loops, instead of one.
The first loop from row-1 to row+1
An inner loop from col-1 to col+1
This will loop over all cells near the cell being checked.
This will also loop over (row, col) too, so you'll simply skip that, in the body of the loop
And the first order of business, inside the inner loop, before checking anything, is to verify that the current coordinate being checked is actually on the playing field. That both row and col are not negative (since the loop will iterate from row-1 and col-1, with either one possibly being 0), and do not exceed the maximum size of the playing field (since row and col can be the coordinate on the right or the bottom edge).
You know that you have the right answer when you have only one call to isTileMine()
in the body of the loop, instead of three.
Upvotes: 1