简体   繁体   中英

How to randomly move the sprite to a certain point in the console C#

I have a sprite which moves randomly in the console. It moves left, right, up or down at a time

.Let's suppose that sprite starts to move from position X=5 , position Y=5

how can I make it go at a certain position in the screen for example at position X=20 and position Y=10 ?

public void Draw()
{
    Console.SetCursorPosition(PositionX, PositionY);
    Console.Write(Sprite);
}

public void RandomMove()
{
    var number = Random.Next(1, 5);
    switch (number)
    {
        case 1:
        PositionX++; //Move Down
        break;
        case 2:
        PositionX--; Move Up
        break;
        case 3:
        PositionY--; Move Left
        break;
        case 4:
        PositionY++; Move Right
        break;
    }
}
while(true)
{
    RandomMove();
    Draw()
}

Use Random to generate a random position

Take a look at Victor Laio's code example there. You need to provide two parameters to Next , a lower and an upper bound .

Make sure to put the cursor into a position that is visible on the screen.

In order to achieve that you can use the following static properties on the Console class:

  • Console.WindowTop - Gets the topmost visible position.
  • Console.WindowLeft - Gets the topmost visible position.
  • Console.WindowWidth - Gets the number of visible characters in a row.
  • Console.WindowHeight - Gets the number of visible rows in the console.

Put the cursor to the desired position

You can use the SetCursorPosition method. For example: Console.SetCursorPosition(10, 10);

Putting it all together

The following example sets the cursor to a random position on every keypress. Notice that I do not subtract 1 from maxLeft because Random.Next takes an exclusive upper bound.

internal class Program
{
    private static void Main(string[] args)
    {
        Random r = new Random();
        while (true)
        {
            Console.ReadKey();
            int minLeft = Console.WindowLeft;
            int maxLeft = Console.WindowLeft + Console.WindowWidth;
            int minTop = Console.WindowTop;
            int maxTop = Console.WindowTop + Console.WindowHeight;
            Console.SetCursorPosition(r.Next(minLeft, maxLeft), r.Next(minTop, maxTop));
            // ...
        }
    }
}

You can use the Random() class to get random values to your application. Below you can see an exemple:

Random rnd = new Random();
int random = rnd.Next(1, 13);

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