Search code examples
javaminesweeper

create random mines for a minesweeper game


 JButton[][] buttons = new JButton[20][20];
public void mines(){
    ArrayList<Integer> x = new ArrayList<>();
    ArrayList<Integer> y = new ArrayList<>();
    for(int a=0;a<20;a++){
        x.add(a);
        y.add(a);
    }
    for(int i=0;i<30;i++){
    int random_x = x.get(new Random().nextInt(x.size()));
    int random_y = y.get(new Random().nextInt(y.size()));
    x.remove(random_x);
    y.remove(random_y);
    buttons[random_x][random_y].setText("X");
    }  
}

I Want to create random mines for a minesweeper game..can anyone tell what I am doing wrong ?If i run the program it won't show me 30 random mines


Solution

  • Try this method:

    public static void mines(JButton[][] buttons)
    {
        Random rand = new Random();
        int mineCount = 0;
        while (mineCount < 30)
        {
            int randomInteger = (int) (rand.nextDouble() * buttons.length);
            int randomInteger2 = (int) (rand.nextDouble() * buttons[0].length);
            if (buttons[randomInteger][randomInteger2].getText().equals("X"))
                continue;
            else
            {
                buttons[randomInteger][randomInteger2].setText("X");
                mineCount++;
            }
        }
    
    }
    

    .nextDouble() method returns a Double value less than 1.0. But we need a random integer between 0 and 19(which is buttons.length-1).

    So we multiply this random double value with the size of the button list, which is 20, and we cast it to int. So we can get values between 0 and 19.

    Difference between buttons.length and buttons[0].length is, with the first one you get the length of first dimension(it's a two dimension array, as you know) and the second one gives the length of the second dimension. So you get the number dynamically and multiply with the random number, to avoid ArrayIndexOutOfBounds exception.

    You can use this method with any size of two dimensional buttons array, it will work. But warning, if you use an array which has less than 30 buttons, while loop will continue forever, as you can't get 30 mines :)

    One way to improve this method would be parameterizing mineCount, so you can change the method like public static void mines(JButton[][] buttons, int mineCount) so you can set mine count on method call.