多维循环辅助

时间:2014-01-07 01:46:05

标签: javascript jquery arrays multidimensional-array

尝试在这种数组中检查可能的组合:

[ ["X","X","X"], ["","",""], ["","",""] ]

组合包括: tic tac toe logic

所以,这些是true

[ ["X","",""], ["","X",""], ["","","X"] ]

[ ["","","X"], ["","X",""], ["X","",""] ]

[ ["","X",""], ["","X",""], ["","X",""] ]

到目前为止,只要我的array[0][0]是所选择的选项之一,我就会工作,但我觉得我正朝着code堆栈迈进

function testWin(){
    var cs=b.length, ph=0, pv=0, pd=0;
    for(var i=0;i<cs;i++){
        if(b[0][i]==="X"){ ph++; }
        if(b[i][0]==="X"){ pv++; }
        if(b[i][i]==="X"){ pd++; }
    }
    if(ph===cs || pv===cs || pd===cs){ alert("YOU WIN!"); }
}

小提琴:http://jsfiddle.net/z4XLj/

  1. 正在尝试另一个for loop无法识别0
  2. 尝试while loop,但它崩溃了,我认为这不是最有效的。
  3. 需要查找是否......
    • ANY array[i][this]只包含X
    • ANY array[this][i]只包含X

2 个答案:

答案 0 :(得分:1)

我现在看起来像黑魔法,但是你有:

function testWin(){
    var cs = b.length, I = [], J = [], d = [0, 0];
    for(var i=0; i<cs; i++){
       for(var j=0; j<cs; j++){
           if(b[i][j] != 'X') continue;
           I[i] = (I[i] || 0) + 1;
           J[j] = (J[j] || 0) + 1;
           if(i == j) d[0]++;  //Diagonal \
           if(i == cs-j-1) d[1]++;  //Diagonal /
       }
    }
    if(d.concat(I).concat(J).indexOf(cs) >=0) alert("You win");
}

jsfiddle:http://jsfiddle.net/edgarinvillegas/z4XLj/3/

它考虑任何尺寸的棋盘的任何水平,垂直或对角线胜利

:O它有效! :)

来自玻利维亚拉巴斯的欢呼声

答案 1 :(得分:0)

function testWin() {
    var xCount;
    var rowsCount = b.length;
    // First check rows
    for (var row = 0; row < rowsCount; row++) {
        xCount = 0;
        colsCount = b[row].length;
        for (var col = 0; col < colsCount; col++) {
            if (b[row][col] == "X") {
                xCount++;
            } else {
                break;
            }
        }
        if (xCount == colsCount) {
            alert ("YOU WIN!");
            return true;
        }
    }
    // Now check columns -- just invert the above nested loops
    colsCount = b[0].length;
    for (var col = 0; col < colsCount; col++) {
        xCount = 0;
        for (var row = 0; row < rowsCount; row++) {
            if (b[row][col] == "X") {
                xCount++;
            } else {
                break;
            }
        }
        if (xCount == rowsCount) {
            alert ("YOU WIN!");
            return true;
        }
    }
    // Check diagonals
    if (b[1][1] == "X" && 
        ((b[0][0] == "X" && b[2][2] == "X") || (b[0][2] == "X" && b[2][0] == "X"))) {
        alert ("YOU WIN!");
        return true;
    }
    return false;
}