我正在创建一个游戏井字游戏作为一个项目与一个二维数组,我有一些麻烦检查点,看看是否有一个赢家。有人能帮我调试这个吗?下面是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;
您可以使用以下方法优化条件代码:
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次。
您立即将CheckWinner
的结果分配给Win
,然后进行游戏,然后再次调用CheckWinner
,而不将其结果分配给Win
。因此,当您检查下一行中的Win
时,您将获得板甚至未初始化时的原始结果。
可能与将文字0或X赋值到应该是char的返回值有关。因此,它应该是'O'或'X',而不是'O'或'X'。除非O或X在发布的代码之外被定义为字符变量