【发布时间】:2021-12-31 10:38:46
【问题描述】:
我在 javascript 中创建一个地雷游戏,在其中我生成一个分配给一个 div 的随机数,这个 div 将是一个地雷,但问题是例如(我将地雷数设置为 8,而不是获得 8 个不同的地雷 我获得了 8 个地雷,但其中 2 个地雷在同一个地方,所以算作我有 6 个地雷,我该如何解决?这是 codem 的重要部分,还有关于如何改进的任何提示在我的代码中,它会被认为是我非常新的程序)
let tiles = document.getElementsByClassName('tile');
let numMines = 6
for (i = 0; i < 1; i++) {
bomb = [tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))],
tiles[(Math.floor(Math.random ()* tiles.length))]]
bomb.splice(numMines)
bomb[0].style.backgroundColor = "red";
bomb[1].style.backgroundColor = "red";
bomb[2].style.backgroundColor = "red";
bomb[3].style.backgroundColor = "red";
bomb[4].style.backgroundColor = "red";
bomb[5].style.backgroundColor = "red";
bomb[6].style.backgroundColor = "red";
bomb[7].style.backgroundColor = "red";
bomb[8].style.backgroundColor = "red";
bomb[9].style.backgroundColor = "red";
bomb[10].style.backgroundColor = "red";
bomb[11].style.backgroundColor = "red";
bomb[12].style.backgroundColor = "red";
bomb[13].style.backgroundColor = "red";
bomb[14].style.backgroundColor = "red";
bomb[15].style.backgroundColor = "red";
bomb[16].style.backgroundColor = "red";
bomb[17].style.backgroundColor = "red";
bomb[18].style.backgroundColor = "red";
bomb[19].style.backgroundColor = "red";
bomb[20].style.backgroundColor = "red";
bomb[21].style.backgroundColor = "red";
bomb[22].style.backgroundColor = "red";
bomb[23].style.backgroundColor = "red";
bomb[24].style.backgroundColor = "red";
bomb[24].style.backgroundColor = "red";
} ```
【问题讨论】:
-
老兄为什么只需要循环一次
i < 1 -
很抱歉,但我对你的问题没有确切的答案,但我希望这个逻辑适用于你的情况。您可以记录以前出现过哪些号码,因此在创建地雷时,在使用该号码之前,您可以检查是否以前使用过此号码,如果没有,则可以部署我的号码,否则您可以跳过部署我的号码。 我不懂我的游戏,所以如果我使用了一些错误的术语,我很抱歉
标签: javascript html random grid