0

我一直在为 naughts and crosss 程序做一些编程,而电路板是一个 2D 数组。如果用户想要重播,我一直在尝试使程序重复,但是我注意到重复时所有值都保留在数组中。所以我想知道是否有办法清除我数组中的所有值。

我确实在论坛上尝试了一些以前的问题,但是我发现的一些解决方案似乎不起作用。

如果有人想查看代码,只需发表评论,我会在此处添加,我只是不确定是否有必要。

任何帮助将非常感激。

    const int Rows = 4;
    const int Columns = 4;
    char Board[Rows][Columns] = { {' ', ' ', ' ', ' ' },
                                  {' ', '_', '_', '_' },
                                  {' ', '_', '_', '_' },
                                  {' ', '_', '_', '_' } };


    for (int i = 0; i < Rows; ++i)
    {
        for (int j = 0; j < Columns; ++j)
            cout << Board [i][j];
        cout << endl;
    }

    cout << endl << endl;



    int row;
    int column;


    do
    {
        cout << "Please enter the value of the row you would like to take ";
        cin >> row;
        }while (row != 0 && row != 1 && row != 2 && row != 3);


    do
    {
        cout << "Please enter the value of the column you would like to take ";
        cin >> column;
        }while (column != 0 && column != 1 && column != 2 && column != 3);


    Board [row][column] = Player1.GetNorX();

            for (int i = 0; i < Rows; ++i)
    {
        for (int j = 0; j < Columns; ++j)
            cout << Board [i][j];
        cout << endl;
    }
4

3 回答 3

2

假设您想Board重置为原始状态,您需要:

for (int i = 0; i < Rows; i++) {
  for (int j = 0; j < Columns; j++) {
    if (i == 0 || j == 0) {
      Board[i][j] = ' ';
    } else {
      Board[i][j] = '_';
    }
  }
}

这将遍历数组的每个元素,如果列或行号为 0,则用 a 填充它' ',否则用 a 填充它'_'

如果您只关心右下角的 3x3 网格,那么您可以这样做:

for (int i = 1; i < 4; i++) {
  for (int j = 1; j < 4; j++) {
    Board[i][j] = '_';
  }
}

但是我建议改为声明Rowsand Columnsas 。3如果您希望用户输入从 1 开始的行号和列号,只需在访问数组时将 {1, 2, 3} 转换为 {0, 1, 2} 即可。

于 2013-02-28T15:10:59.523 回答
0

使用List类代替传统的多维数组。这个类的对象的元素可以很容易的清除和移除。此外,列表的大小是动态的和可变的。创建对象时无需指定大小。尝试定义一个二维列表。

List<List<char>> Board = new List<List<char>>;
于 2013-02-28T15:31:01.437 回答
0

将代码放入单独的函数中

void game()
{
   const int Rows = 4;
   // ...
}

并从游戏控制器调用它

bool replay;
do
{
    game();
    cout << "Replay? (0 - no, 1 - yes)";
    cin >> replay;
} while(replay);

这种方法恢复了整个给定的环境。

于 2013-02-28T15:19:52.040 回答