0
votes

So

I have a method that gets called on every second to add sprites to a scene.

What i want to do is be able to control the percentage rate of which sprite gets added when the method is called.

So i tried using

Math.Random() > .3; 

Basically this would be a 30% chance that the sprite would get added...correct?

So the problem with this was that i only have four sprites. So sometimes when the method was called no sprites would be added to the scene, when each time the method is called a sprite is added.

So tried using

    Random rand = new Random();

int itemNumber = rand.nextInt(4) + 1;

if (itemNumber == 1) {

The problem with this is this is totally controlled by the Random generator. When i want to be able to control the percentage of which sprite is added more or less.

So what would be my way of doing this??

2

2 Answers

1
votes

To start, this:

if(Math.Random() > .3)   

will pass 70% of the time, not 30%. If you want 30%, change it to <

EDIT:

Ok, so you want to ensure a sprite is called, and want to be able to control how often each particular sprite is called? What you need is a variable for each sprite that contains the odds of calling it. For example, this will return an int to represent each sprite:

final double[] mOdds = {0.10, 0.25, 0.30, 0.35};   
// note, mOdds totals 1.0

public int pickSprite()
{
    double rand = Math.Random();
    for(int i=0;i<mOdds.length;i++)
    {
        if(rand < mOdds[i])
            return i;
        rand -= mOdds[i];
    }
    return -1;                    // should never reach this
}

You could use arbitrary numbers in your mOdds that don't add to 1.0, but you'd have to modify it a bit. Basically, you just have to make sure that rand will give you a number between 0 and the total of all the mOdds if you want a sprite every turn.

Update 2:

In your drawing routine, you can call the above function to choose the sprite and draw accordingly:

...
switch(pickSprite())
{
case 0:
    // draw sprite 0
    break;
case 1:
    // draw sprite 1
    break;
case 2:
    // draw sprite 2
    break;
case 3:
    // draw sprite 3
    break;
}
...

Or, if you have the sprites in an array, it's even easier:

...
sprite[pickSprite()].draw(); // substitute however you draw
...

It all depends on your program flow, really. You should be able to adapt the concept to whatever routine you're using.

0
votes

If I understand correct. You need to generate a random number between 1-4 (including 1 and 4).

This code must give you a random number between 1-4 (including 1 and 4).

Math.ceil(Math.random()*4);