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

2014/3/24

Help With Score Counter

tristanisms tristanisms

2014/3/24

#
I need to make a counter count up by one every time my asteroid eats a spaceship. import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import java.awt.Color; /** * A simple counter with graphical representation as an actor on screen. * * @author mik * @version 1.0 */ 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; /** * Create a new counter, initialised to 0. */ public Counter() { background = getImage(); // get image from class value = 0; target = 0; updateImage(); } /** * Animate the display to count up (or down) to the current target value. */ public void act() { if (value < target) { value++; updateImage(); } else if (value > target) { value--; updateImage(); } } /** * Add a new score to the current counter value. */ public void add(int score) { target += score; } /** * Return the current counter value. */ public int getValue() { return value; } /** * Set a new counter value. */ public void setValue(int newValue) { target = newValue; value = newValue; updateImage(); } /** * Update the image on screen to show the current value. */ private void updateImage() { GreenfootImage image = new GreenfootImage(background); GreenfootImage text = new GreenfootImage("" + value, 22, Color.BLACK, transparent); image.drawImage(text, (image.getWidth()-text.getWidth())/2, (image.getHeight()-text.getHeight())/2); setImage(image); } }
danpost danpost

2014/3/24

#
Have actor (whichever one is checking for collision between asteroid and spaceship) get World object, 'getWorld' method of Actor class have world object get List object of all Counter objects in it, 'getObjects' method of World class have List object return first element from itself, 'get' method (one of them) of List class cast element returned from List object as Counter object, '(Counter)' have Counter object add one to its 'value' field, 'add' method of Counter class
You need to login to post a reply.