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

2019/3/31

Act delay for method not working

ShatteredAsh ShatteredAsh

2019/3/31

#
public int turtlesEaten;
    World world = getWorld();
    private Actor announcement;
    private int delay;
    public Crab()
    {
        turtlesEaten=0;
    }

    /**
     * Act - do whatever the Crab wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        checkForArrowKeys(5);
        eatTurtle();
        endGame();
    } 

    public void endGame()
    {
        if(turtlesEaten == 12)
        {
            world.showText("You won!",300,30);
            Greenfoot.stop();
        }
    }

    public void eatTurtle()
    {
        if(isTouching(Turtle.class))
        {
            removeTouching(Turtle.class);
            turtlesEaten = turtlesEaten + 1;
            announcement = new TurtleDied();
            delay = 10;
            getWorld().addObject(announcement,300,30);
            if(delay == 0)
            {
                getWorld().removeObject(announcement);
            }
            else
            {
                delay--;
            }

        }
    }
This is an excerpt of the code for my Crab Class. I have a class called TurtleDied that is an image stating the crab ate a turtle. It shows up when my crab eats a turtle but won't disappear after a delay. My countdown starts at delay = 10 and counts down with delay-- until delay == 0, but the image stating the turtle was eaten is never removed. What am I missing?
danpost danpost

2019/3/31

#
You remove the turtle, so how is the code for the delay to be executed (the condition for that block of code to execute is eliminated). It is really not the right place for the delay, anyway. It should be moved to the TurtleDied class:
import greenfoot.*;

public class TurtleDied extends Actor
{
    int delay = 10;
    
    public void act()
    {
        if (--delay == 0) getWorld().removeObject(this);
    }
}
Remove lines 2 through 4 from your Crab class. Change 'world' in line 25 to 'getWorld()'.
ShatteredAsh ShatteredAsh

2019/3/31

#
Moving it to the TurtleDied class worked, and I got rid of the world and delay variable from the crab. Line 25 is because I want to announce a win or loss to my players. My only other idea would be to place a 600x400 image centered in my world announcing it, but placing images gives me problems lol
danpost danpost

2019/3/31

#
ShatteredAsh wrote...
Line 25 is because I want to announce a win or loss to my players. My only other idea would be to place a 600x400 image centered in my world announcing it, but placing images gives me problems lol
Not sure why you mention this. I was not saying to remove line 25 or anything like that.
You need to login to post a reply.