如何从另一个div中随机选择div?

发布于 2025-01-16 22:54:23 字数 405 浏览 3 评论 0原文

我正在努力随机选择一些 div(在本例中为 9)来为这些选定的图块放置炸弹/地雷。

我的代码是:

    function place_mines() {

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

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

        }

    }
}

在此处输入图像描述检查包含所有图块的元素网格。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心碎无痕… 2025-01-23 22:54:23

我会使用不同的方法。我会创建一个tile对象列表并从列表中生成html。这使您可以将对象标记为炸弹,而无需通过将其添加为类名来将其透露给用户。

生成列表后,您可以随机选取一个子集并将其标记为炸弹。例如,您可以使用此方法:从数组中采样随机子集

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.

骄兵必败 2025-01-23 22:54:23

我建议您为图块提供 id ,稍后生成随机 id ,并将生成的 id 映射到图块

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

So要识趣 2025-01-23 22:54:23

对我有用的是我添加了一个计数器来索引元素。
之后,制作一个由 0-80 的 9 个随机数组成的数组(计数器从 0 开始),检查所选图块的 id 是否在该数组中,如果是则该图块有地雷,否则它是一个普通图块。

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

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++;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文