Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Console-Based Matrix Editor in C#
char[,] matrix = new char[,]
{
{ 'x', '-', '-', 'x', 'x'},
{ 'x', '-', '-', 'x', 'x'},
{ 'x', '-', '-', 'x', 'x'},
};
int x = 0;
int y = 0;
while (true)
{
PrintMatrix();
Console.SetCursorPosition(x, y);
ReadAndProcessKey();
}
void ReadAndProcessKey()
{
var key = Console.ReadKey();
if (key.Key == ConsoleKey.LeftArrow)
x--;
if (key.Key == ConsoleKey.RightArrow)
x++;
if (key.Key == ConsoleKey.UpArrow)
y--;
if (key.Key == ConsoleKey.DownArrow)
y++;
EnsureCoordinatesAreInTheMatrix();
if (key.Key == ConsoleKey.Spacebar)
{
if (matrix[y, x] == 'x')
matrix[y, x] = '-';
else
matrix[y, x] = 'x';
}
}
void EnsureCoordinatesAreInTheMatrix()
{
if (x < 0)
x = 0;
if (x > matrix.GetLength(1) - 1)
x = matrix.GetLength(1) - 1;
if (y < 0)
y = 0;
if (y > matrix.GetLength(0) - 1)
y = matrix.GetLength(0) - 1;
}
void PrintMatrix()
{
Console.Clear();
for (int row = 0; row < matrix.GetLength(0); row++)
{
for (int col = 0; col < matrix.GetLength(1); col++)
{
Console.Write(matrix[row, col]);
}
Console.WriteLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment