LTC*_*ipp -4 c++ boolean tic-tac-toe
我正在制作一个tic-tac-toe控制台应用程序,我主要完成它.还有一些我要添加的东西,但我遇到了一个大问题.我有一个bool checkwin()函数,它应该看看游戏是否已经赢了,但由于某种原因,无论我的参数是否满足,这个函数总是返回true.这导致程序在第一次移动后结束.为什么这样做,我该如何解决?
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;
}
Run Code Online (Sandbox Code Playgroud)
它返回true,因为' '
它等于' '
- 也就是说,在第一次移动之后,你可以保证一行中的三个方格仍然是空的,你只测试方形值是否相等而不是它们是相等而不是空的.
一种可能的解决方法:
if (BSTAT.getsquarestatus("A1")!=' ' &&
BSTAT.getsquarestatus("A1")==BSTAT.getsquarestatus("A2") &&
BSTAT.getsquarestatus("A2")==BSTAT.getsquarestatus("A3"))
Run Code Online (Sandbox Code Playgroud)
您需要将此... != ' '
检查添加到每个条件,显然会更改您测试的特定方块.
这可能是显而易见的,但你只需要测试其中一个方块,因为如果第一个方块不是空的而其他方块等于它,那么显然其他方块也不是空的.
归档时间: |
|
查看次数: |
129 次 |
最近记录: |