我现在正在玩蛇游戏,并且很难确保尾巴跟随我的头部。我目前正试图让它工作,我已经尝试了大约十几种不同的想法,所有这些想法要么让它完全停止(例如蛇似乎被冻结在一个地方),要么完全发生垂直运动尾巴的点一次,而不是一个动作跟随另一个动作。我在使用似乎不可避免的 Console.Clear() 方法时也遇到了一些麻烦。要么我这样做太多次,它会删除除了我的蛇的第一个点之外的所有内容,或者我不这样做并且旧位置不会被删除。这是代码(这是一个测试代码,从实际游戏中分离出来,因为我需要确保代码有效):
class Program
{
const int size = 10;
struct Sprite
{
public char[] ch;
public int[,] posXY;
public int directionX;
public int directionY;
}
static void Main(string[] args)
{
int startX = 10;
int startY;
Sprite player = new Sprite();
player.ch = new char[7];
player.posXY = new int[7,2];
for (int i = 0; i < player.ch.Length; i++)
{
player.ch[i] = '*';
}
for (int i = 0; i < 7; i++)
{
startY = 10;
player.posXY[i, 0] = startX;
player.posXY[i, 1] = startY;
startX--;
}
ConsoleKeyInfo cki = new ConsoleKeyInfo();
while (true)
{
update(cki, ref player);
draw(player);
Thread.Sleep(200);
}//end while
}//end main
static void update(ConsoleKeyInfo cki, ref Sprite player)
{
if (Console.KeyAvailable)
{
cki = Console.ReadKey(true);
if (cki.Key == ConsoleKey.LeftArrow || cki.Key == ConsoleKey.A)
{
player.directionX = -1;
player.directionY = 0;
}
if (cki.Key == ConsoleKey.RightArrow || cki.Key == ConsoleKey.D)
{
player.directionX = 1;
player.directionY = 0;
}
if (cki.Key == ConsoleKey.UpArrow || cki.Key == ConsoleKey.W)
{
player.directionX = 0;
player.directionY = -1;
}
if (cki.Key == ConsoleKey.DownArrow || cki.Key == ConsoleKey.S)
{
player.directionX = 0;
player.directionY = 1;
}
}//endif
for (int i = 0; i < 7; i++)
{
player.posXY[i, 0] = player.posXY[i, 0] + player.directionX;
player.posXY[i, 1] = player.posXY[i, 1] + player.directionY;
}
}//end update
static void draw(Sprite player)
{
Console.Clear();
for (int i = 0; i < 7; i++)
{
Console.SetCursorPosition(player.posXY[i, 0], player.posXY[i, 1]);
Console.Write(player.ch[i]);
}
}//end draw
}
PS我需要为我的蛇使用结构,使用类不是一个选项。