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

2014/10/21

World Isn't Spawning New Actors

BryanGSMST BryanGSMST

2014/10/21

#
I have my code set up to spawn a new bread actor each time j/10 == 1, but it never spawns a new bread.
import greenfoot.*;  // (Actor, World, Greenfoot, GreenfootImage)

public class CrabWorld extends World
{
    /**
     * Create the crab world (the beach). Our world has a size 
     * of 560x560 cells, where every cell is just 1 pixel.
     */
    public CrabWorld() 
    {
        super(560, 560, 1);
        populateWorld();
        
         
}
public void act()
    {
        int j = 0;
        
        if (j/1 == 10 )
        {  
             addObject (new Bread(), Greenfoot.getRandomNumber (561), Greenfoot.getRandomNumber (561));
        } 
        else{
            j++;
        }
    }
public void populateWorld()
    {
        addObject (new Fly(), 150, 100);
        addObject (new Human(), 400, 100);
        
        int i = 0;
        
        for (i=0; i<10; i++) {
            addObject (new Bread(), Greenfoot.getRandomNumber (561), Greenfoot.getRandomNumber (561));
        }
    }
}
danpost danpost

2014/10/21

#
Line 18 is setting the value of 'j' to zero; so the condition in your next line, line 20, will always be 'false' ('j' will never be anything but zero). Declare 'j' outside of the method, changing it from a local variable to a instance field (a local variable exists until the method is exited, so the next time the method is executed the variable is re-created; an instance field exists as long as the object it belongs to exists -- in this case, your CrabWorld instance, or world object). After moving the line outside the method, you will need to reset the field to zero after ten is reached. So, add a line to reset it back to zero when you add a new Bread object into the world. You may also want to increase the limit from ten -- at that limit, you will end up with an over-abundance of bread in your world very rapidly.
BryanGSMST BryanGSMST

2014/10/21

#
danpost wrote...
Line 18 is setting the value of 'j' to zero; so the condition in your next line, line 20, will always be 'false' ('j' will never be anything but zero). Declare 'j' outside of the method, changing it from a local variable to a instance field (a local variable exists until the method is exited, so the next time the method is executed the variable is re-created; an instance field exists as long as the object it belongs to exists -- in this case, your CrabWorld instance, or world object). After moving the line outside the method, you will need to reset the field to zero after ten is reached. So, add a line to reset it back to zero when you add a new Bread object into the world. You may also want to increase the limit from ten -- at that limit, you will end up with an over-abundance of bread in your world very rapidly.
Thanks so much! :)
You need to login to post a reply.