I am making a tic-tac-toe console application and I have it mostly finished. There's a few more things I will add to it, but I am running into a big problem. I have a bool checkwin() function that is supposed to see if the game has been won, but for some reason this function is always returning true whether or not my parameters have been met. This causes the program to end after the first move has been made. Why is it doing this and how can I fix it?
bool checkwin( Boardstatus& BSTAT)
{
//Row 'A' checkwin
if (BSTAT.getsquarestatus("A1")==BSTAT.getsquarestatus("A2") && BSTAT.getsquarestatus("A2")==BSTAT.getsquarestatus("A3"))
{
return true;
}
//Row 'B' checkwin
else if (BSTAT.getsquarestatus("B1")==BSTAT.getsquarestatus("B2") && BSTAT.getsquarestatus("B2")==BSTAT.getsquarestatus("B3"))
{
return true;
}
//Row 'C' checkwin
else if (BSTAT.getsquarestatus("C1")==BSTAT.getsquarestatus("C2") && BSTAT.getsquarestatus("C2")==BSTAT.getsquarestatus("C3"))
{
return true;
}
//Column 1 checkwin
else if (BSTAT.getsquarestatus("A1")==BSTAT.getsquarestatus("B1") && BSTAT.getsquarestatus("B1")==BSTAT.getsquarestatus("C1"))
{
return true;
}
//Column 2 checkwin
else if (BSTAT.getsquarestatus("A2")==BSTAT.getsquarestatus("B2") && BSTAT.getsquarestatus("B2")==BSTAT.getsquarestatus("C2"))
{
return true;
}
//Column 3 checkwin
else if (BSTAT.getsquarestatus("A3")==BSTAT.getsquarestatus("B3") && BSTAT.getsquarestatus("B3")==BSTAT.getsquarestatus("C3"))
{
return true;
}
//Diagonal upper-left->bottom-right checkwin
else if (BSTAT.getsquarestatus("A1")==BSTAT.getsquarestatus("B2") && BSTAT.getsquarestatus("B2")==BSTAT.getsquarestatus("C3"))
{
return true;
}
//Diagonal lower-left->upper-right checkwin
else if (BSTAT.getsquarestatus("C1")==BSTAT.getsquarestatus("B2") && BSTAT.getsquarestatus("B2")==BSTAT.getsquarestatus("A3"))
{
return true;
}
else
{
return false;
}
}
int main()
{
//Start of initializing all squares as a blank
Boardstatus BSTAT;
BSTAT.setsquarestatus( "A1", ' ' );
BSTAT.setsquarestatus( "A2", ' ' );
BSTAT.setsquarestatus( "A3", ' ' );
BSTAT.setsquarestatus( "B1", ' ' );
BSTAT.setsquarestatus( "B2", ' ' );
BSTAT.setsquarestatus( "B3", ' ' );
BSTAT.setsquarestatus( "C1", ' ' );
BSTAT.setsquarestatus( "C2", ' ' );
BSTAT.setsquarestatus( "C3", ' ' );
//End of square initialization
do
{
playerturn(BSTAT);
} while (checkwin(BSTAT) == false);
return 0;
}
It returns true because
' '
is equal to' '
-- that is, after the first move you are guaranteed that three squares in a row will still be empty and you only test if the square values are equal and not that they are equal and not empty.One possible way to fix this:
You would need to add this
... != ' '
check to every conditional, obviously changing the particular square you test.This may be obvious, but you only have to test one of the squares because if the first square isn't empty and the others are equal to it, then obviously the other squares are not empty either.