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

2017/4/24

Trying to make a counter

Nozarashi Nozarashi

2017/4/24

#
Hello, I'm trying to make a counter. I need some help here. This is the world's code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
public class Floor extends World
{
    /**
     * Constructor for objects of class Floor.
     *
     */
    public Floor()
    {   
        super(600, 400, 1);
    }
    Counter counter = new Counter();
     
    public Counter getCounter()
    {
        return counter;
    }
    private void prepare()
    {
         
        addObject(counter,6,0);
        Spider spider = new Spider();
        addObject(spider,5,1);
        Spider spider2 = new Spider();
        addObject(spider2,1,1);
    }
}
This is the counter's code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Counter extends Actor
{
    private int totalCount = 0;
     
    public Counter()
    {
        setImage(new GreenfootImage("0",20,Color.WHITE, Color.BLACK));
    }
     
    public void bumpCount(int amount)
    {
        totalCount += amount;
        setImage(new GreenfootImage("" + totalCount, 20, Color.WHITE, Color.BLACK));
    }
}
This is the spider's code:
1
2
3
4
5
6
7
8
9
10
Actor Ant;
Ant = getOneObjectAtOffset(0,0,Ant.class);
if (Ant !=null)
{
    World world;
    world = getWorld();
    world.removeObject(Ant);
    Floor floor = (Floor) getWorld();
    Counter counter = floor.getCounter();
    Counter.bumpCount(1);
I want to make it so everytime the spider eats an ant, the score goes up.
Nozarashi Nozarashi

2017/4/24

#
Anyone?
danpost danpost

2017/4/24

#
Line 10 should be:
1
counter.bumpCount(1);
'counter' with a lowercase 'c', which is the name given to the variable that holds the reference to the Counter object on line 9.
Nozarashi Nozarashi

2017/4/24

#
danpost wrote...
Line 10 should be:
1
counter.bumpCount(1);
'counter' with a lowercase 'c', which is the name given to the variable that holds the reference to the Counter object on line 9.
Okay, I'm not getting an error anymore, but when the spider eats the ant, the score doesn't go up.
danpost danpost

2017/4/24

#
You are probably manually adding the Counter object into the world and it is probably not the same object that the 'counter' field refers to. Add a call to the 'prepare' method in your world constructor and adjust where the actors are spawned at. Then compile and only manually add ants into the world.
Nozarashi Nozarashi

2017/4/24

#
danpost wrote...
You are probably manually adding the Counter object into the world and it is probably not the same object that the 'counter' field refers to. Add a call to the 'prepare' method in your world constructor and adjust where the actors are spawned at. Then compile and only manually add ants into the world.
It's working now. Cheers Danpost.
You need to login to post a reply.