TicTacToe win logic for NxN board

后端 未结 2 1366
误落风尘
误落风尘 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:48

    So, to do it programatically, you can use classes to keep track of what "set" each cell is in, i.e. "row1" or "col1":

    In i/j creation loops:

    cell.addClass('col' + j); // The cell is in column j
    cell.addClass('row' + i); // The cell is in row i
    if (i == j) {
        cell.addClass('dia0'); // The cell is in the down/right diagonal
    }
    if (j == SIZE - i - 1) {
        cell.addClass('dia1'); // The cell is in the up/right diagonal
    }
    

    Then, in win(), pass in the last cell clicked. For each class the cell belongs to, check if the number of cells with that class containing X (or O) is equal to the table size:

    win = function (clicked) {
        // Get all of the classes this cell belongs to
        var memberOf = clicked[0].className.split(/\s+/);
    
        // Check elements with the same class, and see if they contain "turn", i.e. X or O
        for (var i=0; i

    JSFiddle Demo

提交回复
热议问题