如何计算井字游戏的获胜者



所以我是一个初学者,我想知道是否有可能生成这些组合。每个教程都有确切的组合,但生成这些组合不是更好吗?我想做10x10的正方形,但键入所有这些组合肯定会让我发疯。

function calculateWinner(squares: any[]) {
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;
}

假设你的TicTacToe仍然需要一名玩家完成一整行,你可以简单地将每一行、每一列和每一对角线相加,其中值1表示玩家一,值-1表示玩家二,最后检查,如果其中一个和等于你的棋盘尺寸。

// this function calculates the winner of a tic tac toe game of size nxn
// squares being 'X', 'O' or ' '
function calculateWinner(squares: string[], dimension: number): any {
const rows = new Array(dimension).fill(0);
const cols = new Array(dimension).fill(0);
const diag = new Array(2).fill(0);
// loop over each cell of the board
for (let row = 0; row < dimension; row++) {
for (let col = 0; col < dimension; col++) {
// get the element via index calculation y * width + x 
const square = squares[row * dimension + col];
// increment for player one
if (square === "X") {
rows[row]++;
cols[col]++;
}
// decrement for player two
else if (square === "O") {
rows[row]--;
cols[col]--;
}
// check diagonal
if (row === col) 
diag[0] += square === "X" ? 1 : -1;
// check anti diagonal
if (row === dimension - col - 1) 
diag[1] += square === "X" ? 1 : -1;
}
}
// check if any of the rows or columns are completed by either player
for (let i = 0; i < dimension; i++) {
// row/col contains the value of the dimension
// if and only if the whole row/col only contains 'X' values
// and therefore get incremented each time a cell
// in that row/col gets looked at above
if (rows[i] === dimension || cols[i] === dimension) 
return "X";
else if (rows[i] === -dimension || cols[i] === -dimension) 
return "O";
}
// same as with the rows/cols but since there are only two diagonals,
// do this right here
if (diag[0] === dimension || diag[1] === dimension) 
return "X";
else if (diag[0] === -dimension || diag[1] === -dimension) 
return "O";
// otherwise no winner is found
return null;
}

最新更新