Console animations

前端 未结 11 1691
误落风尘
误落风尘 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:33

    Great work with the ConsoleSpinner and the sequence implementation. Thanks for the code. I thought about sharing my customized approach.

        public class ConsoleSpinner
        {
            static string[,] sequence = null;
    
            public int Delay { get; set; } = 200;
    
            int totalSequences = 0;
            int counter;
    
            public ConsoleSpinner()
            {
                counter = 0;
                sequence = new string[,] {
                    { "/", "-", "\\", "|" },
                    { ".", "o", "0", "o" },
                    { "+", "x","+","x" },
                    { "V", "<", "^", ">" },
                    { ".   ", "..  ", "... ", "...." },
                    { "=>   ", "==>  ", "===> ", "====>" },
                   // ADD YOUR OWN CREATIVE SEQUENCE HERE IF YOU LIKE
                };
    
                totalSequences = sequence.GetLength(0);
            }
    
            /// 
            /// 
            /// 
            ///  0 | 1 | 2 |3 | 4 | 5 
            public void Turn(string displayMsg = "", int sequenceCode = 0)
            {
                counter++;
                
                Thread.Sleep(Delay);
    
                sequenceCode = sequenceCode > totalSequences - 1 ? 0 : sequenceCode;
    
                int counterValue = counter % 4;
    
                string fullMessage = displayMsg + sequence[sequenceCode, counterValue];
                int msglength = fullMessage.Length;
    
                Console.Write(fullMessage);
    
                Console.SetCursorPosition(Console.CursorLeft - msglength, Console.CursorTop);
            }
        }
    

    Implementation:

        ConsoleSpinner spinner = new ConsoleSpinner();
        spinner.Delay = 300;
        while (true)
        {
            spinner.Turn(displayMsg: "Working ",sequenceCode:5);
        }
    

    Output:

提交回复
热议问题