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

2013/2/15

Counting Objects

Gingervitis Gingervitis

2013/2/15

#
I am going to make an almost endless wave of zombies for level 10 of my Turtle Adventure game, and I want to to count how many zombies the BlasterBullet class will eat, but every time you hit the spacebar, a new BlasterBullet appears and will disappear at the world edge so the count never gets past 1. Are there any suggestions on how to make the count get past 1?
Gevater_Tod4711 Gevater_Tod4711

2013/2/15

#
If you declare the counting integer as static it will still exist after the object is removed. And it'll have the same value in every instance of the class.
danpost danpost

2013/2/15

#
Static fields (also known as 'class fields' because they belong to the class and not to the individual objects created within that class, although all objects of that class have access to those fields) retain their values from each compilation of the project to the next. Therefore, when resetting (or restarting) the scenario, the value will still have the value it had before it was reset. To avoid complications with this regard, make sure to set its initial value in the world constructor.
Gingervitis Gingervitis

2013/2/15

#
So, if I am understanding you guys correctly, I would write some thing that says "private static int x = y" in both the actor class and world?
danpost danpost

2013/2/15

#
No. You would declare a class field in the BlasterBullet class with:
public static int zombiesEaten = 0;
In your initial world constructor, you will need to set the initial value of it to zero with:
BlasterBullet.zombiesEaten = 0;
If you create a second instance of the initial world, you will have to pass the value of 'zombiesEaten' to it. Where you detect (in the BlaserBullet class) a zombie and eat it, you will have:
zombiesEaten++;
Gingervitis Gingervitis

2013/2/15

#
When I placed ' BlasterBullet.zombiesEaten = 0; ' in my world class, it gave me on error saying an identifier is expected.
danpost danpost

2013/2/15

#
You need to add the field to the BlasterBullet class in like manner as here:
public class BlasterBullet extends Actor
{
    public static int zombiesEaten=0;  // adding this line here
    
    public BlasterBullet()
    {
        // etc.
Gingervitis Gingervitis

2013/2/15

#
I did that and it compiled correctly, but just a test I set it to create a class at the 5th zombie eaten but it doesn't reset itself when I go to a new world.
danpost danpost

2013/2/15

#
My first post in this discussion thread should shed light as to why. If need be, you should reset it to zero when you have determined that a new world is to be instantiated.
if (BlasterBullet.zombiesEaten == 5)
{
    BlasterBullet.zombiesEaten=0;
    Greenfoot.setWorld( ... );
}
Gingervitis Gingervitis

2013/2/15

#
Ok. I guess that makes sense.
You need to login to post a reply.