0
\$\begingroup\$

So I'm basically doing a snake game in Console Application. I'm kind of new to programming and I'm not sure how to do the game loop. My code looks like this:

while (true)
{
    System.Threading.Tasks.Sleep(250);
    Refresh();
}

I want it to read user input while sleeping. Could you tell me how to do it? Thanks in advance

\$\endgroup\$
  • \$\begingroup\$ You have one of two options; 1 - you use multi threading, which is a particularly advanced topic for someone new to programming, or 2 - you simply don't, because your already doing something (a thread can't be sleeping and processing input at the same time). \$\endgroup\$ – Gnemlock Dec 13 '16 at 20:38
  • \$\begingroup\$ I think I'll try with multithreading. Thanks for help :) \$\endgroup\$ – huB1erTi2 Dec 13 '16 at 20:52
3
\$\begingroup\$

I think it goes without saying that this is not something that a console application is well suited for, but at the same time, I've also written a Tetris clone for same. So....

enter image description here

While it's not quite an answer to the question you've asked (you can't do anything while sleeping. It's the point of sleeping), you can handle input to a console while managing drawing at the same time.

DateTime lastMeasuredTime = DateTime.Now;
double desiredFrameTime = 1000.0 / 24.0; //24FPS

//Main game looop
while (true)
{
    while (Console.KeyAvailable)
    {
        ConsoleKeyInfo key = Console.ReadKey(true);
        //Process input for each key
    }
    if ((DateTime.Now - lastMeasuredTime).TotalMilliseconds >= desiredFrameTime)
    {
        //Do a game tick here
        // ...
        // ...
        lastMeasuredTime = DateTime.Now;
    }
}

This approach is neither foolproof nor well-advised, but it is functional. Instead of relying on fixed sleep calls to create your time delay, you create your own timer to handle the waits for you. You then capture input inside the main loop, but outside the timer logic so that input can be received as close to immediate as possible. Also note that using DateTime is not going to create the world's most accurate timer, but it works for this application.

Also note than when using console as a renderer, you need to be smart about how you "draw" to it. Only drawing when and where necessary.

| improve this answer | |
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.