简体   繁体   English

创建一种方法,该方法将以程序方式写出控制台文本,例如迷你游戏并动态更改静态文本

[英]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 我需要2条代码片段的帮助

  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 ... 这只是一个骨架,您可能需要一些额外的帮手...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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