简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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