Minesweeper game in html css and js does not correctly count adjacent bomb units
P粉145543872
P粉145543872 2024-01-17 08:35:00
0
1
486

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

P粉145543872
P粉145543872

reply all(1)
P粉124070451

I think the problem is mixing coll and rows:

                if(cells[x+i + (y+j)*rows].isBomb == true)
                //                   ^^^^

...

    cells[x + y*coll].number = count
    //          ^^^^

Sometimes you can access the cell at x, y via cells[x y*coll], sometimes via cells[x y*rows] . I think coll is correct (each y skips an entire row consisting of coll columns), so try changing your code to :

if(cells[x+i + (y+j)*colls].isBomb == true)
//                   ^^^^^ changed here

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 an if inside another if, but neither Will cause problems) p>

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template