Nicholas Hazel Nicholas Hazel - 1 month ago 19
Javascript Question

Very Specific Bug - Tic Tac Toe Tester

I provided WAY too much info last time, so I'll reduce it.

I have a tic-tac-toe program I'm writing, but before I introduce the AI, I need to fix this bug.

Use Case:




  • 4x4 grid

  • Selecting 3 on the right col, and either "index 2" or "index 3" for the bottom row.



Doing this produces a false win. I have tested this with EVERY other use case, and this is the only bug I've found so far. (images provided below):

enter image description here
enter image description here


It has to do with my checking system. I've provided the
array
it is testing for the
bug
, as well as the
code to find a win
.


var b = [ ["", "", "", "X"],
["", "", "", "X"],
["", "", "", "X"],
["", "", "X", ""] ]

function testWin() {
var len=b.length, r=0, c=0, dr=0, dl=0;
for(var i=0;i<len;i++){
c=0;
for(var j=0;j<len;j++){
(b[j][i]==="X") ? c++ : c=0;
(b[i][j]==="X") ? r++ : r=0;
if(b[i][j]==="X" && i<len-win+1){
dr=0; dl=0;
for(var z=0;z<win;z++){
(b[i+z][j+z]==="X") ? dr++ : dr=0;
(b[i+z][j-z]==="X") ? dl++ : dl=0;
}
}
if(c===win || r===win || dr===win || dl===win){
alert("YOU WIN!"); return true;
}
}
r=0;
}
}


(I know, lots of ternary operators... hopefully it makes sense still. I built it from scratch, so I can elaborate if anybody needs me to.)


Answer

You need to reset the column counter c each time the loop moves to the next column.

function testWin() {
    var len=b.length, r=0, c=0, dr=0, dl=0;
    for(var i=0;i<len;i++){
        c=0;
        for(var j=0;j<len;j++){
            (b[j][i]==="X") ? c++ : c=0;
            (b[i][j]==="X") ? r++ : r=0;
            if(b[i][j]==="X" && i<len-win+1){ dr=0; dl=0;
                for(var z=0;z<win;z++){ 
                    (b[i+z][j+z]==="X") ? dr++ : dr=0;
                    (b[i+z][j-z]==="X") ? dl++ : dl=0;
                }
            }
            if(c===win || r===win || dr===win || dl===win){ alert("YOU WIN!"); return true;}
        } r=0;
    }
}

EDIT: Here is a way to do it with only two loops:

function testWin() {
    var len=b.length, r=0, c=0, dr=0, dl=0;
    for(var i=0;i<len;i++){
        r=0, c=0, dr=0, dl=0;
        for(var j=0;j<len;j++){
            (b[j][i]==="X") ? c++ : c=0;
            (b[i][j]==="X") ? r++ : r=0;
            if(i+j<len){ z = i+j;} else{z = i+j-len, dr=0, dl=0;}
            (b[j][z]==="X") ? dr++ : dr=0;
            (b[j][len-1-z]==="X") ? dl++ : dl=0;
            if(c===win || r===win || dr===win || dl===win){ alert("YOU WIN!"); return true;}
        }
    }
}
Comments