Writing a check for an array to determine if there are any potential consecutive values within it, be it horizontal, vertical, or either way diagonal. The example below is a sample diagonal, but I need it working both ways / and \.
Fiddle Away: http://jsfiddle.net/PXPn9/10/
So let's make a pretend scenario...
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, which iterates over the whole thing and uses some ternary operators to identify "wins"
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;
}
}
The horizontal check and the vertical check appear to work flawlessly, until I enable the commented attempts to create a diagonal test... Could I have somebody take a look at the diagonal tests and help identify why enabling them breaks everything, and what I have done wrong?
I would like assistance with this in particular to create a diagonal check. (view JSFiddle for 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;
Fiddle Away: http://jsfiddle.net/PXPn9/10/
NEW COMMENT
I've tried this, for example, but it is hard coded for a diagonal of 3 (I need it to expand later to use the win variable). When I add this though, the bottom right corner of my horizontal and vertical checks 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 it has something to do with the values of dl and dr aren't resetting properly, and its affecting the other horizontal and vertical tests, but I'm a tad lost of an effective way to solve it.
dlanddraren't resetting properly, and its affecting the otherhorizontalandverticaltests, but I'm a tad lost of an effective way to do it.