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

2013/9/19

Help with a command please.

Dillybar Dillybar

2013/9/19

#
Hi, I was wondering how you can make greenfoot create a new object when there are less than a certain number of them. For example, if there are less than 10 worms I want to spawn a new worm. All help is appreciated, thanks.
SPower SPower

2013/9/19

#
Do this in a subclass of World:
// at the top:
import java.util.List;

// where you want to create the new object:
List worms = getObjects(Worm.class);
if (worms.size() < 10) {
    // add a new worm.
}
Dillybar Dillybar

2013/9/19

#
Hi, I tried that but it still wouldn't work. Here is my code. When I compile it says that there are no errors. import greenfoot.*; // (Actor, World, Greenfoot, GreenfootImage) import java.util.List; 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); addObject (new Crab(), 280, 280); addObject (new Worm(), Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber (560)); addObject (new Worm(), Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber (560)); addObject (new Worm(), Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber (560)); addObject (new Worm(), Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber (560)); addObject (new Worm(), Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber (560)); addObject (new Worm(), Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber (560)); addObject (new Worm(), Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber (560)); addObject (new Worm(), Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber (560)); addObject (new Worm(), Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber (560)); addObject (new Worm(), Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber (560)); spawnWorms(); } public void spawnWorms() { List worms = getObjects(Worm.class); if (worms.size() < 10) { addObject (new Worm(), Greenfoot.getRandomNumber(560), Greenfoot.getRandomNumber (560)); } } }
SPower SPower

2013/9/19

#
That's because you only do it once: in your constructor of your world. You have to put it in your act method, which gets executed every so-often (usually about 60 times per second).
public void act()
{
    spawnWorms();
}
Dillybar Dillybar

2013/9/19

#
Thank you very much! I'm a new programmer so this is all new to me
SPower SPower

2013/9/19

#
Doesn't matter, as long as you understand what you code!
You need to login to post a reply.