为什么游戏中蛇的中间部分有时会消失?

时间:2019-07-11 16:08:56

标签: c#

只有在蛇向左移动后尝试上下移动蛇时,才会发生这种情况。如果它在向右移动后向上或向下移动,都不会发生。

IMG1

我创建了一个点类型列表

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

然后我将其打印到网格上

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

这是蛇移动的代码

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);

1 个答案:

答案 0 :(得分:3)

您正在控制台中看到用户输入。例如。您的击键(向左箭头,向右箭头)会导致插入符号移动,因此有时会出现空白。

您可以更改

      initialInput = Console.ReadKey().Key;

收件人

      initialInput = Console.ReadKey(true).Key;

这会拦截用户输入并不会显示