JavaScript TicTacToe if… Winner detection

前端 未结 7 1624
借酒劲吻你
借酒劲吻你 2020-12-21 09:22

I just have a small problem.

The final assignment in my computer science class is to write a game of Tic-Tac-Toe in JavaScript. The game works by clicking on cells w

相关标签:
7条回答
  • 2020-12-21 10:04

    Assume 'squares' is a Array of Arrays of square size with 0 for not filled , 1 for player 1 (x) and -1 for the other player (O).

    e.g.

    let squares= Array(3).fill(Array(3).fill(0))
    

    would be the staring board.

    The following works for board size 1,2,3,4... where for a board of size n, n consecutive x's or o's need to be in a row, column or diagonal.

    Returns 0 if nobody won yet and 1 for player 1 and -1 for the other player.

    First defining two helper functions to make the code more readable.

    const add = (a, b) => a + b
    
    function sum(array){  
       return array.reduce(add);
    }
    
    function calculateWinner(squares) {
      // check for horizontal wins along rows and diagonals
      let winner = calculateWinnerInner(squares);
      if (winner !== 0) return winner;
      // check for possible vertical wins as well
      const stranspose = squares.map((col, i) => squares.map(row => row[i]));
      return calculateWinnerInner(stranspose);
    }
     
    function calculateWinnerInner(squares) {
      for (let r = 0; r < squares.length; r++) {
        if (squares[r].length === sum(squares[r])) {
          return 1;
        }
        if (squares[r].length === - sum(squares[r])) {
          return -1;
        }
      }
    
      const diagonal = squares.map((row, r) => squares[r][r]);
    
      if (squares[0].length === sum(diagonal)) {
        return 1;
      }
      if (squares[0].length === -sum(diagonal)) {
        return -1;
      }
      
     const len=squares.length;
     const crossdiagonal = squares.map((row, r) => squares[r][len-r-1]);
    
     if (squares[0].length === sum(crossdiagonal)) {
      return 1;
     }
     if (squares[0].length === -sum(crossdiagonal)) {
      return -1;
     }
    
      return 0;
    }

    0 讨论(0)
提交回复
热议问题