Writing a check for an array to determine if it has potential sequential values
, be it horizontal
, vertical
or in any case diagonal
. Below is an example of a diagonal, but I need it to work in both directions /
and \
.
So let's make a fake script ...
var b = [ [ 0, 0, X, 0, 0 ] [ 0, 0, 0, X, 0 ] [ 0, 0, 0, 0, X ] [ 0, 0, 0, 0, 0 ] [ 0, 0, 0, 0, 0 ] ]
Using a basic 2-level deep loop that iterates through the whole subject and uses several ternary operators to determine the βwinningsβ
function testWin() { var win=3, len=b.length, r=0, c=0, dr=0, dl=0; for(var i=0;i<len;i++){ for(var j=0;j<len;j++){ // COL WIN CHECK // (b[j][i]==="X") ? c++ : c=0; // ROW WIN CHECK // (b[i][j]==="X") ? r++ : r=0; // DIAG WIN CHECK // // (b[i][j]==="X" && b[i+1][j+1]==="X") ? dr++ : dr=0; // (b[j][i]==="X" && b[i+1][j+1]==="X") ? dl++ : dl=0; // WIN CHECK FOR ALL 4 if(c===win || r===win){ alert("YOU WIN!"); return true;} } r=0; } }
horizontal check
and vertical check
seem flawless until I turn on commented attempts to create a diagonal test ... Can I ask someone to look at the diagonal tests and help determine why they allow me to break everything and what I did wrong?
I would like to help with this, in particular, create a diagonal
check. (view JSFiddle for the whole source)
// DIAG WIN CHECK // // (b[i][j]==="X" && b[i+1][j+1]==="X") ? dr++ : dr=0; // (b[j][i]==="X" && b[i+1][j+1]==="X") ? dl++ : dl=0;
NEW COMMENT I tried this, for example, but it is hardcoded for diagonal 3 (I need it to expand later to use the win
variable). When I add this, the lower right corner of my horizontal
and vertical
tags fails.
// if((b[i][j] && b[i+1][j+1] && b[i+2][j+2])==="X"){ alert("YOU WON! Diag1"); return true; } // if((b[i][j] && b[i+1][j-1] && b[i+2][j-2])==="X"){ alert("YOU WON! Diag2"); return true; }
I know that this has something to do with dl and dr values ββthat are not being restored correctly, and also affect other horizontal and vertical tests, but I have lost an effective way to solve it.