Reputation: 11
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.
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);
Upvotes: 1
Views: 93
Reputation: 531
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
Upvotes: 3