gpt4 book ai didi

javascript - 井字棋 javascript 答案检查器

转载 作者:行者123 更新时间:2023-12-03 05:10:46 25 4
gpt4 key购买 nike

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

最佳答案

React tutorial实现了 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;
}

来自 starter source code

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

关于javascript - 井字棋 javascript 答案检查器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41829688/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com