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

2017/1/30

Problem with adding an actor

Radu18 Radu18

2017/1/30

#
I made a frog that is supposed to be replaced by a snake once it eats 5 flies. However, it spawns 2 snakes. Does someone know how to make it so that only 1 snake is created? Frog:
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)

/**
 * Write a description of class Frog here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Frog extends Actor
{
    /**
     * Act - do whatever the Frog wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    int Flies=5;
    public void act() 
    {
        if(Greenfoot.isKeyDown("up"))
        {move(4);}
        if(Greenfoot.isKeyDown("left"))
        {turn(-3);}
        if(Greenfoot.isKeyDown("right"))
        {turn(3);}
        Actor Frog=getOneIntersectingObject(Wall.class);
        if(Frog!=null)
        {move(-4);}
        Actor fly;
        fly=getOneObjectAtOffset(0,0,Fly.class);
       if(fly!=null)
       {World world;
           world=getWorld();
           world.removeObject(fly);
           Flies=Flies-1;
    }    
    if(Flies==0)
    {getWorld().addObject(new Snake(), getX(), getY());
    
    }    
}
}
Snake: import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Snake here. * * @author (your name) * @version (a version number or a date) */ public class Snake extends Actor { /** * Act - do whatever the Snake wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { Actor frog; frog=getOneObjectAtOffset(0,0,Frog.class); if(frog!=null) {World world; world=getWorld(); world.removeObject(frog);} if(Greenfoot.isKeyDown("up")) {move(4);} if(Greenfoot.isKeyDown("left")) {turn(-3);} if(Greenfoot.isKeyDown("right")) {turn(3);} } }
danpost danpost

2017/1/30

#
Just change the value of Flies to '-1' when you spawn a snake.
Super_Hippo Super_Hippo

2017/1/30

#
The following happens: - frog eats the 5th fly and creates a snake at his current position next act cycle: - frog's Flies variable is still at 0 and he creates another snake - the snake created in the last act cycle eats the frog I am not sure why a frog is replaced by a snake which eats frogs, but you could remove the frog from the world at line 37. You can also put the whole 'if(Flies==0)' block after line 33.
Radu18 Radu18

2017/1/30

#
Thanks a lot, I'm quite new to Greenfoot
You need to login to post a reply.