This site requires JavaScript, please enable it in your browser!
Greenfoot back
allyand17
allyand17 wrote ...

2014/6/5

Spawning Objects At Different Rates?

allyand17 allyand17

2014/6/5

#
I wanted to know how I could do this, because this code isn't working.
public void spawnFood(int b)
    {
        if(a <= (b/2)+(b/4)) {
            addObject(ok, getWidth(), Greenfoot.getRandomNumber(getHeight()));
            a = Greenfoot.getRandomNumber(b);
        } else if(a > (b/2)+(b/4) && a <= ((b/2)+(b/4))+(((b/2)+(b/4))/4)) {
            addObject(bad, getWidth(), Greenfoot.getRandomNumber(getHeight()));
            a = Greenfoot.getRandomNumber(b);
        } else if(a > ((b/2)+(b/4))+(((b/2)+(b/4))/4) && a <= b) {
            addObject(good, getWidth(), Greenfoot.getRandomNumber(getHeight()));
            a = Greenfoot.getRandomNumber(b);
        } else {
            //Do Nothing
        }
    }
"ok" is supposed to be the most common, "bad" the second, and "good" should be rare, but they spawn at equal rates. I tried creating the integer a inside of the code and setting it to a random number right after, but it did the same thing. I'm currently setting b to 100.
danpost danpost

2014/6/5

#
The integer a should be set upon entering the method AND it should be local to the method (not declared as an instance field in the class):
public void spawnFood(int b)
{
    int a = Greenfoot.getRandomNumber(b);
    int y = Greenfoot.getRandomNumber(getHeight());
    if (a >= 100) return; // do nothing
    if (a > 93) addObject(good, getWidth(), y);
    else if (a>75) addObject(bad, getWidth(), y);
    else addObject(ok, getWidth(), y);
}
You can put a control on spawning anything by calling the 'spawnFood' method on a random number condition:
if (Greenfoot.getRandomNumber(100)<2) spawnFood(100);
// instead of using the following
spawnFood(100);
danpost danpost

2014/6/5

#
I am not sure that I understand the 'good'/'bad'/'ok' fields. You should probably be using 'new good()'/'new ok()'/ new bad()' instead (using the proper class names, of course).
You need to login to post a reply.