Console animations

前端 未结 11 1696
误落风尘
误落风尘 2020-12-04 10:15

I just want to know how to create simple animations like blinking, moving stuffs on C# console applications. Is there any special method for this?

11条回答
  •  忘掉有多难
    2020-12-04 10:41

    I thought I'd chime in with my version of the previously listed code. Here it is:

    class ConsoleSpinner
    {
        bool increment = true,
             loop = false;
        int counter = 0;
        int delay;
        string[] sequence;
    
        public ConsoleSpinner(string sSequence = "dots", int iDelay = 100, bool bLoop = false)
        {
            delay = iDelay;
            if (sSequence == "dots")
            {
                sequence = new string[] { ".   ", "..  ", "... ", "...." };
                loop = true;
            }
            else if (sSequence == "slashes")
                sequence = new string[] { "/", "-", "\\", "|" };
            else if (sSequence == "circles")
                sequence = new string[] { ".", "o", "0", "o" };
            else if (sSequence == "crosses")
                sequence = new string[] { "+", "x" };
            else if (sSequence == "arrows")
                sequence = new string[] { "V", "<", "^", ">" };
        }
    
        public void Turn()
        {
            if (loop)
            {
                if (counter >= sequence.Length - 1)
                    increment = false;
                if (counter <= 0)
                    increment = true;
    
                if (increment)
                    counter++;
                else if (!increment)
                    counter--;
            }
            else
            {
                counter++;
    
                if (counter >= sequence.Length)
                    counter = 0;
            }
    
            Console.Write(sequence[counter]);
            Console.SetCursorPosition(Console.CursorLeft - sequence[counter].Length, Console.CursorTop);
    
            System.Threading.Thread.Sleep(delay);
        }
    }
    

    Adds delay (unfortunately through Thread.Sleep() but, hey), the ability to loop the animation forwards and backwards (starts to reverse when it hits the end), and general improvements overall. Enjoy!

提交回复
热议问题