1

Its happening only if I tried to move my snake up or down after it was moving left. It doesn't happen if I move it up or down after it was moving right.

IMG1

I created a List of Point Type

List<Point> snakeBody = new List<Point>();
   for(int i = 0 ; i<5 ; i++)
   {
       body.Add(new Point(40 , i +25));
   }

Then I printed it onto the Grid

foreach(Point point in snakeBody)
   {
       Console.SetCursorPosition(point.X , point.Y);
       Console.Write((char)2);
   }

This is the code for movement of the snake

do
  {
     Point last = snakeBody[snakeBody.Count - 1];
     Console.SetCursorPosition(last.X , last.Y);
     snakeBody.RemoveAt(snakeBody.Count - 1);
     Console.WriteLine(" ");
     Point nextHead = body[0];
     if(initialInput == ConsoleKey.UpArrow)
     {
         nextHead = new Point(nextHead.X , nextHead.Y-1);
         Console.SetCursorPosition(nextHead.X , nextHead.Y);
         Console.Write("0");
     }
     else if(initialInput == ConsoleKey.DownArrow)
     {
         nextHead = new Point(nextHead.X, nextHead.Y+1);
         Console.SetCursorPosition(nextHead.X , nextHead.Y);
         Console.Write("0");
     }
     else if(initialInput == ConsoleKey.LeftArrow)
     {
         nextHead = new Point(nextHead.X -1 , nextHead.Y);
         Console.SetCursorPosition(nextHead.X , nextHead.Y);
         Console.Write("0"); 
     }
     else if(initialInput == ConsoleKey.RightArrow)
     {
          nextHead = new Point(nextHead.X+1 , nextHead.Y);
          Console.SetCursorPosition(nextHead.X , nextHead.Y);
          Console.Write("0");
     }

     snakeBody.Insert(0,nextHead);

     if(Console.KeyAvailable)
     {   
          initialInput = Console.ReadKey().Key;
     }

  }while(gameIsStillRunning);
JohnyL
  • 6,894
  • 3
  • 22
  • 41
Zarc
  • 11
  • 2
  • You may be interested in my [Snake Game](https://stackoverflow.com/questions/16905124/c-sharp-console-snake-gets-stuck-on-long-key-press/16907575#16907575). It shows how to add a fixed delay to the movement of a snake, and also doesn't require the arrow keys to be held. – Idle_Mind Jul 11 '19 at 16:48
  • Besides your issue (which was solved, BTW), you may want to look into refactoring your code to avoid duplicating lines, like those inside each `if-else`. – Andrew Jul 11 '19 at 17:14

1 Answers1

3

You are seeing user input in console. E.g. your keystrokes (left arrow, right arrow) result in caret movement and hence sometimes you get empty spaces.

You can change

      initialInput = Console.ReadKey().Key;

To

      initialInput = Console.ReadKey(true).Key;

This would intercept user input and wont display it

Shorstok
  • 461
  • 5
  • 7