简体   繁体   中英

Creating a method that will procedurally write out console text like a mini game & dynamically changing still-text

I am creating a presentation for my Internship project and I figured what would be a cooler and more appropriate way than to do it in a Console Application.

I need help with 2 code snippets

  1. This snippet procedurally writes out text and it works well but runs sub-optimally (hogs resources)

     static void SleeperText(string text, int interval) { char[] SlowPrint = text.ToCharArray(); foreach (char letter in SlowPrint) { Write(letter); Thread.Sleep(interval); } 
  2. This snippet is meant to be a graphic representation of what a salt would look like (for demonstration purposes) but flickers the whole Console.

     static char RandomAsciLetter() { char charsi = (ascii[r.Next(tempstring.Length)]); return charsi; } static string RandomAsciCombo() { string stringsi = String.Format("{0}{1}{2}{3}{4}{5}{6}{7}{8}{9}", RandomAsciLetter(), RandomAsciLetter(), RandomAsciLetter(), RandomAsciLetter(), RandomAsciLetter(), RandomAsciLetter(), RandomAsciLetter(), RandomAsciLetter(), RandomAsciLetter(), RandomAsciLetter()); return stringsi; } void Main() { do { while (!KeyAvailable) { Thread.Sleep(10); Clear(); Write("[ Esc ] to exit."); Write("\\r\\n\\r\\n\\r\\n\\r\\n"); WriteLine(String.Format("Salt:\\t{0}{1}", RandomAsciCombo(), RandomAsciCombo())); } } while (Console.ReadKey(true).Key != ConsoleKey.Escape); ReadLine(); } 

What is a better way to run the first snippet, and how do I remove the flickering for the second?

To remove flickering, do not clear the screen but rather set cursor position and write there.

To remove the annoying cursor position change, just hide it.

using System;

namespace ConsoleApp1
{
    internal static class Program
    {
        private static readonly Random Random = new Random();

        private static void Main(string[] args)
        {
            Console.CursorVisible = false;

            while (true)
            {
                if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)
                    break;

                Console.SetCursorPosition(10, 10);
                Console.Write(GetString());
            }
        }

        private static char GetChar()
        {
            return (char) Random.Next(65, 92);
        }

        private static string GetString()
        {
            return $"{GetChar()}{GetChar()}{GetChar()}{GetChar()}{GetChar()}";
        }
    }
}

This is just a skeleton, you will likely need some extra helpers ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM