亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何重置我的 javascript 游戲中的所有內容

如何重置我的 javascript 游戲中的所有內容

阿波羅的戰車 2022-12-09 16:30:00
我用 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++      這有效地刪除了加載時創建的網格方塊,但不會再次創建它們。我希望能夠再次運行該初始函數。我怎樣才能做到這一點?這是一個代碼筆
查看完整描述

1 回答

?
慕容708150

TA貢獻1831條經驗 獲得超4個贊

您正在刪除.grid容器,而不是

grid.remove("div");

使用以下語句刪除容器的所有內容

grid.innerHTML = "";


查看完整回答
反對 回復 2022-12-09
  • 1 回答
  • 0 關注
  • 74 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號