0

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?

jokeSlayer94
  • 143
  • 1
  • 9
  • Do you have some use cases, i.e. inputs and expected outputs so we understand more what you are looking to achieve? – orabis May 07 '23 at 22:28
  • 1
    Create a list of all field of the board `[[0, 0], [0, 1], ..., [k, l], ...]`. Select 40 random elements from this list and place mines on these fields. – jabaa May 07 '23 at 22:32
  • [why ignore this answer?](https://stackoverflow.com/questions/66099102/javascript-minesweeper-opening-whole-mine-free-area-at-once-not-working-proper/66539667#66539667) – Mister Jojo May 07 '23 at 22:42
  • 1
    `16 x 16 = 256`, so you need to `40` random values in the range `[0...255]`, then transform each value in `{x,y}` – Mister Jojo May 07 '23 at 22:50

1 Answers1

1
  1. Create a list of all fields of the board [[0, 0], [0, 1], ..., [k, l], ...].

  2. Select mines random elements from this list (How to get a number of random elements from an array?)

  3. Place mines on these fields.

jabaa
  • 5,844
  • 3
  • 9
  • 30
  • Im not sure I understand your answer. what do you mean create a list of all the fields on the board? the board doesnt exist yet – jokeSlayer94 May 07 '23 at 22:48
  • @jokeSlayer94 Create a list of elements that represent the fields. Each element could be an array with the coordinates of the field `[4, 3]` or an object `{ x: 4, y: 3 }`. You can achieve it with a simple nested loop `const fields = []; for (let i = 0; i < row; ++i) for (let j = 0; j < col; ++j) fields.push([i, j]);`. You can enumerate the fields, as Mister Jojo commented, and iterate with a simple loop `const fields = []; for (let i = 0; i < col * row; ++i) fields.push(i);`. – jabaa May 07 '23 at 23:10