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

2013/1/13

Counter in many levels

moobe moobe

2013/1/13

#
Hi, I'm programming a Counter right now. I can add and subtract values when my actor collects a gift. Now the problem: How can I give the value to the new world? My idea: I have programmed an integer called "level". And then it says " if (level == 1) { Level1 lev = (Level1) getWorld(); lev.subtractToCounter(1); } if (level == 2) { Level2 lev = (Level2) getWorld(); lev.subtractToCounter(1); } . . . . This works, but I have 20 levels, so this is a bad idea. Are there any other options to make this easier?
Gevater_Tod4711 Gevater_Tod4711

2013/1/13

#
If you declare the counter as static it exists for the whole runtime and it isn't deletet because of a new world.
moobe moobe

2013/1/13

#
How can I do that? I know how to declare a static integer, but can a class really be static, so that when I remove the world the object of that class is still there?
moobe moobe

2013/1/13

#
OK, I've read that I could do this with a constructor. This sounds really difficulty, isn't there an other way to solve this problem?
danpost danpost

2013/1/13

#
With just one world, you could do:
public class Level extends World
{
    static int level;
    Counter counter = null;

    public Level()
    {
        this(new Counter());
        level=0;
    }

    public Level(Counter cntr)
    {
        super(600, 400, 1);
        counter = cntr;
        prepare();
    }

    // etc.
}
// then when changing worlds, use
level++;
Greenfoot.setWorld(new Level(counter));
danpost danpost

2013/1/13

#
As a side note: even if you remove the current world and do not use static fields, you can set the fields in the new world immediately with code like the following (requiring only the basic constructor without any parameters):
Level world = new Level();
Greenfoot.setWorld(world);
world.counter = counter; // passing the counter object
world.level = level+1; // passing the new level number
moobe moobe

2013/1/14

#
Hi, thanks for your answer, I've solved this problem before your post^^ I have an actor collecting items and have given him direct reference of the counter object now, because he's the one who creates the counter. I've made an integer which knows the current value of the counter. So every time I change the world I create a new counter with my actor. Then I type in counter.setValue(collected); and then is everything fine again - so I have no code in the world ;) Your second solution sounds great! Can I do that with all objects I want? Cause I have three counters in my game and I think it's more easier than the way I did it. And the positive thing: The world would it be again who creates my counter object, not my main actor :D
You need to login to post a reply.