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

2012/9/30

actor/counter

Stephon231 Stephon231

2012/9/30

#
i have a money counter which is in one of the actors, how can i get another actor also add to the same counter
nooby123 nooby123

2012/9/30

#
You can make one public money counter in ActorA and access it through ActorB.
// This is in ActorA

static int money_counter;
And in ActorB, you can write :
ActorA.money_counter = 0;
Stephon231 Stephon231

2012/10/1

#
what would the code be to add to the counter(Money = money + 5)?
nooby123 nooby123

2012/10/1

#
If you want to add it from ActorB :
ActorA.money_counter = ActorA.money_counter + 5;
davmac davmac

2012/10/1

#
nooby123, you're showing how to add a counter to one actor *class*, not just one particular actor. (It might work in this case - depending on what's required - but it is, in general, not good design). Stephon231, you should look at tutorial #6.
Stephon231 Stephon231

2012/10/4

#
what if the counter's code is Counter counter = 0;
danpost danpost

2012/10/4

#
'Counter counter' in itself tells the compiler that you have a variable call 'counter' and it is to hold a 'Counter' object. You cannot assign an 'int' or any other type to a variable of 'Counter' type; it must be an instance of the 'Counter' class. You can, however have an 'int' variable within the 'Counter' class. An example of a simple Counter class follows:
import greenfoot.*;
import java.awt.Color;

public class Counter extends Actor
{
    int value = 0;

    public Counter()
    {
        updateImage();
    }

    public void add(int amount)
    {
        value += amount;
        updateImage();
    }

    public int getValue()
    {
        return value;
    }

    private void updateImage()
    {
        setImage(new GreenfootImage("Score: " + value, 24, Color.black, new Color(0, 0, 0, 0)));
    }
}
Then, lets say you had an actor that will earn points.
// in the actor class act method (or method it calls)
if (whatever == true)  addToCounter(10);
// and add the following method
private void addToCounter(int addAmount)
{
    WorldName world = (WorldName) getWorld();
    Counter counter = (Counter) world.getObjects(Counter.class).get(0);
    counter.add(addAmount);
}
The above will work, provided you have exactly one Counter object, and it must be in the world. If you happen to have more, it would be best to have references to each one. If they are both for different actors of the same type (say, player1 and player2), it would be best to have the references in the Player class (so each player has a reference to their own Counter object).
You need to login to post a reply.