我用 JS 構建了一個廣泛的掃雷游戲,我正在嘗試實現一種有效的方法來通過點擊重新啟動游戲,但我做空了?,F在我只是讓整個頁面在點擊時重新加載,但這不是我想要發生的。我構建游戲的方式,一切都被加載,所以我不確定如何在不重構我的所有代碼的情況下處理這個問題。我嘗試創建一個函數來重置所有全局變量,刪除我之前創建的所有 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++ 這有效地刪除了加載時創建的網格方塊,但不會再次創建它們。我希望能夠再次運行該初始函數。我怎樣才能做到這一點?這是一個代碼筆
如何重置我的 javascript 游戲中的所有內容
阿波羅的戰車
2022-12-09 16:30:00