mercredi 12 décembre 2018

randomly changing the colour of foreground and background in c#

I have a code here that randomly chooses a string from an array, then uses that corresponding string to change the color of the background. The same is done for the background, but there is a lot of code, and if i wanted to add any more colors, it would be quite time consuming. Any tips?

Here is the code:

 static void Main(string[] args)
        {
            Random random = new Random();
            Console.WriteLine("Input your name: ");
            string yourName = Console.ReadLine();
            while (true)
                {
                string[] colours = new string[5] {"red" , "white", "yellow" , "magenta" , "blue" };
                int backColour = random.Next(0,5);
                if (backColour == 0)
                {
                    Console.BackgroundColor = ConsoleColor.Red;
                }
                if (backColour == 1)
                {
                    Console.BackgroundColor = ConsoleColor.White;
                }
                if (backColour == 2)
                {
                    Console.BackgroundColor = ConsoleColor.Yellow;
                }
                if (backColour == 3)
                {
                    Console.BackgroundColor = ConsoleColor.Magenta;
                }
                if (backColour == 4)
                {
                    Console.BackgroundColor = ConsoleColor.Blue;
                }

                int frontColour = random.Next(0, 5);
                if (frontColour == 0)
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                }
                if (frontColour == 1)
                {
                    Console.ForegroundColor = ConsoleColor.White;
                }
                if (frontColour == 2)
                {
                    Console.ForegroundColor = ConsoleColor.Yellow;
                }
                if (frontColour == 3)
                {
                    Console.ForegroundColor = ConsoleColor.Magenta;
                }
                if (frontColour == 4)
                {
                    Console.ForegroundColor = ConsoleColor.Blue;
                }


                Console.Write("All work and no pla`enter code here`y makes " + yourName + " a dull person! ");
                Console.Clear();
                }
        }

Many Thanks!




Aucun commentaire:

Enregistrer un commentaire