Skip to content

Instantly share code, notes, and snippets.

@chaojian-zhang
Last active November 5, 2022 18:29
Show Gist options
  • Save chaojian-zhang/c5dc1898c8fe7e40143e416ccd4074e8 to your computer and use it in GitHub Desktop.
Save chaojian-zhang/c5dc1898c8fe7e40143e416ccd4074e8 to your computer and use it in GitHub Desktop.
Interesting command line animation. #C#, #CSharp, #Utility
/*Dependency: Csv by Steven Hansen*/
using System.Drawing;
using Console = Colorful.Console;
namespace Utility
{
public class Train : IDisposable
{
#region Construction
private int _animCounter = 0;
private readonly int _delay;
private bool _active;
private readonly Thread _thread;
private int _top;
private const int ReservedNumOfLines = 7;
public Train(int delay = 200)
{
_delay = delay;
_thread = new Thread(Update);
}
#endregion
#region Properties
public string Status = string.Empty;
#endregion
#region Life Time
public void Start()
{
for (int i = 0; i < ReservedNumOfLines; i++)
Console.WriteLine(new String(' ', Console.WindowWidth));
_top = Console.CursorTop;
_active = true;
if (!_thread.IsAlive)
_thread.Start();
}
public void Stop()
{
_active = false;
}
public void Dispose()
{
Stop();
}
#endregion
#region Rendering
private void Update()
{
while (_active)
{
if (_animCounter == 52)
_animCounter = 0;
// Clear console
ClearConsole();
// Status
Console.WriteLine(Status);
// Steam
Console.Write(" . . . . o o o o o o", Color.Gray);
for (int s = 0; s < _animCounter / 2; s++)
Console.Write(" o", Color.Gray);
Console.WriteLine();
// Train body
var margin = "".PadLeft(_animCounter);
Console.WriteLine(margin + " _____ o", Color.DeepSkyBlue);
Console.WriteLine(margin + " ____==== ]OO|_n_n__][.", Color.DeepSkyBlue);
Console.WriteLine(margin + " [________]_|__|________)< ", Color.DeepSkyBlue);
Console.WriteLine(margin + " oo oo 'oo OOOO-| oo\\_", Color.OrangeRed);
Console.WriteLine(" +--+--+--+--+--+--+--+--+--+--+--+" + new string(Enumerable.Range(0, _animCounter).Select(GetSymbol).ToArray()), Color.Green);
Thread.Sleep(_delay);
_animCounter++;
}
char GetSymbol(int index)
=> "--+"[index % 3];
}
#endregion
#region Routine
private void ClearConsole()
{
Console.SetCursorPosition(0, _top - ReservedNumOfLines);
for (int i = 0; i < ReservedNumOfLines; i++)
Console.WriteLine(new String(' ', Console.WindowWidth));
Console.SetCursorPosition(0, _top - ReservedNumOfLines);
}
#endregion
}
}
Console.WriteLine("Running...");
using (Train train = new Train()) // Do NOT directly write to Console while within this block
{
train.Start();
for (int i = 0; i < loppSize; i++)
{
train.Status = $"{i}/{loopSize}";
// Do stuff
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment