【发布时间】:2021-08-15 23:28:14
【问题描述】:
我一直试图找出为什么我的井字游戏没有按照我想要的方式进行检查。由于我一直在看教程,但仍然无法弄清楚当玩家赢得游戏时正确使函数winning 运行的逻辑。
这里我尝试将 O 或 X 推送到数组中,并使用 console.log 来查看它的样子以及获胜条件检查不起作用的原因。
spaces.push[id];
console.log(spaces);
我还尝试了其他方法来使程序正确,例如使用预先制作的获胜条件并映射当前数组,但也无法正常工作......
const winningCondition = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
];
对于单元格,我在 HTML 中创建 9 个 div,并在 CSS 中使用网格系统。
非常感谢您的帮助!下面是井字游戏的 JavaScript 代码:
const winning = (player) => {
if (spaces[0] === player) {
if (spaces[1] === player && spaces[2] === player) return true;
if (spaces[3] === player && spaces[6] === player) return true;
if (spaces[4] === player && spaces[8] === player) return true;
}
if (spaces[8] === player) {
if (spaces[2] === player && spaces[5] === player) return true;
if (spaces[6] === player && spaces[7] === player) return true;
}
if (spaces[4] === player) {
if (spaces[1] === player && spaces[7] === player) return true;
if (spaces[3] === player && spaces[5] === player) return true;
}
};
【问题讨论】:
-
请提供重现问题所需的所有代码。见minimal reproducible example。
-
请也添加 HTML。我想知道为那些
.cell元素设置了哪些 ID? -
回答问题:
What is 'spaces' and how information is stored there?应该有助于解决问题。 -
你可以尝试制作一个codepen或jsfiddle吗?