【问题标题】:Why does the middle part of the snake in my game disappear sometimes?为什么我的游戏中蛇的中间部分有时会消失?
【发布时间】:2019-07-11 16:08:56
【问题描述】:

只有当我的蛇向左移动后我试图向上或向下移动时才会发生这种情况。如果我在它向右移动后向上或向下移动它就不会发生。

我创建了一个点类型列表

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

【问题讨论】:

  • 您可能对我的Snake Game 感兴趣。它展示了如何为蛇的移动添加固定延迟,并且不需要按住箭头键。
  • 除了您的问题(顺便说一句已解决)之外,您可能还需要考虑重构代码以避免重复行,例如每个 if-else 中的行。

标签: c#


【解决方案1】:

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

你可以改变

      initialInput = Console.ReadKey().Key;

      initialInput = Console.ReadKey(true).Key;

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    相关资源
    最近更新 更多