X 在切换到 O 之前需要两圈

X takes two turns before switching to O

提问人:Joe.sexton 提问时间:10/31/2023 更新时间:10/31/2023 访问量:29

问:

我在井字游戏中添加了重启功能,但是当 X 获胜并且我点击重启时,默认情况下 X 是第一步,但切换到 O 需要两回合。

const board = document.getElementById('board')
const cell = document.querySelectorAll('.cell')
const displayOutcome = document.getElementById('display-outcome')
const winningMessge = document.getElementById('winning-message')
const restart = document.getElementById('restart')
let nextTurn = 'x'
const winningCombos = [
  [0,1,2],
  [3,4,5],
  [6,7,8],
  [0,3,6],
  [1,4,7],
  [2,5,8],
  [0,4,8],
  [2,4,6]
]

restartGame()

board.addEventListener('click', (e) => {
  let icon = document.createElement('i')
  
  if (e.target.classList.contains('cell')) {

    if (board.classList.contains('x')) {
      icon.classList.add('fa-solid', 'fa-x')
      e.target.appendChild(icon)
      e.target.classList.add('x')
    }

    if (board.classList.contains('o')) {
      icon.classList.add('fa-solid', 'fa-o')
      e.target.appendChild(icon)
      e.target.classList.add('o')
    }
  }

  if (isDraw()) {
    winningMessge.innerText = 'Draw!'
    displayOutcome.classList.add('show')
  }

  if (checkWinner(nextTurn)) {
    winningMessge.innerText = `${nextTurn}'s Wins`
    displayOutcome.classList.add('show')
  }
  
  changeTurns()
  
  console.log(nextTurn)

})

function changeTurns() {
  if (nextTurn === 'x') {
    nextTurn = 'o'
    board.classList.replace('x', 'o')
  } else {
    nextTurn = 'x'
    board.classList.replace('o', 'x')
  }
}

function checkWinner (nextTurn) {
  return winningCombos.some(combo => {
    return combo.every(index => {
      return cell[index].classList.contains(nextTurn) 
    })
  })
}

function isDraw() {
  return [...cell].every(cell => {
    return cell.classList.contains('x') || cell.classList.contains('o')
  })
}

function restartGame() {
  cell.forEach(cell => {
    cell.innerHTML = ''
    displayOutcome.classList.remove('show')
    cell.classList.remove('o', 'x')
    board.classList.remove('o', 'x')
    board.classList.add('x')
  })
}


restart.addEventListener('click', restartGame)

我尝试在按下重新启动后将 x 类添加到我的板上,这应该将下一步设置为 x。

function restartGame() {
  cell.forEach(cell => {
    cell.innerHTML = ''
    displayOutcome.classList.remove('show')
    cell.classList.remove('o', 'x')
    board.classList.remove('o', 'x')
    board.classList.add('x')
  })
}

我查看了 devtools 中的元素选项卡,重置后我可以看到 x 的类在板元素上,但当 x 轮到它时,它不会切换到 o。

javascript dom-events 井字游戏

评论


答:

1赞 Yan Tavares 10/31/2023 #1

您应该在开始新游戏之前重置该变量。nextTurn

让我们来分解一下:

如果玩家 X 赢了,仍然包含存储在其中。但是,class 被设置为 ,因此玩家 X 有两回合。nextTurnOx

溶液:

function restartGame() {
  cell.forEach(cell => {
    cell.innerHTML = '';
    displayOutcome.classList.remove('show');
    cell.classList.remove('o', 'x');
    board.classList.remove('o', 'x');
    board.classList.add('x');
  });

  nextTurn = 'x';
}

如果这能解决您的问题,请告诉我!干杯!