gpt4 book ai didi

Javascript - Tic Tac Toe - 如何遍历获胜条件?

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:16:14 25 4
gpt4 key购买 nike

我正在编写一个可以正常运行的井字游戏程序,我已经差不多完成了。除了我的胜利条件太长而且丑陋。看起来像这样。

function checkWin(){
if(board[0].textContent === "X" &&
board[1].textContent === "X" &&
board[2].textContent === "X"
) { alert("Win")}
else if (
board[3].textContent === "X" &&
board[4].textContent === "X" &&
board[5].textContent === "X"
) { alert("Win")}
else if (
board[6].textContent === "X" &&
board[7].textContent === "X" &&
board[8].textContent === "X"
) { alert("Win")}

}

我只写了几个获胜条件,因为如果我写了整个东西,它会更长。我想知道如何编写一个较短的版本。我正在考虑做一个数组并循环遍历它,但我不知道如何做。它将是这样的。

var winConditions = [[0,1,2], [3,4,5], [6,7,8], [0,3,6], [1,4,7], [2, 5,8], [0,4,8], [6,4,2]]

但是我如何使用 checkWin 遍历 winConditions 并使其等于 X 和 O?

最佳答案

使用 ES6

function checkWin(player){
// player = 'X' or 'O'

const horizontal = [0,3,6].map(i=>{return[i,i+1,i+2]});
const vertical = [0,1,2].map(i=>{return[i,i+3,i+6]});
const diagonal = [[0,4,8],[2,4,6]];

var allwins = [].concat(horizontal).concat(vertical).concat(diagonal);

let res = allwins.some(indices => {
return board[indices[0]] == player && board[indices[1]] == player && board[indices[2]] == player})
return res;
}
// O O O
// X X O
// X X O
var board=["X","X","O","X","X","O","O","O","O"];
console.log(checkWin("X"),"Expect: false"); // false
console.log(checkWin("O"),"Expect: true"); // true

// negative test case
var board = [];
console.log(checkWin("X"),"Expect: false"); // false

// wierd case of only 1 player
// X X X
var board = ["X","X","X"]
console.log(checkWin("X"),"Expect: true"); //true

关于Javascript - Tic Tac Toe - 如何遍历获胜条件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45703381/

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