dimanche 7 mai 2023

How can I ensure that x number of mines are placed on a minesweeper board, if the mines are generated at random? [duplicate]

So I am making minesweeper in html/css/javascript. I have 3 different difficulty states that the player can choose that determine how large the board is going to be, and how many mines it will have. for the purposes of this question I'll go with the intermediate settings, 16x16 board with 40 mines on it.

board is initiated to board = []; to populate it I use

function createBoard(row,col,mines){
    let count=0;
    for(let r=0;r<row;r++){
        board[r]=[];
        for(let c=0;c<col;c++){
            if(count <= mines){
                board[r][c]=new CELL(row,col,false);
            }
            else{
                let mine = Math.round(Math.random());
                board[r][c]=new CELL(row,col,Boolean(mine)); //0 is no mine, 1 means mine
                if(mine){
                    count++;
                }
            }
        }
    }
}

so that should create the right sized board, and populate it with CELL objects, some of which are mines. The problem is that my count variable only ensures that my randomizer doesnt generate MORE THAN 40 mines. The randomizer could (theoretically) choose 0 for every single object.

so how can I make sure my board gets created with the appropriate number of mines while still being truly random?




Aucun commentaire:

Enregistrer un commentaire