繁体   English   中英

C# 控制台应用程序 | 移动角色

[英]C# Console Application | Moving a character

首先,我想道歉,因为这可能是在我之前问过的。 然而,无论我在哪里看,我都找不到答案。 我想让某个角色移动(不断地,或按某个键)。 通过移动我的意思是它改变了它在屏幕上的位置。 我不认为我真的明白它的想法,但我认为你可以使用 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)
        {
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM