简体   繁体   English

移动2个对象的C#控制台游戏

[英]Moving 2 objects C# console game

Basically i want to write a game where you can shoot stuff.My problem is that when i shoot i can't move while the object hasn't reached the end of the console and i tried using thread to make it parallel but it messes up the cleaning of the console from previous coordinates. 基本上我想写一个可以射击的游戏。我的问题是射击时我无法移动,而物体还没到达控制台的尽头,我尝试使用线程使其平行,但是搞砸了从以前的坐标清洗控制台。

static void ShootingLaser(int x,int y,string symbol)
{
    Drawing(x, y, symbol);

    Point basePoint = new Point(x,y);
    while (y < Console.WindowWidth - 1)
    {
        Point lastLaserPoint = new Point(x, y);
        y++;
        DeletingLastDraw(lastLaserPoint.x, lastLaserPoint.y);
        Drawing(x, y, symbol);

        Thread.Sleep(30);
    }    

What do you think guys?Can you help me figure out how to make it shoot and move at the same time without bugging up the console? 您觉得家伙如何?您能帮我弄清楚如何同时射击和移动它而又不影响控制台吗?

From your description of the problem, I'm guessing that your code for drawing to the screen and deleting look something like this: 从问题的描述中,我猜测您用于绘制到屏幕上并删除的代码看起来像这样:

private static void Drawing(int x, int y, string symbol)
{
    Console.SetCursorPosition(x, y);
    Console.Write(symbol);
}

private static void DeletingLastDraw(int x, int y)
{
    Drawing(x, y, " ");
}

If that is the case, then when multiple threads try and draw to the screen the cursor may be moved between the two lines of the Drawing method. 如果真是这样,那么当多个线程尝试绘制到屏幕上时,光标可能会在Drawing方法的两行之间移动。

You can prevent this by making sure that any attempts to draw to the screen are synchronized by using a lock: 您可以通过使用锁定来确保同步任何绘制到屏幕的尝试来避免这种情况:

private static object consoleLock = new object();

private static void Drawing(int x, int y, string symbol)
{
    lock (consoleLock)
    {
        Console.SetCursorPosition(x, y);
        Console.Write(symbol);
    }
}

Having said all that, I would recommend not launching a separate thread for the laser shot, but instead writing your game using a standard main update/draw loop that updates the scene for a fixed timestep, then draws the entire scene. 说了这么多,我建议不要为激光射击启动一个单独的线程,而是使用标准的主更新/绘制循环编写您的游戏,该循环以固定的时间步长更新场景,然后绘制整个场景。 This will allow you handle things like the laser hitting something and disappearing etc. 这将使您能够处理诸如激光撞击和消失之类的事情。

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

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