In my game the player has a certain amount of lives that are recorded using a counter. How do I make the animation stop when the life count reaches 0?


1 | if (counter.getValue()== 0 ) Greenfoot.stop(); |
1 | int value = ((Counter)getWorld().getObjects(Counter. class ).get( 0 )).getValue(); |
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 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 | import greenfoot.*; // (World, Actor, GreenfootImage, and Greenfoot) import java.awt.Color; import java.awt.Graphics; /** *LifeCounter that displays a number with a text prefix. * * @author Michael Kolling * @version 1.0.2 */ public class LifeCounter extends Actor { private static final Color textColor = new Color( 0 , 0 , 0 ); private int value = 0 ; private int target = 0 ; private String text; private int stringLength; public LifeCounter() { this ( "" ); } public LifeCounter(String prefix) { text = prefix; stringLength = (text.length() + 2 ) * 10 ; setImage( new GreenfootImage(stringLength, 16 )); GreenfootImage image = getImage(); image.setColor(textColor); updateImage(); } public LifeCounter(String prefix, int lives) { text = prefix; stringLength = (text.length() + 2 ) * 10 ; target = lives; value = lives; setImage( new GreenfootImage(stringLength, 16 )); GreenfootImage image = getImage(); image.setColor(textColor); updateImage(); } public void act() { if (value < target) { value++; updateImage(); } else if (value > target) { value--; updateImage(); } } public void add( int score) { target += score; } public void subtract( int score) { target -= score; } public int getValue() { return value; } public int getTarget() { return target; } /** * Make the image */ private void updateImage() { GreenfootImage image = getImage(); image.clear(); image.drawString(text + value, 1 , 12 ); } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | public void lookForCrab() { if ( canSee(Crab. class ) ) { eat(Crab. class ); changeImage(); crabLives.subtract( 1 ); Greenfoot.playSound( "au.wav" ); if (!getWorld().getObjects(LifeCounter. class ).isEmpty()) { ((LifeCounter) getWorld().getObjects(LifeCounter. class ).get( 0 )).subtract( 1 ); if (LifeCounter.getValue()== 0 ) {Greenfoot.stop();} } } } |
1 2 3 4 5 6 7 8 9 10 11 12 | public void lookForCrab() { if (canSee(Crab. class )) { eat(Crab. class ); changeImage(); crabLives.subtract( 1 ); Greenfoot.playSound( "au.wav" ); // only the following was changed if (crabLives.getValue()== 0 ) Greenfoot.stop(); } } |