Skip to content

Instantly share code, notes, and snippets.

@nakov
Created July 12, 2022 09:51
Show Gist options
  • Save nakov/bba6a0bdddf236a35bdfef55596e9e82 to your computer and use it in GitHub Desktop.
Save nakov/bba6a0bdddf236a35bdfef55596e9e82 to your computer and use it in GitHub Desktop.
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