【问题标题】:Error in Tic-Tac-Toe Game井字游戏中的错误
【发布时间】:2018-04-08 05:19:26
【问题描述】:

我在创建模拟井字游戏的程序时遇到了这个 C++ 代码的问题。游戏运行“正常”、显示获胜者、验证输入等,但如果玩家“X”获胜,则仍然允许玩家“O”在宣布获胜者之前再采取行动。

do
{
    int turn = 0;

    if (turn % 2 == 0)
    {
        cout << "Player X, Row and Column: ";
        cin >> row >> column;

        while (array[(row-1)][(column-1)] != '*')
        {
            cout << "Invalid move try again \n";
            cout << "Player X, Row and Column: ";
            cin >> row >> column;
        }

        array[row-1][column-1] = 'X';
        showArray(array);
        results = checkWin(array);
    }

    if (turn % 2 != 0)
    {
        cout << "Player O, Row and Column: ";
        cin >> row >> column;

        while (array[row-1][column-1] != '*')
        {
            cout << "Invalid move try again \n";
            cout << "Player O, Row and Column: ";
            cin >> row >> column;
        }
        array[row-1][column-1] = 'O';
        showArray(array);
        results = checkWin(array);
    }
    turn++;
}while (results == 0);

我正在使用在两个玩家之间交替的 do-while 循环。当我放置递增的 'turn++;'两个 if 块之外的语句,程序只允许玩家“X”移动。当我放置'turn++;'播放器'X' if 块中的语句,它交替出现,但我遇到了上述问题。如果您有任何建议,请给他们。谢谢。

【问题讨论】:

标签: c++ increment do-while tic-tac-toe


【解决方案1】:

每次循环迭代时,轮值都会初始化为 0,这就是每次玩家“X”都有机会的原因。

所以将 int turn = 0 放在循环之外。

【讨论】:

    【解决方案2】:

    正如@hai_uit 所说,将int turn = 0; 移出循环。大多数情况下,在任何循环或 if 语句之外声明所有变量是个好主意。

    【讨论】:

    • 谢谢!是的,我看到了索引/计数器变量在每次循环后重置的位置。
    【解决方案3】:

    int turn = 0; 移出您的循环。例如:

    int turn = 0;
    do {
        doSomeThing();
        turn++;
    } while(someThingHappen());
    

    如果您将int turn = 0 放在循环中,则每个循环都将以turn = 0 开头

    【讨论】:

      猜你喜欢
      • 2023-03-16
      • 2014-12-31
      • 1970-01-01
      • 1970-01-01
      • 2017-11-06
      • 2018-06-03
      • 1970-01-01
      相关资源
      最近更新 更多