重绘时控制台闪烁

c#

我最近开始用 c# 编码,我想制作一个在控制台中绘制一些东西的程序,这是我的代码:

    using System;
    using System.Threading.Tasks;

    namespace HelloWorld
    {
        class Program
        {
            private static readonly Random random = new Random();

            // Console width and height
            static int width = Console.WindowWidth;
            static int height = Console.WindowHeight;

            // Declare window grid
            static string[,] Grid = new string[height, width];

            public static void Main(string[] args)
            {
                init();
                loop();

                Console.ReadKey();
            }

            // Game loop

            static async void loop()
            {
                bool running = true;
                int i = 0;

                while (running)
                {
                    Grid[0, i] = "#";

                    render();

                    i++;
                    await Task.Delay(1000);
                }
            }

            static void init()
            {
                for(int y = 0; y < height; y++)
                {
                    for(int x = 0; x < width; x++)
                    {
                        Grid[y, x] = random.Next(0, 2) == 1? "#" : " ";
                    }
                }
            }

            static void render()
            {
                string temp = "";

                for (int y = 0; y < height; y++)
                {
                    for (int x = 0; x < width; x++)
                    {
                        string current = Grid[y, x];

                        temp += current;
                    }
                    temp += "n";
                }

                Console.Clear();
                Console.Write(temp);
            }
        }
    }

不过我有一个问题,当我刷新控制台时,它闪烁得非常轻微,但非常明显。有解决方案吗?或者有更好的方法来实现我的目标?提前致谢!

回答

问题是现有内容在您调用时被删除Console.Clear();,即使它没有改变。您正在立即将其写回,但正如您发现的那样,延迟足以使其显示为闪烁。

由于您每次都重新重写整个网格,因此我建议您使用Console.SetCursorPosition(0, 0);This 会将开始位置移动回开头,然后它会在不先清除控制台的情况下覆盖所有内容。这应该消除闪烁。

static void render()
{
    string temp = "";

    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            string current = Grid[y, x];

            temp += current;
        }
        temp += "n";
    }

    Console.SetCursorPosition(0, 0); // reset the cursor position
    Console.Write(temp);
}

我会完全删除字符串构建,只需更新控制台中的单个字符:

static void render()
{
    for (int y = 0; y < height; y++)
    {
        for (int x = 0; x < width; x++)
        {
            Console.SetCursorPosition(x, y); // set the position to x,y
            string current = Grid[y, x];
            Console.Write(current); // write this value
        }
    }
}


以上是重绘时控制台闪烁的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>