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 ^^


1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // 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()); } } |
1 2 3 4 5 6 7 | 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 ; } |
1 2 3 4 | // 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 ); |