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

2019/5/25

How can I make greenfoot choose a random world?

AmyIsBadAtCoding AmyIsBadAtCoding

2019/5/25

#
Basically I'm making a game where the player controls a plane and has to avoid the other planes. I have multiple worlds, and am trying to make it so when the plane touches the end of the world Greenfoot will choose which world out of a few to switch to, but I'm not sure how to go about doing it. I'm aware you can't just say or, but the following code is somewhat how I want it to work:

if (isAtEdge())
    {
        Greenfoot.setWorld(new SkyEnemy()); or Greenfoot.setWorld(new SkyEnemyTwo()); or Greenfoot.setWorld(new SkyEnemyThree());
    }
AmyIsBadAtCoding AmyIsBadAtCoding

2019/5/25

#
nvm I have big brain I worked it out lol
Super_Hippo Super_Hippo

2019/5/25

#
You didn't really work it out by the way. Your code: (at least that's what is in the other discussion)
if (isAtEdge())
{
    if (Greenfoot.getRandomNumber(4)==1)
    {
        Greenfoot.setWorld(new SkyEnemy());
    }
   if (Greenfoot.getRandomNumber(4)==2)
   {
       Greenfoot.setWorld(new SkyEnemyTwo());
    }
    if (Greenfoot.getRandomNumber(4)==3)
    {
        Greenfoot.setWorld(new SkyEnemyThree());
    }
}
First of all, "getRandomNumber(4)" returns one of {0,1,2,3}. So if 0 is returned, nothing happens. However, you get three random numbers instead of getting one. So even if you would use 3 instead of 4 and reduce the 1,2,3 by 1, there is still a good chance that it doesn't work. Doesn't work here means that it is not always triggered immediately when the object reaches the end of the world.
if (isAtEdge())
{
    int randomWorld = Greenfoot.getRandomNumber(3);
    if (randomWorld == 0) Greenfoot.setWorld(new SkyEnemy());
    else if (randomWorld == 1) Greenfoot.setWorld(new SkyEnemyTwo());
    else if (randomWorld == 2) Greenfoot.setWorld(new SkyEnemyThree());
}
Or more simple:
if (isAtEdge())
{
    switch (Greenfoot.getRandomNumber(3))
    {
        case 0: Greenfoot.setWorld(new SkyEnemy()); break;
        case 1: Greenfoot.setWorld(new SkyEnemyTwo()); break;
        case 2: Greenfoot.setWorld(new SkyEnemyThree()); break;
    }
}
But honestly, I doubt that you would ever need three world classes like that.
AmyIsBadAtCoding AmyIsBadAtCoding

2019/5/25

#
I've never ever got that error, so I don't know if It's because I use the version my school uses
Super_Hippo Super_Hippo

2019/5/25

#
Well, if there are 60 act cycles a second, the chance that you notice it is small, but it can happen that the object is already at the edge of the world for some act cycles before the world actually changes.
You need to login to post a reply.