0

I know, I know. This has been asked a lot of times. I am not looking for an algorithm. I think my algorithm is not working properly.

Here is the algorithm I am using:

public void onFirstMove (int moveX, int moveY) {
    setFirstMove (false);
    Random r = new Random ();

    for (int i = 0 ; i < 10 ; i++) {
        int x;
        int y;
        do {
            x = r.nextInt (9);
            y = r.nextInt (9);
        } while (tileMatrix[x][y].hasMine () &&
                moveX == x && moveY == y);

        tileMatrix[x][y].setMine ();
    }

    timer.startTimer ();
}

I put it in the onFirstMove method because I don't want the player to lose on the first move. As you can see, I made it keep trying to find x and y coords while it is the same as the position of the first move.

while (tileMatrix[x][y].hasMine () &&
                moveX == x && moveY == y);

And now it has 2 known bugs:

  1. It sometimes generates 9 mines instead of 10. I know this because when I lose, it displays where all the mines at.

  2. It sometimes does generate a mine at the position of the first move.

Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • 1
    To interested parties, I solved this first XD http://chat.stackoverflow.com/transcript/message/25104533#25104533 – xrisk Aug 15 '15 at 04:44

2 Answers2

2

The bug is in your while condition. It should be:

while (tileMatrix[x][y].hasMine () ||    // OR not AND
                (moveX == x && moveY == y));
xashru
  • 3,400
  • 2
  • 17
  • 30
0

I agree with xashru's answer (1+ to it). Myself, I'd use a List, add all the Tiles to the List except the first move tile, shuffle it, and then select the first N tiles (N being the number of mines, and set the mines. e.g., something like:

public void onFirstMove (int moveX, int moveY) {
    setFirstMove (false);

    // assuming your tiles are of type Tile
    List<Tile> tileList = new ArrayList<>();
    for (int x = 0; x < MAX_X; x++) {
        for (int y = 0; y < MAX_Y; y++) {
            if (x != moveX || x != moveY) {
                // add all tile's except the first move
                tileList.add(tileMatrix[x][y]);
            }
        }
    }

    // randomize the collection
    java.util.Collections.shuffle(tileList);

    // set MAX_MINES tiles to have mines
    for (int i = 0; i < MAX_MINES; i++) {
        tileList.get(0).setMine();
    }
    timer.startTimer();
}

For more MineSweeper "fun", please see my code and answer to this MineSweeper Question.

Community
  • 1
  • 1
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373