A small syntactic problem in javascript- Tic Tac Toe
this is part of code in javascript for a Tic Tac Toe game. this part is checking win for diagonal in both directions. The diagonals work in X's winning but they do not work in O's winning. I basically wrote the same thing so I'm not sure what's the mistake I made. Did I make some syntactic mistake?
function CheckWin_Diagonal(rowClicked, colClicked) {
if (rowClicked == colClicked) {
for (c = 0; c < rows; c++) {
if (intBoard[c][c] != X_CLASS)
break;
if (c == rows - 1) {
alert("PLAYER X WIN!!");
document.location.reload()
}
}
}
else {
if (rowClicked == colClicked) {
for (c = 0; c < rows; c++) {
if (intBoard[c][c] != CIRCLE_CLASS)
break;
if (c == rows - 1) {
alert("PLAYER O WIN!!");
}
}
}
}
}
function CheckWin_Diagonal2(rowClicked, colClicked) {
if (rowClicked + colClicked == cols - 1) {
for (r = 0; r < cols; r++) {
if (intBoard[r][(cols - 1) - r] != X_CLASS)
break;
if (r == cols - 1) {
alert("PLAYER X WIN!!");
document.location.reload()
}
}
}
else {
if (rowClicked + colClicked == cols - 1) {
for (r = 0; r < cols; r++) {
if (intBoard[r][(cols - 1) - r] != CIRCLE_CLASS)
break;
if (r == cols - 1) {
alert("PLAYER O WIN!!");
}
}
}
}
}
Solution 1:
I haven't seen the logic at all, but you are doing:
function CheckWin_Diagonal(rowClicked, colClicked) {
if (rowClicked == colClicked) {
/** logic **/
}
else {
if (rowClicked == colClicked) {
/** logic **/
}
}
}
Obviously the code in the second if
will never execute because it's the same condition as the first one (so it'll never get there).
You are basically saying:
IF SOMETHING HAPPENED DO THIS, OTHERWISE IF THE SAME THING HAPPENED DO THAT
So THAT
will never happen, because you trapped the condition in the first IF
and there's no OTHERWISE
for the exact same condition
Solution 2:
Your else
blocks run the same if
condition that triggered the else
in the first place, guaranteeing they'll never run.