我试图制作C ++ Tic Tac Toe游戏,但未获得正确的输出

时间:2019-03-16 20:10:48

标签: c++ turbo-c++

我试图编写一个c ++程序,但每次都得到错误的结果。

每当我分别指定x和y坐标2和3时,它都会将两个元素分配为“ X”,而不仅仅是一个。我已经尝试了很多次。

代码:

#include<iostream.h>
#include<conio.h>
void reset(char a[2][2])
{
    for(int i = 0; i < 3; i++)
        for(int j = 0; j < 3; j++)
            a[i][j] = '_';
}
void dispmat(char a[2][2])
{
    for (int k = 0; k < 3; k++)
    {
        for(int l = 0; l < 3; l++)
            cout << a[k][l] << '\t';
        cout << endl;
    }
}
void getcoordinates(int &x, int &y)
{
    cout << "Enter the row: "<< endl;
    cin >> x;
    cout << "Enter the column:" << endl;
    cin >> y;
    x--;
    y--;
}
void main()
{
    clrscr();
    char a[2][2],yon = 'y';
    int t = 2,x,y, flag = 0;
    do
    {
        reset(a);
        for(int h = 0; h < 9; h++)      // max no. of cells to be filled = 9
        {
            clrscr();
            dispmat(a);             // displays matrix
            if(t++%2 == 0)          // X's turn
            {
                cout << "It is X \'s chance now" << endl;
                getcoordinates(x,y);
                a[x][y] = 'x';
                for(int m = 0; m < 3; m++)
                    //if any one condition is true, x is declared the winner
                    if((a[m][0] == a[m][1] && a[m][1] == a[m][2] && a[m][2] == 'x')||(a[0][m] == a[1][m]&&a[1][m] == a[2][m] && a[2][m] == 'x')||(a[0][0] == a[1][1]&&a[1][1] == a[2][2] && a[2][2] == 'x')||(a[2][0] == a[1][1]&&a[1][1] == a[0][2] && a[0][2] == 'x'))
                    {
                        flag = -1;   //if flag = 1, x wins
                                 //if flag = -1, 0 wins
                                 // if flag = 0, its a draw
                        break;
                    }
                if (flag == -1||flag == 1)
                    break;
            }
            else              // 0's turn
            {
                cout << "It is 0 \'s chance now" << endl;
                getcoordinates(x,y);
                a[x][y] = '0';
                for(int n = 0; n < 3; n++)
                    if((a[n][0] == a[n][1] && a[n][1] == a[n][2] && a[n][2] == '0')||(a[0][n] == a[1][n]&&a[1][n] == a[2][n] && a[2][n] == '0')||(a[0][0] == a[1][1]&&a[1][1] == a[2][2] && a[2][2] == '0')||(a[2][0] == a[1][1]&&a[1][1] == a[0][2] && a[0][2] == '0'))
                    {
                        flag = 1;
                        break;
                    }
                if(flag == 1)
                    break;

            }
        }
        if(flag == 1)
            cout << "Winner is 0!" << endl;
        else if(flag == -1)
            cout << "Winner is X!" << endl;
        else
            cout << "It is a draw!" << endl;
        cout << "Do you want to continue?" << endl;
        cin >> yon;
    } while(yon == 'y' || yon == 'Y');
    getch();
}

1 个答案:

答案 0 :(得分:-1)

您的错误很简单: 您正在使用[2] [2]数组,但实际上需要[3] [3]数组。您可以使用[0],[1],[2]来索引数组,但是要定义其实际大小,则需要使用最大索引+ 1,

在这种情况下是char a[3][3]