1

I am struggling to randomly select some divs (9 in this case) to place bombs/mines for those selected tiles.

My code for this is:

    function place_mines() {

    if (document.getElementById("difficulty").selectedIndex == "2") {

        for (var u = 0; u < 8; u++) {

        }

    }
}

enter image description here Inspected the element, grid which contains all the tiles.

  • 1
    Take a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random function. Start by creating a function that returns an index of the tile to be selected. In your case, you could use # of divs with `tile` class name + 1 as the max. (avoid gotcha: it could generate duplicate number, so keep track of generated numbers and skip if already selected). Once you have 9 distinct numbers between 0 and max, just add some special class to those tiles to show them as selected. – printfmyname Mar 24 '22 at 00:57
  • Thanks a lot @printfmyname, your comment enabled me to think of this problem with new eyes! – Vatsal Rajyaguru Mar 24 '22 at 01:58

3 Answers3

2

I would use a different approach. I would make a list of tile objects and generate the html from the list. This lets you flag an object as bomb without revealing it to the user by adding it as class name.

After you generated the list, you can take a random subset and flag it as bombs. You could use this approach for example: Sampling a random subset from an array.

Tobias
  • 294
  • 3
  • 13
0

I suggest you to give id to the tiles, to later you generate random id , and map the generated id to the tiles

Tinsae
  • 577
  • 5
  • 10
0

What worked for me was I added a counter to index the elements. After that, made an array of 9 random numbers from 0-80 (counter starts at 0), checked if the id of the tile selected is in that array, if it was then that tile has a mine else its a normal tile.

tile.setAttribute("id",counter);counter++;