Reputation: 95
I've been doing some programming for a naughts and crosses program and the board is a 2D array. I have been trying to make the program repeat if the user wants to replay however I noticed that all of the values stay in the array when it is repeated. So I was wondering if there was a way to clear all of the values in my array.
I did try some previous questions on forums however some of the solutions I found didn't seem to work.
If anyone would like to see the code just comment and I will add it here, I just wasn't sure if it would be necessary.
Any help would be much appreciated.
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;
}
Upvotes: 0
Views: 144
Reputation: 463
Use List class instead of traditional multidimensional arrays. The elements of the object of this class can be easily cleared and removed. Moreover, the size of the list is dynamical and changeable. It is not necessary to specify the size when creating an object. Try to define a two dimensional list.
List<List<char>> Board = new List<List<char>>;
Upvotes: 0
Reputation: 110658
Assuming you want Board
to be reset to its original state, you need:
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] = '_';
}
}
}
This will loop through every element of the array and, if the column or row number is 0, fill it with a ' '
, or otherwise fill it with a '_'
.
If you only care about the bottom right 3x3 grid then you could do:
for (int i = 1; i < 4; i++) {
for (int j = 1; j < 4; j++) {
Board[i][j] = '_';
}
}
But then I recommend declaring Rows
and Columns
as 3
instead. If you want your user to enter row and column numbers starting from 1, just translate from {1, 2, 3} to {0, 1, 2} when you access the array.
Upvotes: 2
Reputation: 1047
Put the code into separate function
void game()
{
const int Rows = 4;
// ...
}
and invoke it from the game controller
bool replay;
do
{
game();
cout << "Replay? (0 - no, 1 - yes)";
cin >> replay;
} while(replay);
This method restores the whole gave environment.
Upvotes: 0