首页 > 解决方案 > C++ 故障检测二维数组中的冲突

问题描述

我正在做一个简单的井字游戏。我的checkCollision功能有一些错误。这是功能:

void checkCollision(const int rows, const int cols, char ticTacToe [][3])
{
    //code to check for collision between x and o
    for (int row = 0; row < rows; row++)
    {
        for (int col = 0; col < cols; col++)
        {
            if (ticTacToe[row][col] != '.') 
            {
                std::cout << "Collision detected. Please try again.\n";
            }
        }
    }
}

这是我的main功能。

int main()
{

    //create 2d array
    char ticTacToe[3][3] = { 
        {'.', '.', '.'},
        {'.', '.', '.'},
        {'.', '.', '.'},
    };

    //declare variables
    const int numRows{ 3 };
    const int numCols{ 3 };
    const int playerOne{ 1 };
    const int playerTwo{ 2 };
    int rowCordinate{};
    int colCordinate{};
    bool hasWon{};

    //print grid
    for (int row = 0; row < numRows; row++)
    {
        for (int col = 0; col < numCols; col++)
        {
            std::cout << ticTacToe[row][col];
        }

        std::cout << "\n";
    }

    //game loop
    do {
        std::cout << "\nPlayer one, please put in a row co-ordinate:\t";
        std::cin >> rowCordinate;

        std::cout << "\nPut in a column co-ordinate:\t";
        std::cin >> colCordinate;

        checkCollision(numRows, numCols, ticTacToe);
        changeArray(numRows, numCols, rowCordinate, colCordinate, ticTacToe, playerOne);
        

        std::cout << "\nPlayer two, please put in a row co-ordinate:\t";
        std::cin >> rowCordinate;

        std::cout << "\nPut in a column co-ordinate:\t";
        std::cin >> colCordinate;

        checkCollision(numRows, numCols, ticTacToe);
        changeArray(numRows, numCols, rowCordinate, colCordinate, ticTacToe, playerTwo);
        
    } while (!hasWon);

    return 0;
}

每次我在第一个循环之后输入行和列坐标时,它都会告诉我有碰撞。感觉就像数组在 C++ 中如何工作的一个怪癖,但我不确定。任何人都可以帮忙吗?

标签: c++debugging

解决方案


看起来您可能想专门检查 , 处的空间rowCordinate是否colCordinate被占用(并且可能不允许用户选择该点)。如果你尝试这样的事情怎么办:

bool checkCollision(const size_t row, const size_t col, char ticTacToe [][3])
{
    return ticTacToe[row][col] != '.';
}

然后在主循环中,您需要将用户输入部分更改为:

//game loop
do {
    // player 1 input
    while (true) {
        // get user input
        std::cout << "\nPlayer one, please put in a row co-ordinate:\t";
        std::cin >> rowCordinate;

        std::cout << "\nPut in a column co-ordinate:\t";
        std::cin >> colCordinate;

        // if the user selected a valid spot, change the array and move on
        if (!checkCollision(rowCordinate, colCordinate, ticTacToe)) {
            changeArray(numRows, numCols, rowCordinate, colCordinate, ticTacToe, playerTwo);
            break;
        }
        
        // otherwise print a message and keep looping
        std::cout << "Collision detected. Please try again.\n";
    }
    
    // player 2 input
    ...

推荐阅读