When it comes to 2D arrays you've got the right idea with nested for loops. These allow you to iterate through each row and then each column (If you visualise this a matrix).
Updating the console view can be achieved with the Console.SetCursorPostion()
method. Each character in the console has an X and Y Coordinate, but calling this method you can place the cursor at a grid reference. After calling this method anything written to the console will output from this new position.
Note: The console is not cleared when you call the Console.SetCursorPostion()
anything output after is simple written over the top. This means that if the text you're writing after calling the method is shorter than the previous output, you will still see some of the old output.
In your case each time your use makes a move you could actually clear down the entire console, which can be achieved with Console.Clear()
.
I've wrote a small demo application below which reads in a grid from a text file which can acts as a Tic Tac Toe board. By default the grid is filled with the coordinates of that particular box, this is because the program is quite crude and uses these text values to place the players goes. The players goes are stored in a 2D array which displays either blank values or can hold a '0'/'X'.
A simple read line lets users enter Coordinates and then it will fill the 2D array with the answer and redraw the grid.
Crosses always goes first!
I hope this demo program gives a good example of how the console can be re-written and provides some ideas about how you could implement your idea using 2D arrays.
Program
static void Main(string[] args)
{
int player = 0;
string[,] grid = new string[3, 3] {{" "," "," "},
{" "," "," "},
{" "," "," "} };
string box = System.IO.File.ReadAllText(@"C:\Users\..\Box.txt");
Console.WriteLine(box);
Console.ReadLine();
while (true)
{
Console.WriteLine("Enter Coordinate in 'x,y' Format");
string update = Console.ReadLine();
if (player == 0)
{
string[] coords = update.Split(',');
var x = int.Parse(coords[0]) - 1;
var y = int.Parse(coords[1]) - 1;
grid[x,y] = " X ";
player++;
}
else
{
string[] coords = update.Split(',');
var x = int.Parse(coords[0]) - 1;
var y = int.Parse(coords[1]) - 1;
grid[x, y] = " 0 ";
player--;
}
UpdateGrid(grid, box);
}
}
public static void UpdateGrid(string[,] grid, string box)
{
Console.Clear();
for (int i = 0; i < grid.GetLength(0); i++)
{
for (int j = 0; j < grid.GetLength(1); j++)
{
box = box.Replace((i + 1) + "," + (j + 1), grid[i, j]);
}
}
// In the case not required as clearning the console default the cursor back to 0,0, but left in
// as an example
Console.SetCursorPosition(0, 0);
Console.WriteLine(box);
}
Text File
+-----------------+
| 1,1 | 2,1 | 3,1 |
+-----+-----+-----+
| 1,2 | 2,2 | 3,3 |
+-----+-----+-----+
| 1,3 | 2,3 | 3,3 |
+-----------------+