我正在创建一个tic tac toe游戏作为一个带有二维数组的项目,我在检查斑点时遇到了一些问题,看看是否有胜利者。有人可以帮我调试吗?这是checkwinner函数和main函数。
char CheckWinner( char board[3][3])
{
int i = 0;
int j = 0;
if ( board[i][j] =='X' && board[i][j+1] == 'X' && board[i][j+2]== 'X' )
{ W = X;}
else if (board[i+1][j] && board[i+1][i+1] && board[i+1][j+2]== 'X' )
{ W = X;}
else if (board[i+2][j] && board[i+2][j+1] && board[i+2][j+2]== 'X')
{ W = X;}
else if (board[i][j] && board[i+1][j] && board[i+2][j]== 'X')
{ W = X;}
else if (board[i][j+1] && board[i+1][j+1] && board[i+2][j+1]== 'X')
{ W = X;}
else if (board[i][j+2] && board[i+1][j+2] && board[i+2][j+2]== 'X')
{ W =X;}
else if (board[i][j] && board[i+1][j+1] && board[i+2][j+2]=='X')
{ W = X;}
else if (board[i+2][j] && board[i+1][j+1] && board[i][j+2]== 'X')
{ W = X;}
else if (board[i][j] && board[i][j+1] && board[i][j+2]== 'O' )
{ W = O;}
else if (board[i+1][j] && board[i+1][j+1] && board[i+1][j+2]== 'O')
{ W = O;}
else if (board[i+2][j] && board[i+2][j+1] && board[i+2][j+2]== 'O')
{ W = O;}
else if (board[i][j] && board[i+1][j] && board[i+2][j]== 'O')
{ W = O;}
else if (board[i][j+1] && board[i+1][j+1] && board[i+2][j+1]== 'O')
{ W = O;}
else if (board[i][j+2] && board[i+1][j+2] && board[i+2][j+2]== 'O')
{ W = O;}
else if (board[i][j] && board[i+1][j+1] && board[i+2][j+2]== 'O')
{ W = O;}
else if (board[i+2][j] && board[i+1][j+1] && board[i][j+2]== 'O')
{ W = O;}
return W;
}
int main ()
{
char board[3][3];
char Win = CheckWinner(board);
int r = 0;
InitializeBoard(board);
for (int r = 0; r < 4 ; r++)
{
PlayX(board);
PlayO(board);
PrintBoard(board);
}
CheckWinner(board);
cout << Win ;
if (Win == X)
{
cout << "The winner is Player 1.";
}
else if (Win == O)
{
cout << "The winner is Player 2.";
}
else if (Win == TIE)
{
cout << " IT'S A TIE";
}
else;
system("PAUSE");
return 0;
答案 0 :(得分:3)
您可以使用以下内容优化条件代码:
typedef char piece;
piece iswin() const
{
piece ret = 'T';
// Checks for horizontal win
for (int i = 0; i < 3; ++i)
if (*arr[i] == arr[i][1] && arr[i][1] == arr[i][2])
if ((ret = *arr[i]) != 'T')
return ret;
// Checks for vertical win
for (int i = 0; i < 3; ++i)
if (arr[0][i] == arr[1][i] && arr[1][i] == arr[2][i])
if ((ret = arr[0][i]) != 'T')
return ret;
// Check for diagonal win (upper left to bottom right)
if (**arr == arr[1][1] && arr[1][1] == arr[2][2])
if ((ret = **arr) != 'T')
return ret;
// Check for diagonal win (upper right to bottom left)
if (arr[0][2] == arr[1][1] && arr[1][1] == arr[2][0])
if ((ret = arr[0][2]) != 'T')
return ret;
return ret;
}
// checking the result:
switch (winner) {
case 'T': /* tie */ break;
case 'X': /* X won */ break;
case 'O': /* O won */ break;
}
这有点清洁。它会做6个循环而不是9个循环。
答案 1 :(得分:1)
您立即将CheckWinner
结果分配给Win
,然后玩游戏,然后再次致电CheckWinner
,而不将结果分配给Win
。因此,当您检查以下行中的Win
时,您将获得原始结果,即电路板甚至未初始化时。
答案 2 :(得分:0)
可能与将文字O或X分配到应该是char的返回值有关。因此,代替O或X,它应该是'O'或'X'。除非在发布的代码之外将O或X定义为char变量。