Certainly! Below is a C# console application that continuously renders a looping ASCII spiral. The spiral moves and spins from the center, with lines that curve and gradually widen. The application adapts to window size changes in real-time and handles any potential out-of-bounds writing gracefully using try-catch. It also uses a variety of characters and applies RGB colors through ANSI escape codes.
Features:
- Continuous Looping Spiral: The spiral continuously spins and expands outward from the center.
- Adaptive to Window Size: Dynamically adjusts to the current size of the console window.
- Smooth Animation: Utilizes timing to create smooth motion.
- RGB Colors: Applies vibrant colors using ANSI escape codes.
- Variety of Characters: Uses different ASCII characters to create a dynamic effect.
- Error Handling: Safely handles any attempts to write outside the console window boundaries.
Prerequisites:
- .NET Core or .NET 5+: Ensure you have a compatible version of .NET installed.
- Windows Console Support for ANSI Codes: Modern Windows consoles (Windows 10 and later) support ANSI escape codes by default. If you're using an older version or a different OS, color support may vary.
Complete C# Code:
using System;
using System.Text;
using System.Threading;
namespace AsciiSpiral
{
class Program
{
// ANSI escape code prefix
const string ESC = "\x1b[";
static void Main(string[] args)
{
// Enable ANSI escape codes
Console.OutputEncoding = Encoding.UTF8;
// Hide the cursor for better visual effect
Console.CursorVisible = false;
// Characters to use in the spiral
char[] chars = new char[] { '*', '+', '.', 'o', 'x', '@', '#', '%', '&', '$' };
Random rand = new Random();
// Spiral parameters
double angleOffset = 0;
double radiusOffset = 0;
double angleIncrement = 0.1; // Controls the tightness of the spiral
double radiusIncrement = 0.05; // Controls how quickly the spiral expands
// Animation loop
while (true)
{
// Get current window dimensions
int width = Console.WindowWidth;
int height = Console.WindowHeight;
// Calculate center of the window
int centerX = width / 2;
int centerY = height / 2;
// Clear the screen for the new frame
Console.SetCursorPosition(0, 0);
Console.Write(ESC + "2J"); // Clear screen using ANSI code
// Number of points in the spiral
int points = 1000;
for (int i = 0; i < points; i++)
{
// Calculate the current angle and radius for the spiral
double currentAngle = angleOffset + i * angleIncrement;
double currentRadius = radiusOffset + i * radiusIncrement;
// Convert polar coordinates to Cartesian coordinates
int x = centerX + (int)(currentRadius * Math.Cos(currentAngle));
int y = centerY + (int)(currentRadius * Math.Sin(currentAngle));
// Select a random character from the array
char c = chars[rand.Next(chars.Length)];
// Generate random RGB color
int r = rand.Next(0, 256);
int g = rand.Next(0, 256);
int b = rand.Next(0, 256);
string color = $"{ESC}38;2;{r};{g};{b}m";
try
{
// Set cursor position and write the colored character
Console.SetCursorPosition(x, y);
Console.Write(color + c);
}
catch (ArgumentOutOfRangeException)
{
// Ignore if the position is outside the console window
continue;
}
}
// Reset color to default
Console.Write(ESC + "0m");
// Update spiral parameters to create motion
angleOffset += 0.05; // Controls rotation speed
radiusOffset += 0.01; // Controls expansion speed
// Control the frame rate
Thread.Sleep(50); // Adjust for smoother or faster animation
}
}
}
}
Explanation of the Code:
-
Setting Up the Console:
Console.OutputEncoding = Encoding.UTF8;: Enables UTF-8 encoding to support a wide range of characters and ANSI codes.
Console.CursorVisible = false;: Hides the blinking cursor for a cleaner visual effect.
-
Spiral Parameters:
angleOffset and radiusOffset are used to animate the spiral's rotation and expansion over time.
angleIncrement and radiusIncrement determine how tightly the spiral coils and how quickly it expands.
-
Main Animation Loop:
- Window Dimensions: Retrieves the current width and height to adapt to any window size changes.
- Center Calculation: Determines the center point to start drawing the spiral.
- Screen Clearing: Uses the ANSI escape code
ESC + "2J" to clear the screen efficiently without flickering.
- Spiral Points: Iterates through a set number of points to plot the spiral. Adjust
points for more or fewer points per frame.
- Coordinate Conversion: Converts polar coordinates (angle and radius) to Cartesian coordinates (x, y) relative to the center.
- Randomization:
- Character Selection: Chooses a random character from the predefined
chars array to add variety.
- Color Selection: Generates random RGB values and creates an ANSI color code.
- Drawing the Spiral:
- Attempts to set the cursor position and write the colored character.
- Uses
try-catch to gracefully handle any ArgumentOutOfRangeException that occurs if the calculated position is outside the visible window.
- Updating Parameters: Adjusts the
angleOffset and radiusOffset to animate the spiral's rotation and expansion.
- Frame Rate Control: Uses
Thread.Sleep(50) to control the speed of the animation. You can adjust this value for faster or slower animations.
Tips for Running the Application:
Sample Output:
When you run the application, you should see a colorful, animated spiral emanating from the center of your console window. The spiral will continuously rotate and expand, adapting to any changes in the window size. Different ASCII characters and vibrant colors will make the spiral visually engaging.
Note: Some older versions of Windows or certain console configurations might not fully support ANSI escape codes. If you encounter issues with colors not displaying correctly, ensure that your console supports ANSI codes and that no additional settings are interfering.