I'm trying to recreate Minesweeper with html, css and javascript, I need to check adjacent cells to see if it's a bomb and count, but it doesn't seem to be checking the correct part of the cell. I'm using a cell class with x, y, isBomb, isChecked, and a number that represents how many of its neighbors are bombs, I'm also using a 1D array to store the grid of cells So my question is if there is something wrong with this function or should I rewrite the code using the inserted 2D array
function checkN(x, y){ let count = 0 if(cells[x+y*coll].isBomb == true){ return } cells[x+y*coll].isChecked = true for(let i = -1; i<=1; i++) for(let j = -1; j<=1; j++){ if( (x+i >= 0 && x+i < coll) && (y+j >= 0 && y+j < rows) && (i != 0 || j != 0) ){ if(cells[x+i + (y+j)*rows].isBomb == true) count++ } } if(count != 0) cells[x + y*coll].number = count }
Results of using checkN function on each cell
I tried changing the values a little bit, like adding -1 to it and adding 1 to it, but it's still not correct
I think the problem is mixing
coll
androws
:Sometimes you can access the cell at
x, y
viacells[x y*coll]
, sometimes viacells[x y*rows]
. I thinkcoll
is correct (eachy
skips an entire row consisting ofcoll
columns), so try changing your code to :And consider extracting this logic into it's own function so you don't make this mistake again.
The(
== true
part is also redundant, like having anif
inside anotherif
, but neither Will cause problems) p>