【发布时间】: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#