I am making a snake game as my homework assignment , I've already added a code for making the snake head move depending on the user input (left , right , down , up) But I am stuck with the timing of it , I used Thread.Sleep in order for the game not to crash and get an exception , but my instructor told me that Thread.Sleep is a horrible idea in programming because it literally adds a delay to your game. So, I need to somehow make it that there won't be a delay in my game while avoiding Thread.Sleep
class Program
{
static void Main(string[] args)
{
Direction direction = Direction.Down;
Console.CursorVisible = false;
int x=0 , y=0 ;
int xprev = 2, yprev = 2;
char shape = 'o';
x = xprev;
y = yprev;
Console.SetCursorPosition(xprev, yprev);
Console.Write(shape);
UserInput input = new UserInput();
ConsoleKeyInfo? info;
while (true)
{
info = input.GetKey();
if (info.HasValue)
{
switch (info.Value.Key)
{
case ConsoleKey.RightArrow:
direction = Direction.Right;
break;
case ConsoleKey.LeftArrow:
direction = Direction.Left;
break;
case ConsoleKey.UpArrow:
direction = Direction.Up;
break;
case ConsoleKey.DownArrow:
direction = Direction.Down;
break;
}
}
Thread.Sleep(100);
switch (direction)
{
case Direction.Up:
y--;
break;
case Direction.Down:
y++;
break;
case Direction.Left:
x--;
break;
case Direction.Right:
x++;
break;
}
Console.MoveBufferArea(xprev, yprev, 1, 1, x, y);
xprev = x;
yprev = y;
}