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

2016/6/14

My Counter is not working? Please Help

coder04 coder04

2016/6/14

#
When the object eats something the counter will not increase World
{
    private int countDown = 0;
    Counter counter = new Counter();
    
    /**
     * Constructor for objects of class WombatWorld.
     * 
     */
    public WombatWorld()
    {    
        super(600, 400, 1); 

        prepare();
    }
    
        public Counter getCounter() 
    {
        return counter;
    }


    /**
     * Prepare the world for the start of the program. That is: create the initial
     * objects and add them to the world.
     */
    private void prepare()
    {
        Wombat wombat = new Wombat();
        addObject(wombat, 278, 152);
        Wombat wombat2 = new Wombat();
        addObject(wombat2, 215, 277);
        Crab crab = new Crab();
        addObject(crab, 455, 274);
        Counter counter = new Counter();
        addObject(counter, 61, 33);
    }
}
Object thats going to eat another object
import greenfoot.*;

/**
 * Write a description of class Wombat here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Wombat extends Actor
{
    /**
     * Act - do whatever the Wombat wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
    move(4);
        if (Greenfoot.getRandomNumber(100) < 10)    
    {
        turn(Greenfoot.getRandomNumber(90) - 45);
    }
    if (getX() <= 5 || getX() >= getWorld().getWidth() - 5)
    {
        turn(180);
    }
        if (getY() <= 5 || getY() >= getWorld().getWidth() - 5)
    {
        turn(180);
    }
}
}
And Counter
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;

/**
 * Write a description of class Counter here.
 * 
 * @author (your name) 
 * @version (a version number or a date)
 */
public class Counter extends Actor
{
    int score = 0;
    /**
     * Act - do whatever the Counter wants to do. This method is called whenever
     * the 'Act' or 'Run' button gets pressed in the environment.
     */
    public void act() 
    {
        setImage(new GreenfootImage("Score : " + score, 24, Color.BLUE, null));
    }    
    
    public void addScore()
    {
         score++;
    }
}
danpost danpost

2016/6/14

#
First, I see no code that tries to change the value of any Counter object (in fact, I do not see any "eating" either). Then, I see that the Counter object held by the 'counter' field is not going to be the same Counter object that you place into the world (remove line 34 -- so that the Counter object already created and saved in the 'counter' field is added into the world on the next line).
You need to login to post a reply.