【问题标题】:tic tac toe javascript answer checker井字游戏 javascript 答案检查器
【发布时间】:2017-01-24 21:49:46
【问题描述】:

我正在用 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>

这是将empty.jpg更改为cross.jpg或circle.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);

【问题讨论】:

  • 您可以将模型保存在 3,3 大小的矩阵上,并检查行、列或对角线是否可以获胜

标签: javascript jquery html


【解决方案1】:

React tutorial 实现了一个井字游戏,他们使用这个函数来检查谁赢了:

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;
}

来自starter source code

Squares 是从左到右、从上到下的九个方格的数组。它包含xo 用于已经填充的方块并返回获胜者的字母。

【讨论】:

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