Created
July 12, 2022 09:51
-
-
Save nakov/bba6a0bdddf236a35bdfef55596e9e82 to your computer and use it in GitHub Desktop.
Console-Based Matrix Editor in C#
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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