Alex Moss
Alex Moss

Reputation: 161

Minesweeper number of mines java

Hi so I am almost done with this program that creates the class minesweeper game. It compiles and runs perfectly and the game shows up in the GUI client program, but one problem occurs.

When playing, sometimes the a 1 will appear when it has more than 1 adjacent mine, or a 0 when there is actually a mine in one of the eight squares surrounding it. Any help/suggestions are gladly appreciated!

private void countAdjacentMines()
{        
    // TO DO: STUDENT CODE HERE
    for (int i = 0; i < mineField.length; i++)
    {
        for (int j = 0; j < mineField.length; j++)
        {
            if (!(mineField[i][j].getIsMine()))
            {
                int count = 0;                    
                for (int p = i -1; p <= i + 1; p++)
                {          
                    for (int q = j - 1; q < j + 1; q++)
                    {
                        if (0 <= p && p < mineField.length && 0 <= q && q < mineField.length)
                        {
                            if (mineField[p][q].getIsMine())
                                count++;
                        } // end if
                    } // end for
                } // end for

            mineField[i][j].setAdjacentMines(count);
            } // end if

        } // end for loop rows
    } // end for loop columns
} // end countAdjacentMines

Upvotes: 1

Views: 3059

Answers (1)

Becuzz
Becuzz

Reputation: 6866

Your inner loop's conditional is off.

for (int q = j - 1; q < j + 1; q++)

should be

for (int q = j - 1; q <= j + 1; q++)
                      ^^

Upvotes: 3

Related Questions