Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate random color? [closed]

Tags:

arrays

c#

colors

So I'm messing around in c#, and was wondering how to generate my string from an array, but with a random color:

    while (true)
        {
            string[] x = new string[] { "", "", "" };
            Random name = new Random();
            Console.WriteLine((x[name.Next(3)]));
            Thread.Sleep(100);
        }

When I'm outputting x, I want it to be a random color. Thanks

like image 812
user1445665 Avatar asked Nov 29 '25 02:11

user1445665


2 Answers

// Your array should be declared outside of the loop

string[] x = new string[] { "", "", "" }; 
Random random = new Random();     

// Also you should NEVER have an endless loop ;)
while (true)         
{            
     Console.ForegroundColor = Color.FromArgb(random.Next(255), random.Next(255), random.Next(255));

     Console.WriteLine((x[random.Next(x.Length)]));             
     Thread.Sleep(100);         
} 
like image 99
Érik Desjardins Avatar answered Nov 30 '25 15:11

Érik Desjardins


If you want to use the standard console colors, you could mix the ConsoleColor Enumeration and Enum.GetNames() to get a random color. You'd then use Console.ForegroundColor and/or Console.BackgroundColor to change the color of the console.

// Store these as static variables; they will never be changing
String[] colorNames = ConsoleColor.GetNames(typeof(ConsoleColor));
int numColors = colorNames.Length;

// ...

Random rand = new Random(); // No need to create a new one for each iteration.
string[] x = new string[] { "", "", "" };
while(true) // This should probably be based on some condition, rather than 'true'
{
    // Get random ConsoleColor string
    string colorName = colorNames[rand.Next(numColors)];
    // Get ConsoleColor from string name
    ConsoleColor color = (ConsoleColor) Enum.Parse(typeof(ConsoleColor), colorName);

    // Assuming you want to set the Foreground here, not the Background
    Console.ForegroundColor = color;

    Console.WriteLine((x[rand.Next(x.Length)]));
    Thread.Sleep(100);
}
like image 33
Jon Senchyna Avatar answered Nov 30 '25 14:11

Jon Senchyna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!