Home > Back-end >  How to draw numbers with exceptions
How to draw numbers with exceptions

Time:03-11

How to draw numbers with exceptions? For example I want to draw numbers between 1 and 4, but I dont't want to draw number 3.

I need it for my randomly movement function, I want to prevent certain movements.

void monsterMove()
{

    Random rnd = new Random();
    int movmentNumber = rnd.Next(1, 4);
    switch (movmentNumber)
    {
        case 1:
            Console.Clear();
            monster1PositionY = monster1.moveRight(monster1PositionY);
            map.movefillRightMonster(monster1PositionX, monster1PositionY);
            map.printBoard();
            break;

        case 2:
            Console.Clear();
            monster1PositionY = monster1.moveLeft(monster1PositionY);
            map.movefillLeftMonster(monster1PositionX, monster1PositionY);
            map.printBoard();
            break;

        case 3:
            Console.Clear();
            monster1PositionX = monster1.moveDown(monster1PositionX);
            map.movefillDownMonster(monster1PositionX, monster1PositionY);
            map.printBoard();
            break;

        case 4:
            Console.Clear();
            monster1PositionX = monster1.moveUp(monster1PositionX);
            map.movefillUpMonster(monster1PositionX, monster1PositionY);
            map.printBoard();
            break;
    }
}

I was looking for solution at stackoverflow and in other places, but coudn't find answer.

CodePudding user response:

You can maybe create an array of possible draws and select a random number corresponding to an index.

Random r = new Random();
int[] draws = new int[] {1, 2, 4};
int number = draws[r.Next(draws.Length)];

Edit: Oops it turns out that r.Next(int max) is exclusive, so it would be draws.Length and not draws.Length-1

  • Related