我用 JS 构建了一个广泛的扫雷游戏,我正在尝试实现一种有效的方法来通过点击重新启动游戏,但我做空了。现在我只是让整个页面在点击时重新加载,但这不是我想要发生的。我构建游戏的方式,一切都被加载,所以我不确定如何在不重构我的所有代码的情况下处理这个问题。我尝试创建一个函数来重置所有全局变量,删除我之前创建的所有 div,然后调用一个我创建的函数来包装我的所有代码并重新做一遍。这种方法删除了 div,但没有再次放置它们。
这是我的主要功能
function createBoard() {
const bombsArray = Array(bombAmount).fill('bomb')
const emptyArray = Array(width * height - bombAmount).fill('valid')
const gameArray = emptyArray.concat(bombsArray)
// --Fisher–Yates shuffle algorithm--
const getRandomValue = (i, N) => Math.floor(Math.random() * (N - i) + i)
gameArray.forEach((elem, i, arr, j = getRandomValue(i, arr.length)) => [arr[i], arr[j]] = [arr[j], arr[i]])
// --- create squares ---
for (let i = 0; i < width * height; i++) {
const square = document.createElement('div')
square.setAttribute('id', i)
square.classList.add(gameArray[i])
grid.appendChild(square)
squares.push(square)
square.addEventListener('click', function () {
click(square)
})
square.oncontextmenu = function (e) {
e.preventDefault()
addFlag(square)
}
}
//add numbers
for (let i = 0; i < squares.length; i++) {
let total = 0
const isLeftEdge = (i % width === 0)
const isRightEdge = (i % width === width - 1)
if (squares[i].classList.contains('valid')) {
//left
if (i > 0 && !isLeftEdge && squares[i - 1].classList.contains('bomb')) total++
//top right
if (i > 9 && !isRightEdge && squares[i + 1 - width].classList.contains('bomb')) total++
//top
if (i > 10 && squares[i - width].classList.contains('bomb')) total++
//top left
if (i > 11 && !isLeftEdge && squares[i - 1 - width].classList.contains('bomb')) total++
//right
if (i < 129 && !isRightEdge && squares[i + 1].classList.contains('bomb')) total++
//bottom left
if (i < 120 && !isLeftEdge && squares[i - 1 + width].classList.contains('bomb')) total++
这有效地删除了加载时创建的网格方块,但不会再次创建它们。我希望能够再次运行该初始函数。我怎样才能做到这一点?
这是一个代码笔
慕容708150
相关分类