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

2018/11/16

Counter not working

ckeegan ckeegan

2018/11/16

#
I am making a game and in the second level when the cars reach the bottom of the screen and are removed the counter is meant to increase by one but it isn't working. import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class cars extends Character { public void act() { driveDown(); endOfRoad(); } private Counter counter; public cars(Counter pointCounter) { counter = pointCounter; } public void driveDown() { setLocation(getX(), getY() + 7); } public void endOfRoad() { if (canSee(Car.class)) { collectItem(Car.class); Greenfoot.setWorld(new Level2GameOver ()); } if(getY() >= getWorld().getHeight() -1) { getWorld().removeObject(this); counter.add(1); } } } import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class Level2 extends World { /** * Constructor for objects of class Level2. * */ public Level2() { // Create a new world with 600x400 cells with a cell size of 1x1 pixels. super(800, 600, 1); act(); prepare(); } public void act() { Counter counter = new Counter (); addObject(counter, 58, 26); counter.setLocation(35, 35); if(Greenfoot.getRandomNumber(100) < 2) //this will make trucks randomley apear. { addObject(new cars(counter), Greenfoot.getRandomNumber(455) + 195, 0); //this keeps trucks on the road } } public void prepare() { Car car = new Car(); addObject (car, 400, 525); } } import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) public class Counter extends Actor { private static final Color transparent = new Color(0,0,0,0); private GreenfootImage background; private int value; private int target; public Counter() { background = getImage(); // get image from class value = 0; target = 0; updateImage(); } public void act() { if (value < target) { value++; updateImage(); } else if (value > target) { value--; updateImage(); } } public void add(int score) { target += score; } public int getValue() { return value; } public void setValue(int newValue) { target = newValue; value = newValue; updateImage(); } private void updateImage() { GreenfootImage image = new GreenfootImage(background); GreenfootImage text = new GreenfootImage("" + value, 22, Color.YELLOW, transparent); image.drawImage(text, (image.getWidth()-text.getWidth())/2, (image.getHeight()-text.getHeight())/2); setImage(image); } }
danpost danpost

2018/11/16

#
You create a Car object, but show a cars class. Cannot do anything about the counter until it is known what you are doing there. Remove act(); from the Level2 class constructor and then take the first 3 lines in act and move them to the prepare method.
You need to login to post a reply.