Tic-Tac-Toe计划

时间:2014-03-24 13:10:23

标签: c++ visual-studio-2012

我正在尝试创建一个Tic-Tac-Toe程序,该程序将确定给定的游戏板是否以“X”“O”或平局获胜。

显然我知道哪些游戏是谁赢了,但我怎么能让程序检查呢?

int check(int board[3][3]) {
//I've tried putting some code here, but nothing successful.  

return 0;
}

int main() {
// this is a three-dimensional array, three games of two-dimensional
// boards; just concern yourself about the two-dimensional boards
int games[3][3][3] = { 
    {  
        { -1,  0,  1 },  //O_X
        {  0,  1, -1 },  //_XO
        {  1, -1,  0 }   //XOX
    },
    {  
        {  0,  1,  1 },  //_XX
        { -1, -1, -1 },  //OOO
        {  1,  1,  0 }   //XX_
    },
    {  
        {  1,  1, -1 }, //XXO
        { -1, -1,  1 }, //OOX
        {  1,  1, -1 }  //XXO 
    }
};

for (int game = 0; game < 3; game++) {
    if (check(games[game]) == 1) {
        cout << "player X wins game " << game + 1 << endl;
    } else if (check(games[game]) == -1) {
        cout << "player O wins game " << game + 1 << endl;
    } else {
        cout << "game " << game + 1 << " is a cat game" << endl;
    }
}

    return 0;
}

1 个答案:

答案 0 :(得分:1)

这应该有效:

int check(int board[3][3]) {
     int winner = 0;

     // check line
     for( int i=0; i<3; ++i )
          { 
               if( board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != 0)
                    winner = board[i][0];  
          }

     // check column
     for( int i=0; i<3; ++i )
          { 
               if( board[0][i] == board[1][i] && board[1][i] == board[2][i] && board[0][i] != 0 )
                    winner = board[0][i];  
          }

     // check diagonal
     if( board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != 0)
          winner = board[1][1];

     if( board[2][1] == board[1][1] && board[1][1] == board[0][2] && board[1][1] != 0)
          winner = board[1][1];

return winner;
}