让两个角色同时移动

时间:2017-11-14 16:40:55

标签: c# console-application

我试图在控制台应用程序中制作一个小游戏,我希望敌人在移动玩家的同时不断移动。代码现在看起来像这样:

public static int y = 5;
    public static string player = "O";
    public static int enemyX = 10;
    static void Main(string[] args)
    {

        while (true)
        {
            Console.SetCursorPosition(enemyX, 10);
            Console.Write("X");
            enemyX = enemyX - 1;
            Console.CursorVisible = false;
            Console.SetCursorPosition(5, y);
            Console.Write(player);

            var move = Console.ReadKey(true);
            switch (move.Key)
            {
                case ConsoleKey.W:
                    y = y - 1;
                    break;
                case ConsoleKey.S:
                    y = y + 1;
                    break;
            }
            if (y <= 0)
            {
                y = 1;
            }

            if (y >= 25)
            {
                y = 24;
            }
            Console.Clear();
        }
    }

1 个答案:

答案 0 :(得分:1)

根据我的理解,无论玩家是否移动,你都希望敌人移动并且这样做你可以使用Threads 例如:

bool BreakThread = false; //you need this to break the thread loop 
Thread enemyThread = new Thread(()=>
{
  while(!BreakThread)
  {
  //do Enemy Actions
  }
});

enemyThread.Start();
//then execute your main game loop

但请记住将BreakThread值设置为true 正在关闭比赛。