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

2015/12/21

Why wont it spawn a new Hamburger after the current one is gone

Infurno Infurno

2015/12/21

#
I'm trying to make it so when the turtle eats the hamburger, a new one will spawn randomly in the map, ive looked at other people's code and i cannot figure out what im doing wrong. I am still very inexperienced
public void eatHamburger()
[code]  
  {
        Actor hamburger = getOneObjectAtOffset(0, 0, Hamburger.class);
        if (hamburger != null) {
            getWorld().removeObject(hamburger);
            Greenfoot.playSound("eating.wav");
            Greenfoot.delay(25);
            hamburgersEaten = hamburgersEaten + 1; 
        }

        if (Greenfoot.getRandomNumber(100) < 1)
        {
            getWorld().addObject(new Hamburger(), 10, 60);
        }
    }
so i probably made a stupid mistake
Super_Hippo Super_Hippo

2015/12/21

#
Line 14 adds a new hamburger to the world at (10,60), not randomly. Instead, it is adding a hamburger in 1% of all act cycles. Remove lines 11 through 15 and add the following after line 9:
getWorld().addObject(new Hamburger(), getWorld().getWidth(), getWorld().getHeight());
danpost danpost

2015/12/21

#
If you want that the hamburger delay its appearance in the world, move the adding code outside the 'eatHamburger' method (maybe to an 'addHamburger' method) and add the condition that no hamburger be in the world:
private void addHamburger()
{
    if (getWorld().getObjects(Hamburger.class).isEmpty() && Greenfoot.getRandomNumber(100) < 1)
    {
        int x = Greenfoot.getRandomNumber(getWorld().getWidth());
        int y = Greenfoot.getRandomNumber(getWorld().getHeight());
        getWorld().addObject(new Hamburger(), x, y);
    }
}
Chances are the hamburger will reappear in about two seconds with this. To increase the possible delay, you could increase the random value of '100'; but, this could also make it take a much longer time to spawn. To set a maximum and minimum time for spawning, generate one value and save it in a field; have it count down the acts before spawning:
// instance field
private int spawnDelay;

// the method
private void addHamburger()
{
    if (getWorld().getObjects(Hamburger.class).isEmpty())
    {
        if (spawnDelay == 0)
        {
            int minTime = 100;
            int maxTime = 400;
            spawnDelay = minTime+Greenfoot.getRandomNumber(1+maxTime-minTime);
        }
        else
        {
            spawnDelay--;
            if (spawnDelay == 0)
            {
                int x = Greenfoot.getRandomNumber(getWorld().getWidth());
                int y = Greenfoot.getRandomNumber(getWorld().getHeight());
                getWorld().addObject(new Hamburger(), x, y);
            }
        }
    }
}
You need to login to post a reply.