【问题标题】:How to reset everything in my javascript game如何重置我的 javascript 游戏中的所有内容
【发布时间】:2020-11-17 11:13:38
【问题描述】:

我用 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++
      //bottom right
      if (i < 119 && !isRightEdge && squares[i + 1 + width].classList.contains('bomb')) total++
      //bottom 
      if (i <= 119 && squares[i + width].classList.contains('bomb')) total++

      squares[i].setAttribute('data', total)
    }
  }
}
createBoard()

真的,我只是希望能够在单击此函数创建的 div 时清除它们,然后再次创建它们。当我尝试这个时:

function resetGame() {
  width = 10
  height = 13
  bombAmount = 20
  squares = []
  isGameOver = false
  flags = 0
  grid.remove('div')
  createBoard() 
}

这有效地删除了加载时创建的网格方块,但不会再次创建它们。我希望能够再次运行该初始功能。我该怎么做?

这是codepen

【问题讨论】:

标签: javascript


【解决方案1】:

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

grid.remove("div");

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

grid.innerHTML = "";

Pen

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多