为了账号安全,请及时绑定邮箱和手机立即绑定

如何重置我的 javascript 游戏中的所有内容

如何重置我的 javascript 游戏中的所有内容

阿波罗的战车 2022-12-09 16:30:00
我用 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++      这有效地删除了加载时创建的网格方块,但不会再次创建它们。我希望能够再次运行该初始函数。我怎样才能做到这一点?这是一个代码笔
查看完整描述

1 回答

?
慕容708150

TA贡献1831条经验 获得超4个赞

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

grid.remove("div");

使用以下语句删除容器的所有内容

grid.innerHTML = "";


查看完整回答
反对 回复 2022-12-09
  • 1 回答
  • 0 关注
  • 63 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号