Console animations

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

    This would be my prefered method:

    public sealed class Spinner
    {
        private static Lazy lazy =
            new Lazy(()=> new Spinner());
    
        public static void Reset()
        {
            lazy = new Lazy(()=> new Spinner());
        }
    
        public static Spinner Instance { get { return lazy.Value; }}
    
        private readonly int _consoleX;
        private readonly int _consoleY;
        private readonly char[] _frames = { '|', '/', '-', '\\' };
        private int _current;
    
        private Spinner()
        {
            _current = 0;
            _consoleX = Console.CursorLeft;
            _consoleY = Console.CursorTop;
        }
    
        public void Update()
        {
            Console.Write(_frames[_current]);
            Console.SetCursorPosition(_consoleX, _consoleY);
    
            if (++_current >= _frames.Length)
                _current = 0;
        }
    }
    

    Call Spinner.Instance.Update() to start the spinner at the current position of the console. Any consecutive call will render the next frame at the same position.

    Call Spinner.Reset() if you want to write more text and then add a new spinner at a new location.

提交回复
热议问题