✍️ Practice (Console)
1. Color Swap
Print your name in yellow on a dark blue background, then reset the colors.
👀Hint
Where in the official documentation can you find the properties you need 👀
💡Solution
class Program
{
static void Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.BackgroundColor = ConsoleColor.DarkBlue;
Console.Write("Frodo Baggins");
Console.ResetColor();
Console.WriteLine();
Console.WriteLine("Back to normal colors.");
}
}
2. Four Corners
Print * in each corner of the window
👀Hint
Where in the official documentation can you find the methods you need 👀
💡Solution
class Program
{
static void Main(string[] args)
{
int right = Console.WindowWidth - 1;
// leave room for prompt
int bottom = Console.WindowHeight - 2;
// ensure theres nothing else there for our beautiful stars
Console.Clear();
// top-left
Console.SetCursorPosition(0, 0);
Console.Write("*");
// top-right
Console.SetCursorPosition(right, 0);
Console.Write("*");
// bottom-left
Console.SetCursorPosition(0, bottom);
Console.Write("*");
// bottom-right
Console.SetCursorPosition(right, bottom);
Console.Write("*");
// Move the cursor below the border so the prompt doesn't overwrite it
Console.SetCursorPosition(0, bottom + 1);
}
}
3. Border
Draw a rectangle of # around the edge of the window.
👀Hint
Use loops 👀
💡Solution
class Program
{
static void Main(string[] args)
{
int right = Console.WindowWidth - 1;
int bottom = Console.WindowHeight - 2;
// ensure theres nothing else there for our beautiful rectangle
Console.Clear();
// Top and bottom edges
for (int x = 0; x <= right; x++)
{
Console.SetCursorPosition(x, 0);
Console.Write("#");
Console.SetCursorPosition(x, bottom);
Console.Write("#");
}
// Left and right edges (corners are already drawn)
for (int y = 1; y < bottom; y++)
{
Console.SetCursorPosition(0, y);
Console.Write("#");
Console.SetCursorPosition(right, y);
Console.Write("#");
}
// Move the cursor below the border so the prompt doesn't overwrite it
Console.SetCursorPosition(0, bottom + 1);
}
}
4. Play ball
Move a ball across the screen from left to right ⚾️
👀Hint
You can use Thread.Sleep(); to determine the pace of the ball
💡Solution
class Program
{
static void Main(string[] args)
{
int row = Console.WindowHeight / 2;
int lastColumn = Console.WindowWidth - 2; // emoji is 2 wide
Console.Clear();
Console.CursorVisible = false;
for (int x = 0; x <= lastColumn; x++)
{
// Erase the previous position (if there is one)
if (x > 0)
{
Console.SetCursorPosition(x - 1, row);
Console.Write(" ");
}
// Draw the ball at the new position
Console.SetCursorPosition(x, row);
Console.Write("⚾️");
// determine ball speed
Thread.Sleep(10);
}
Console.CursorVisible = true;
Console.SetCursorPosition(0, row + 2);
}
}