C#控制台应用程序|移动字符



首先,我想道歉,因为这可能是我之前问过的。然而,无论我往哪里看,我都找不到答案。我想让某个角色移动(不断地,或按某个键)。我所说的移动是指它改变了在屏幕上的位置。我不认为我真的有这个想法,但我认为你可以使用for循环,每次都在这个字符前面加一个空格。如果可能的话,我想知道如何制作这个for循环。例如:运行程序时,您会看到以下内容:*然后,在你按下一个键或只是不断地(正如我之前提到的):*如您所见,角色向右移动。但我想知道如何使它向所有方向移动(向上、向下等)

希望这已经足够好了。运行代码,然后按箭头键移动星号。从这里获得灵感:https://msdn.microsoft.com/en-us/library/system.console.setcursorposition(v=vs.110).aspx

public class Program
{
    public static void Main(string[] args)
    {
        const char toWrite = '*'; // Character to write on-screen.
        int x = 0, y = 0; // Contains current cursor position.
        Write(toWrite); // Write the character on the default location (0,0).
        while (true)
        {
            if (Console.KeyAvailable)
            {
                var command = Console.ReadKey().Key;
                switch (command)
                {
                    case ConsoleKey.DownArrow:
                        y++;
                        break;
                    case ConsoleKey.UpArrow:
                        if (y > 0)
                        {
                            y--;
                        }
                        break;
                    case ConsoleKey.LeftArrow:
                        if (x > 0)
                        {
                            x--;
                        }
                        break;
                    case ConsoleKey.RightArrow:
                        x++;
                        break;
                }
                Write(toWrite, x, y);
            }
            else
            {
                Thread.Sleep(100);
            }
        }
    }
    public static void Write(char toWrite, int x = 0, int y = 0)
    {
        try
        {
            if (x >= 0 && y >= 0) // 0-based
            {
                Console.Clear();
                Console.SetCursorPosition(x, y);
                Console.Write(toWrite);
            }
        }
        catch (Exception)
        {
        }
    }
}

最新更新