控制台在重绘时闪烁

Console flickering on redraw

我最近开始使用 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);这样会把开始写的位置移回开头,然后会覆盖所有内容,而不需要先清除安慰。这应该可以消除闪烁。

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
        }
    }
}