# Snake user input

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)
{
Refresh();
}


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

• 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). – Gnemlock Dec 13 '16 at 20:38
• I think I'll try with multithreading. Thanks for help :) – huB1erTi2 Dec 13 '16 at 20:52

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

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.