如何更新 "board" 变量数组,以便 X 和 O 的项轮流交替?顺便说一句,这是一个井字游戏

How do I update the "board" variable's array's so that the turns of X and O alternate in turns? Btw, this is a Tic Tac Toe Game

let board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
]


var square1 = document.getElementById("square1")
square1.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square1.innerHTML = "X"
        board[0].splice(0, 0, "X")
    } else {
        square1.innerHTML = "O"
        board[0].splice(0, 0, "O")
    }
    console.log(board)
})

var square2 = document.getElementById("square2")
square2.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square2.innerHTML = "X"
        board[0].splice(1, 1, "X")
    } else {
        square2.innerHTML = "O"
        board[0].splice(1, 1, "O")
    }
    console.log(board)
})

var square3 = document.getElementById("square3")
square3.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square3.innerHTML = "X"
        board[0].splice(2, 2, "X")
    } else {
        square3.innerHTML = "O"
        board[0].splice(2, 2, "O")
    }
    console.log(board)
})

var square4 = document.getElementById("square4")
square4.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square4.innerHTML = "X"
        board[1].splice(0, 0, "X")
    } else {
        square4.innerHTML = "O"
        board[1].splice(0, 0, "O")
    }
    console.log(board)
})

var square5 = document.getElementById("square5")
square5.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square5.innerHTML = "X"
        board[1].splice(1, 1, "X")
    } else {
        square5.innerHTML = "O"
        board[1].splice(1, 1, "O")
    }
    console.log(board)
})

var square6 = document.getElementById("square6")
square6.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square6.innerHTML = "X"
        board[1].splice(2, 2, "X")
    } else {
        square6.innerHTML = "O"
        board[1].splice(2, 2, "O")
    }
    console.log(board)
})

var square7 = document.getElementById("square7")
square7.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square7.innerHTML = "X"
        board[2].splice(0, 0, "X")
    } else {
        square7.innerHTML = "O"
        board[2].splice(0, 0, "O")
    }
    console.log(board)
})

var square8 = document.getElementById("square8")
square8.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square8.innerHTML = "X"
        board[2].splice(1, 1, "X")
    } else {
        square8.innerHTML = "O"
        board[2].splice(1, 1, "O")
    }
    console.log(board)
})

var square9 = document.getElementById("square9")
square9.addEventListener("click", function(turnMove){
    if ((turnMove % 2 === 0)) {
        square9.innerHTML = "X"
        board[2].splice(2, 2, "X")
    } else {
        square9.innerHTML = "O"
        board[2].splice(2, 2, "O")
    }
    console.log(board)
})



function turnMove(board) {
    turns = 0
    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            if (board[i][j]) {
                turns = turns + 1
            } else {
                turns = turns + 0
            }
        }
    }
    return turns
}
#board {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr  1fr;
    max-width: 40%;
    height: 40vw;
    margin: auto;
    border: 2px solid black;
    text-align: center;
  
}

.square {
    background-color: aliceblue;
    border: 1px solid black;
    
}

* {
    font-size: 2.5rem;
}
<html>
    <head>
        <title>Tic Tac Toe Game</title>
        <link rel="stylesheet" href="style.css">
        <meta name="viewport" content="width-device-width initial-scale=1">
    </head>

<body>
    <div id="board">
        <div id="square1" class="square"></div>
        <div id="square2" class="square"></div>
        <div id="square3" class="square"></div>
        
        <div id="square4" class="square"></div>
        <div id="square5" class="square"></div>
        <div id="square6" class="square"></div>
        
        <div id="square7" class="square"></div>
        <div id="square8" class="square"></div>
        <div id="square9" class="square"></div>
        <script type="text/javascript" src="script.js"></script>
    </div>
</body>

</html>

函数 turnMove 正在确定它在哪个移动中,并使用它允许 addEventListener 确定 innerHTML 和拼接是否将“X”或“O”添加到 div 和棋盘数组。

如何交替使用“X”和“O”?我需要更新董事会“状态”。我该怎么做?

let board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
]


var square1 = document.getElementById("square1")
square1.addEventListener("click", function(turnMove){
    if (turnMove % 2 === 0) {
        square1.innerHTML = "X"
        board[0].splice(0, 0, "X")
    } else {
        square1.innerHTML = "O"
        board[0].splice(0, 0, "O")
    }
    console.log(board)
})

// This code is applicable for the 9 squares.
// square2, square2, and so on...

function turnMove(board) {
    turns = 0
    for (let i = 0; i < board.length; i++) {
        for (let j = 0; j < board[i].length; j++) {
            if (board[i][j]) {
                turns = turns + 1
            } else {
                turns = turns + 0
            }
        }
    }
    return turns
}

这是我解决问题的方法。

1。编辑您的 turnMove()

您想在每次点击一个方块时增加转数。可以很简单,像这样:

let turns = 0;
const turnMove = () => turns++;

2。改变你的使用方式 turnMove()

您需要将 turnMove 作为 turnMove() 而不是 turnMove 的函数来调用。而yourSquareElement是on-click回调的一个参数,你可以把它的名字改成任何你想要的,但是你不能改变它的值。

square9.addEventListener("click", function(yourSquareElement){
    if((turnMove() % 2 === 0)){}
})

这是解决您问题的两件事。给您的一个提示是将变量放入 console.log() 以查看它们所持有的值。如果这样做,您将看到 yourSquareElement 实际上是一个 Event 对象,无论您给它起什么名字。

在此处查看我的演示:

let board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
]


var square1 = document.getElementById("square1")
square1.addEventListener("click", function(el){
    if(turnMove() % 2 === 0){
        square1.innerHTML = "X"
        board[0].splice(0, 0, "X")
    }else{
        square1.innerHTML = "O"
        board[0].splice(0, 0, "O")
    }
    console.log(board)
})

var square2 = document.getElementById("square2")
square2.addEventListener("click", function(el){
    if(turnMove() % 2 === 0){
        square2.innerHTML = "X"
        board[0].splice(1, 1, "X")
    }else{
        square2.innerHTML = "O"
        board[0].splice(1, 1, "O")
    }
    console.log(board)
})

var square3 = document.getElementById("square3")
square3.addEventListener("click", function(el){
    if(turnMove() % 2 === 0){
        square3.innerHTML = "X"
        board[0].splice(2, 2, "X")
    }else{
        square3.innerHTML = "O"
        board[0].splice(2, 2, "O")
    }
    console.log(board)
})

var square4 = document.getElementById("square4")
square4.addEventListener("click", function(el){
    if(turnMove() % 2 === 0){
        square4.innerHTML = "X"
        board[1].splice(0, 0, "X")
    }else{
        square4.innerHTML = "O"
        board[1].splice(0, 0, "O")
    }
    console.log(board)
})

var square5 = document.getElementById("square5")
square5.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square5.innerHTML = "X"
        board[1].splice(1, 1, "X")
    }else{
        square5.innerHTML = "O"
        board[1].splice(1, 1, "O")
    }
    console.log(board)
})

var square6 = document.getElementById("square6")
square6.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square6.innerHTML = "X"
        board[1].splice(2, 2, "X")
    }else{
        square6.innerHTML = "O"
        board[1].splice(2, 2, "O")
    }
    console.log(board)
})

var square7 = document.getElementById("square7")
square7.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square7.innerHTML = "X"
        board[2].splice(0, 0, "X")
    }else{
        square7.innerHTML = "O"
        board[2].splice(0, 0, "O")
    }
    console.log(board)
})

var square8 = document.getElementById("square8")
square8.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square8.innerHTML = "X"
        board[2].splice(1, 1, "X")
    }else{
        square8.innerHTML = "O"
        board[2].splice(1, 1, "O")
    }
    console.log(board)
})

var square9 = document.getElementById("square9")
square9.addEventListener("click", function(el){
    if((turnMove() % 2 === 0)){
        square9.innerHTML = "X"
        board[2].splice(2, 2, "X")
    }else{
        square9.innerHTML = "O"
        board[2].splice(2, 2, "O")
    }
    console.log(board)
})

let turns = 0;
const turnMove = () => turns++;
#board {
    display: grid;
    grid-template-columns: 1fr 1fr 1fr;
    grid-template-rows: 1fr 1fr  1fr;
    max-width: 40%;
    height: 40vw;
    margin: auto;
    border: 2px solid black;
    text-align: center;
  
}

.square {
    background-color: aliceblue;
    border: 1px solid black;
    
}

* {
    font-size: 2.5rem;
}
<html>
    <head>
        <title>Tic Tac Toe Game</title>
        <link rel="stylesheet" href="style.css">
        <meta name="viewport" content="width-device-width initial-scale=1">
    </head>

<body>
    <div id="board">
        <div id="square1" class="square"></div>
        <div id="square2" class="square"></div>
        <div id="square3" class="square"></div>
        
        <div id="square4" class="square"></div>
        <div id="square5" class="square"></div>
        <div id="square6" class="square"></div>
        
        <div id="square7" class="square"></div>
        <div id="square8" class="square"></div>
        <div id="square9" class="square"></div>
        <script type="text/javascript" src="script.js"></script>
    </div>
</body>

</html>

更新:我重构了您的脚本,使其更加简洁。

我将每个方块的所有 on-click 事件合并为一个,希望你觉得这有用。您现在的脚本是:

const board = [
    ["", "", ""],
    ["", "", ""],
    ["", "", ""]
];


let turns = 0;
const turnMove = () => turns++;
const squares = document.querySelectorAll('.square');

squares.forEach((thisSquare, index) => {
    const col = index % 3;
    const row = Math.floor(index / 3);

    thisSquare.addEventListener('click', () => {
        const player = turnMove() % 2 === 0 ? "X" : "O";

        thisSquare.innerHTML = player;
        board[row][col] = player;

        console.log(row, col, board);
    });
});

const board = [
  ["", "", ""],
  ["", "", ""],
  ["", "", ""]
];


let turns = 0;
const turnMove = () => turns++;
const squares = document.querySelectorAll('.square');

squares.forEach((thisSquare, index) => {
  const col = index % 3;
  const row = Math.floor(index / 3);

  thisSquare.addEventListener('click', () => {
    const player = turnMove() % 2 === 0 ? "X" : "O";

    thisSquare.innerHTML = player;
    board[row][col] = player;

    console.log(row, col, board);
  });
});
#board {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  max-width: 40%;
  height: 40vw;
  margin: auto;
  border: 2px solid black;
  text-align: center;
}

.square {
  background-color: aliceblue;
  border: 1px solid black;
}

* {
  font-size: 2.5rem;
}
<html>

<head>
  <title>Tic Tac Toe Game</title>
  <link rel="stylesheet" href="style.css">
  <meta name="viewport" content="width-device-width initial-scale=1">
</head>

<body>
  <div id="board">
    <div id="square1" class="square"></div>
    <div id="square2" class="square"></div>
    <div id="square3" class="square"></div>

    <div id="square4" class="square"></div>
    <div id="square5" class="square"></div>
    <div id="square6" class="square"></div>

    <div id="square7" class="square"></div>
    <div id="square8" class="square"></div>
    <div id="square9" class="square"></div>
    <script type="text/javascript" src="script.js"></script>
  </div>
</body>

</html>

作为最终结果在此处发布,这不是您问题的解决方案

@phucbm另一方面解释了你的代码有什么问题,这是你的解决方案,这只是你最终结果的指南

以此为指导,使用 @phucbm 的答案来解决您的问题

-

const emptyBoard = [
    ["-", "-", "-"],
    ["-", "-", "-"],
    ["-", "-", "-"]
];
// Break reference by stringify/parsing
let board = JSON.parse(JSON.stringify(emptyBoard));
const boardEl = document.querySelector('#board');

const createBoard = () => {
  boardEl.innerHTML = ''; // Reset board on win
  board.map((row, rowIndex) => {
      let rowHTML = ``;
      row.map((col, colIndex) => {
          rowHTML += `<div class="cell" data-row="${rowIndex}" data-col="${colIndex}"></div>`;
      });
      boardEl.innerHTML += `<div class="row">${ rowHTML }</div>`;
  });
}

createBoard(); // Init

const checkForWins = (row, col) => {
    // Check either diagonal or current row / col clicked
    const diagonalLeft = [ board[0][0], board[1][1], board[2][2] ];
    const diagonalRight = [ board[0][2], board[1][1], board[2][0] ];
    const currentRow = [board[row][0], board[row][1], board[row][2]];
    const currentCol = [board[0][col], board[1][col], board[2][col]];

    [ diagonalLeft, diagonalRight, currentRow, currentCol ].map((arr) => {
        const string = arr.join('');

        if (string === 'xxx' || string === 'ooo') {
            alert(string[0]+' wins!');
            board = JSON.parse(JSON.stringify(emptyBoard));
            createBoard();
        }
    })
};


let currentPlayer = "x";
boardEl.addEventListener('click', (evt) => {
    const row = evt.target.getAttribute('data-row');
    const col = evt.target.getAttribute('data-col');
    const isEmpty = evt.target.innerText === '';

    if (row && col && isEmpty) {
        board[ row ][ col ] = currentPlayer;
        evt.target.innerHTML = board[row][col];
        checkForWins(row, col);
        currentPlayer = currentPlayer === 'x' ? 'o' : 'x';
    }
})
#board {
    display: block;
}
#board .row { display: block; font-size: 0; }
#board .row .cell {
    display: inline-block;
    width: 30px;
    height: 30px;
    border: 1px solid #000;
    text-align: center;
    line-height: 30px;
    font-size: 15px;
    vertical-align: top;
}
<div id="board"></div>