javascript - NxN 棋盘的 TicTacToe 获胜逻辑

标签 javascript jquery algorithm

电流逻辑适用于 3x3 板,因为它是静态的。 如何将其转换为 NxN 逻辑?

Win 逻辑通过添加行和列方 block 来工作。

/*
 * To determine a win condition, each square is "tagged" from left
 * to right, top to bottom, with successive powers of 2.  Each cell
 * thus represents an individual bit in a 9-bit string, and a
 * player's squares at any given time can be represented as a
 * unique 9-bit value. A winner can thus be easily determined by
 * checking whether the player's current 9 bits have covered any
 * of the eight "three-in-a-row" combinations.
 *
 *     273                 84
 *        \               /
 *          1 |   2 |   4  = 7
 *       -----+-----+-----
 *          8 |  16 |  32  = 56
 *       -----+-----+-----
 *         64 | 128 | 256  = 448
 *       =================
 *         73   146   292
 *
 */
wins = [7, 56, 448, 73, 146, 292, 273, 84],

/*
 * Returns whether the given score is a winning score.
 */
win = function (score) {
    for (var i = 0; i < wins.length; i += 1) {
        if ((wins[i] & score) === wins[i]) {
            return true;
        }
    }
    return false;
},

我的 fiddle 是 here

最佳答案

因此,要以编程方式执行此操作,您可以使用类来跟踪每个单元格所在的“集合”,即“row1”或“col1”:

i/j 创建循环中:

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
}

然后,在 win() 中,传入最后单击的单元格。对于单元格所属的每个类,检查该类包含 X(或 O)的单元格数是否等于表格大小:

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<memberOf.length; i++) {
        var testClass = '.'+memberOf[i];
        // If the number of elements containing "turn" == SIZE,
        // we have a winning condition
        if( $('#tictactoe').find(testClass+':contains('+turn+')').length == SIZE) {
             return true;   
        }
    }

    return false;
},

JSFiddle Demo

关于javascript - NxN 棋盘的 TicTacToe 获胜逻辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20578372/

相关文章:

javascript - 在没有 jQuery UI 的情况下获取拖动位置

有效绘制树木的算法?

algorithm - 从另一个点有效地找到最近的点

javascript - 高度自动在左侧菜单中不起作用

javascript - 基于数据表 Jquery 的插件 - 表 - 表中可折叠的问题 - Javascript/HTML

jquery - 在 chrome 上返回 AJAX 调用后,用于分页的 CSS 将无法工作

javascript - 收缩箱

javascript - 构建 Angular 项目后图像未显示

javascript - 使用ajax从chartjs填充动态饼图

Javascript 函数存储在数组中与存储在变量中