TicTacToe win logic for NxN board

后端 未结 2 1369
误落风尘
误落风尘 2021-01-14 10:29

Current logic works fine with 3x3 board because it is static. How can I convert it into NxN logic?

Win logic works by adding the row and column squares.



        
2条回答
  •  无人共我
    2021-01-14 10:47

    This matches your list for three, and I've checked two by hand. It certainly seems right, as the code is really dead simple, but you'll probably want to check it over:

    var getWins = function(size) {
        var val = 1, cells = [], wins = [];
        for (var i = 0; i < size; i++) {
            cells[i] = [];
            for (var j = 0; j < size; j++) {
                cells[i][j] = val;
                val *= 2;
            }
        }
        var rowWins = [], colWins = [], mainDiagWin = 0, antiDiagWin = 0;
        for (i = 0; i < size; i++) {
            rowWins[i] = 0;
            colWins[i] = 0;
            mainDiagWin += cells[i][i];
            antiDiagWin += cells[i][size - i - 1];
            for (j = 0; j < size; j++) {
                rowWins[i] += cells[i][j];
                colWins[i] += cells[j][i];
            }
        }
        return rowWins.concat(colWins, mainDiagWin, antiDiagWin);
    };
    
    getWins(2);
    //=> [3, 12, 5, 10, 9, 6]
    
    getWins(3);
    //=> [7, 56, 448, 73, 146, 292, 273, 84]
    
    getWins(4)
    //=> [15, 240, 3840, 61440, 4369, 8738, 17476, 34952, 33825, 4680]
    

提交回复
热议问题