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

2021/1/13

need help with random numbers and switch statements

Zurah Zurah

2021/1/13

#
i am currently creating this terraria-like game for class, and i want to make the ores generate randomly, or rather, have a random chance of generating. i wanted to achieve this by making a Greenfoot.getRandomNumber() statement inside of a switch case, but it throws an error (required: int; found: int, int) this is an example switch statement of how i wanted to do this:
switch(a)
             {
                case 1:
                    gras grass = new gras();
                    int rng = Greenfoot.getRandomNumber(0, 10);
                    if(rng <= 3)    {
                    addObject(grass, x, y);
                }
}
i tried making the int = rng outside of the switch statement part, but that resulted in the same error I cant seem to find a way how to get around this limitation, so if any of you have any idea, please let me know ^^
Super_Hippo Super_Hippo

2021/1/13

#
It doesn’t have anything to do with the switch. The method has one parameter, not two. If you want to have a 30% chance to spawn a gras object, then do this:
if (Greenfoot.getRandomNumber(10)<3)
{
    addObject(new Gras(), x, y);
}
Note: I changed gras to Gras. Class names should be uppercase. You create the object in line 4. In 70% of the time, it will be discarded and not used. In my code, the object is only created when it will be added. The same thing might also apply to x and y which are created somewhere else and may not be used at all if no object is spawned.
Zurah Zurah

2021/1/13

#
thanks, i used a slightly different method of achieving the same goal but i have it working now ^^
You need to login to post a reply.