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

2013/9/28

How do I have 2 act methods that remove objects run simultaneously without one erroring out the other?

JasonZhu JasonZhu

2013/9/28

#
    public void act() 
    {
        if (isPregnant()){
            gestationPeriod();
        }
        moveAround();
        eating();
        matingProcess();
        becomingHungry();
        growOlder();
    }  

    private void becomingHungry()
    {
        hungercycle++;
        if(hungercycle == MONTH){
            hungercycle = 0;
            hungerpoint--;
            if(hungerpoint == FULLNESS){
                stomach=false; // change variable to something that makes more sense
            }else{
                stomach=true;
            }
            if(hungerpoint == EMPTINESS){
                getWorld().removeObject(this);
            }
        }
    }

    private void growOlder()
    {
        cycles++;
        if( cycles == MONTH ) {
            cycles = 0;
            age++;
            if( age == LIFE_SPAN ) {
                getWorld().removeObject(this);
            }            
        }
    }
growingOlder and becomingHungry are erroring out each other. How do I fix this?
danpost danpost

2013/9/28

#
One way is to put a condition on the second one:
if (getWorld() != null) growOlder();
Another way is to create another method called 'checkDeath' and remove and place the 'if' blocks that remove the actor from the world into that method and call it from the act.
private void checkDeath()
{
    if (hungerpoint == EMPTINESS || age == LIFE_SPAN) getWorld().removeObject(this);
}

public void act()
{
    if (isPregnant()){
        gestationPeriod();
    }
    moveAround();
    eating();
    matingProcess();
    becomingHungry();
    growOlder();
    checkDeath();
}
JasonZhu JasonZhu

2013/9/28

#
How does that condition work? Can you explain please?
danpost danpost

2013/9/28

#
'getWorld()' returns the world object that the actor is in. When you create an actor object, it is not in a world and 'getWorld()' will return 'null'. When you add the actor object into a world, it will then return that world. When you remove the object from the world, it goes back to returning 'null'. By qualifying the call to 'growOlder' with 'if (getWorld() != null)', you are asking if the actor object is still in the world. Only if the object is in the world will the method 'growOlder' execute.
JasonZhu JasonZhu

2013/9/28

#
Thanks for the great explanation, I can make sense of it now.
You need to login to post a reply.