[英]Creating a method that will procedurally write out console text like a mini game & dynamically changing still-text
我正在為我的實習項目創建一個演示文稿,並且我想比在控制台應用程序中做一個更酷,更合適的方法。
我需要2條代碼片段的幫助
該代碼段以程序方式寫出文本,雖然效果很好,但運行效果欠佳(占用資源)
static void SleeperText(string text, int interval) { char[] SlowPrint = text.ToCharArray(); foreach (char letter in SlowPrint) { Write(letter); Thread.Sleep(interval); }
該片段旨在作為鹽的圖形表示(出於演示目的),但會閃爍整個控制台。
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(); }
運行第一個代碼段的更好方法是什么,如何消除第二個代碼的閃爍?
要消除閃爍,請不要清除屏幕,而要設置光標位置並在此處寫入。
要刪除煩人的光標位置更改,只需將其隱藏即可。
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()}";
}
}
}
這只是一個骨架,您可能需要一些額外的幫手...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.