Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make text be "typed out" in console application?

Just like the way the computer does it in War Games. I've started, but I don't know where to go from here.

static void TypeLine(string line)
{
    string output = null;
    char[] characters = line.ToCharArray();
    for (int i = 0; i < characters.Length; i++)
    {
        output += characters[i];
        Console.Clear();
    }
    Console.WriteLine(output);
}

My idea was to split the string you wanted it to output, add a character, clear the console, add another, and so on. I got that far, but I don't really know how to make it add, then clear, then add again. Some tips would be nice, or even completed code if you feel like it.

like image 482
Tre B Avatar asked Jan 18 '26 14:01

Tre B


2 Answers

The easiest way may be to Sleep() between characters. Something like this:

static void TypeLine(string line) {
    for (int i = 0; i < line.Length; i++) {
        Console.Write(line[i]);
        System.Threading.Thread.Sleep(150); // Sleep for 150 milliseconds
    }
}
like image 177
mwk Avatar answered Jan 21 '26 02:01

mwk


The effect you are looking for is that after each character of the string is written to the console a short delay of about 10 to 50 milliseconds is made, just like in this code:

static void Main()
{
    var myString = "Hey there" + Environment.NewLine + "How are you doing?";

    foreach (var character in myString)
    {
        Console.Write(character);
        Thread.Sleep(30);
    }
    Console.WriteLine();
    Console.ReadLine();
}

In the code above, I create a string that has a line break in it (Environment.NewLine). Afterwards I use an foreach loop to run through every character of that string and write it to the console one by one. After each character, the thread is put to sleep for 30 milliseconds (Thread.Sleep) so that is just works again after that time span.

If you have any further questions, please feel free to ask.

like image 41
feO2x Avatar answered Jan 21 '26 03:01

feO2x



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!