0

I'm trying to write a simple console based game engine in C# for fun. Right now what I'm trying to do is establish a simple game loop where the "game" waits for user input, updates then renders then clears the screen then repeats.

This is my code so far:


int x = 0;

bool quit = false;
Task.Run(async () =>
{
    try // Catch any issues
    {
        while (!quit)
        {
            Console.WriteLine("render");
            Console.WriteLine("Position of implicit object: {0}", x);
            await Task.Delay(100);
            Console.Clear();
        }
    }
    catch (Exception e) { Console.WriteLine(e); }
});

while (!quit)
{
    ConsoleKeyInfo keyInfo = Console.ReadKey(false);
    ConsoleKey key = keyInfo.Key;

    switch (key)
    {
        case ConsoleKey.D:
            x++;
            Console.WriteLine("A-key pressed");
            break;
        case ConsoleKey.A:
            x--;
            Console.WriteLine("D-key pressed");
            break;

        case ConsoleKey.Escape:
            quit = true;
            break;
    }
}

But the issue is, there's a constant flicker when the console is updating. I heard Console.SetCursorPosition(0, 0); might work but when I try that, it seems that the updating stops when the user clicks the screen.

Is there another way to do it? Even if it involves changing the method of the game loop itself.

Thank you!

  • I don't see any code in here that actually renders anything. – Robert Harvey Feb 12 '22 at 14:59
  • @RobertHarvey The render function is just a simple Console.WriteLine() statement right now. That part is fine. But when it "renders" the statement, it keeps flickering – Hanna Assaf Feb 12 '22 at 15:01
  • I would imagine that it's the `Console.Clear()` call that is the problem. – Robert Harvey Feb 12 '22 at 15:11
  • @RobertHarvey You're right but without it, I'd just get a series of print statements in a list going downwards on the console. I'm trying to clear the screen and "redraw" the next "frame" (in this simple example, just a mere print statement) – Hanna Assaf Feb 12 '22 at 15:15
  • https://stackoverflow.com/questions/13656846/how-to-programmatic-disable-c-sharp-console-applications-quick-edit-mode – Hans Passant Feb 12 '22 at 15:32

1 Answers1

0

Please use this as a fix Console.SetCursorPosition(0, 0), add this before Console.WriteLine("render"). To fix the click issue as you have mentioned. You have to uncheck Quick Edit mode on console window. Right click on console window -> properties in edit section uncheck Quick Edit. Screenshot attached.

enter image description here

saif iqbal
  • 219
  • 1
  • 9