如何从另一个div中随机选择div?
我正在努力随机选择一些 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++) {
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会使用不同的方法。我会创建一个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.
我建议您为图块提供 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
对我有用的是我添加了一个计数器来索引元素。
之后,制作一个由 0-80 的 9 个随机数组成的数组(计数器从 0 开始),检查所选图块的 id 是否在该数组中,如果是则该图块有地雷,否则它是一个普通图块。
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.