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

2012/11/20

limitating a number of objects

bonana bonana

2012/11/20

#
hey, how can I limitate a number of objects of the same class being in my world? for example: a maximum of 3 pencils should be on my desk ^^
SPower SPower

2012/11/20

#
This would be my solution:
// at the top:
import java.util.Hashtable;

// at the beginning of the class:
private Hashtable objectKindCount = new HashTable();

// somewhere in your class:
@Override
public void addObject(Actor object, x, y)
{
    Integer num = objectKindCount.get(object.getClass());
    int number = 0;
    if (num != null)
        number = num.intValue();
    if (number < limit) {
        super.addObject(object,x,y);
        objectKindCount.put((number +1), object.getClass());
    }
}
danpost danpost

2012/11/20

#
My solution would be to add a method (Actor object named "Pencil" to be limited to 3 instances)
public boolean canAddPencil()
{
    // in the world class, use this line
    return getObjects(Pencil.class).size() < 3;
    // or, in an actor class, use this line
    return getWorld().getObjects(Pencil.class).size() < 3;
}
Place the code in the class you are adding the pencils into the world from; and use
// if in the world class
if (canAddPencil()) addObject(new Pencil(), 100, 100); // wherever
// if in an actor class
if (canAddPencil()) getWorld().addObject(new Pencil(), 100, 100);
You need to login to post a reply.