使用 Javascript TicTacToe 游戏的 <H1> TAG HTML 问题

问题描述 投票:0回答:1

我正在制作井字棋游戏,现在正在执行获胜者功能。一名玩家获胜后,我的 h1(玩家)应该说

${playerOne} Won
${PlayerTwo} Won
但这并没有发生。当某人获胜后,h1不会改变,它继续“轮到玩家一”,“轮到玩家二”)

const cells = document.querySelectorAll(`.cell`);
let playerOne = "";
let playerTwo = "";
let currentPlayer = false;
let submitOne = false
let submitTwo = true
let board = ["", "", "", "", "", "", "", "", ""];
let winCombinations = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6]
];
const players = document.getElementById(`h1Id`)

function game() {
  document.getElementById("submitNameOne").addEventListener("click", () => {
    playerOne = document.getElementById("playerOne").value;
    submitOne = true
  });

  document.getElementById(`submitNameTwo`).addEventListener(`click`, () => {
    playerTwo = document.getElementById("playerTwo").value;
    submitTwo = true
    checkSubmit()
  })


  cells.forEach((cell, index) => {
    cell.addEventListener(`click`, () => {
      if (board[index] === ``) {
        board[index] = currentPlayer;
        if (currentPlayer === false) {
          cell.textContent = `X`;
          currentPlayer = true;
          checkWinner()
          players.textContent = `Vez de ${playerTwo}`
        } else {
          players.textContent = `Vez de ${playerOne}`
          currentPlayer = playerTwo;
          cell.textContent = `O`;
          currentPlayer = false;
        }
      }
    });
  });
}


function checkWinner() {
  for (let combination of winCombinations) {
    let [a, b, c] = combination.map(index => board[index])
    // O map irá iterar sobre os índices que
    // foram presentes na combinaçao específica. Se o index da jogada foi, por ex, 3, 4, 5
    // combination é igual a 3,4,5 e o index [3,4,5,] que é responsável por verificar se os
    // quadrados foram preenchidos

    if (a !== `` && a === b && b === c) {
      // se os valores forem iguais e não vazios, temos um vencedor
      if (a === `X`) {
        players.textContent = `${playerOne} Won!`
      } else {
        players.textContent = `${playerTwo} Won!`
      }
    }
  }

}

function checkSubmit() {
  if (submitOne && submitTwo === true) {
    players.textContent = `Vez de ${playerOne}`
  }
}

game();
.board {
  display: grid;
  grid-template-columns: repeat(3, 100px);
  grid-template-rows: repeat(3, 100px);
  gap: 5px;
  margin: 50px auto 0 auto;
  /* Adicionado margem inferior de 0 */
  max-width: fit-content;
  /* Adicionada essa linha */
}

.cell {
  background-color: #ddd;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 48px;
  font-weight: bold;
  cursor: pointer;
}

body {
  display: flex;
  /* Adicionar essa linha */
  justify-content: center;
  /* Adicionar essa linha */
  align-items: center;
  /* Adicionar essa linha */
  min-height: 100vh;
  /* Adicionar essa linha */
  margin: 0;
  /* Adicionar essa linha */
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Jogo da Velha</title>
  <link rel="stylesheet" href="index.css">
</head>

<body>


  <br> <br>

  <div id="textContent">

    <label for="playerOne">Player Um:</label>
    <input type="text" name="" id="playerOne">
    <button type="submit" id="submitNameOne">Submit</button>

    <label for="playerTwo">Player Dois:</label>
    <input type="text" name="" id="playerTwo">
    <button type="submit" id="submitNameTwo">Submit</button>
    <button type="submit">Restart</button>
  </div>

  <div class="board">
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
    <div class="cell"></div>
  </div>


  <div>
    <br> <br>
    <h1 id="h1Id">Quem são os jogadores?</h1>
  </div>

  <script src="index.js" defer></script>

</body>

</html>

javascript tic-tac-toe
1个回答
0
投票

您在

players.textContent
调用之后更新
checkWinner()
,这将放弃在
players.textContent
函数中对
checkWinner
所做的任何更改。

checkWinner()
players.textContent = `Vez de ${playerTwo}`

简单的解决方案是让

checkWinner
在找到获胜者时返回
true
,并在设置
checkWinner
之前检查
players.textContent = "Vez de ${playerTwo}"

if (!checkWinner())
  players.textContent = `Vez de ${playerTwo}`

但是,我建议重构您的代码以使其更具可读性并重命名变量。例如玩家一 -> 玩家X,玩家二 -> 玩家O。

board[index] = isTurnOfPlayerX;
if (isTurnOfPlayerX) {
  currentPlayer = playerX;
  cell.textContent = `X`;
} else {
  currentPlayer = playerO;
  cell.textContent = `O`;
}

if (checkWinner()) {
  players.textContent = `${currentPlayer} Won!`
} else {
  players.textContent = `Vez de ${currentPlayer}`
}
isTurnOfPlayerX = !isTurnOfPlayerX
© www.soinside.com 2019 - 2024. All rights reserved.