井字 tac toe JavaScript 答案检查器



我正在用javascript/jquery制作一个简单的井字游戏,我不知道如何检查是否有人赢了。这是游戏场:

<div id="gamefield">
            <table border="0">
                <tr>
                    <td><img alt="" title="" src="img/empty.jpg" /></td>
                    <td><img alt="" title="" src="img/empty.jpg" /></td>
                    <td><img alt="" title="" src="img/empty.jpg" /></td>
                </tr>
                <tr>
                    <td><img alt="" title="" src="img/empty.jpg" /></td>
                    <td><img alt="" title="" src="img/empty.jpg" /></td>
                    <td><img alt="" title="" src="img/empty.jpg" /></td>
                </tr>
                <tr>
                    <td><img alt="" title="" src="img/empty.jpg" /></td>
                    <td><img alt="" title="" src="img/empty.jpg" /></td>
                    <td><img alt="" title="" src="img/empty.jpg" /></td>
                </tr>
            </table>
        </div>

这是将空.jpg更改为十字.jpg或圆.jpg的代码:

$("#gamefieldtr td").click( function (event) {
if($(".game-button").html() == "Reset game" && $(this).children().attr("src") == "img/empty.jpg") {
    if(randomStart == 0){
        var val = $(this).children().attr('src', 'img/cross.jpg');
        randomStart = 1;
        $(this).children().unbind("click");
    }
    else {
        var val = $(this).children().attr('src', 'img/circle.jpg');
        randomStart = 0;
        $(this).children().unbind("click");
    }
}
if ($(".game-button").html() == "Start game") {
    alert("you can't start");
}
});

这是随机启动代码:

var randomStart = Math.floor(Math.random() * 2);

React 教程实现了一个 TicTacToe 游戏,他们使用此函数来检查谁赢了:

function calculateWinner(squares) {
  const lines = [
    [0, 1, 2],
    [3, 4, 5],
    [6, 7, 8],
    [0, 3, 6],
    [1, 4, 7],
    [2, 5, 8],
    [0, 4, 8],
    [2, 4, 6],
  ];
  for (let i = 0; i < lines.length; i++) {
    const [a, b, c] = lines[i];
    if (squares[a] && squares[a] === squares[b] && squares[a] === squares[c]) {
      return squares[a];
    }
  }
  return null;
}

从起始源代码

正方形

是从左到右,从上到下的九个正方形的数组。它包含已填充方块的xo,并返回获胜者的字母。

最新更新