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

2014/3/16

Help with counter system

patrick26 patrick26

2014/3/16

#
Hi, Is there a way for whenever my actor (Bowser) obtains 10 coins to play a sound indicating that the game is won? Setting up a private integer equal to zero? Here is my code: import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Coin here. * * @author (your name) * @version (a version number or a date) */ public class Coin extends Actor { /** * Act - do whatever the Coin wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { setLocation(getX(),getY()+5); if(getY()>getWorld().getHeight()-3) { getWorld().removeObject(this); }else{ Actor bowser = getOneIntersectingObject(Bowser.class); if(bowser !=null) { Greenfoot.playSound("coin.wav"); getWorld().removeObject(this); } } } }
danpost danpost

2014/3/16

#
The correct way is to have Bowser count the coins collected. Add an int field in the Bowser class. Call it 'coins' or 'coinCount' or 'coinsCollected' -- whatever. Add a method in the Bowser class for 'foundCoin'. It will be called by the Coin class when Bower is detected and it will increment the value of the field and then check for a value of 10 to play the sound and indicate game over. In the Coin class where you have 'Actor bowser = getOneIntersectingObject(Bowser.class);', change it to 'Bowser bowser = (Bowser)getOneIntersectingObject(Bowser.class);'. As a Bowser type object, you can use 'bowser.foundCoin();' to run the new method in the Bowser class.
patrick26 patrick26

2014/3/16

#
Where exactly do I insert the 'bowser.foundCoin();' ?
danpost danpost

2014/3/16

#
Inside the 'if' block -- 'if (bowser != null) { ...'
patrick26 patrick26

2014/3/16

#
It worked! Thank you so much! :)
You need to login to post a reply.