如何计算井字游戏的赢家?

How to calculate a tic tac toe winner?

所以我是初学者,我想知道是否可以生成这些组合。每个教程都有确切的组合,但生成这些组合不是更好吗?我想做 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;
}