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

2014/3/28

How do I stop an if statement?....or should I be using a loop?

Roz Roz

2014/3/28

#
Hello! I'm working on my first game which is similar to pac man. The goal is for Patrick to collect shamrocks in order to earn a keg of beer. I have a counter which counts shamrocks and am trying to add one keg of beer for every 10 shamrocks that are collected. I've used an if statement which adds a keg when ten shamrocks have been collected, but I think it keeps adding kegs until the counter reaches 11. The kegs are placed on top of each other, so it is not apparent until you manually move a keg and find several underneath it. Here is the code I have so far: /** * Create a new Keg for every 10 shamrocks collected . */ private void createNewKeg() { if (counter.getValue() == 10 ) { getWorld().addObject(new Keg(), 130, 455); } // if (counter.getValue() ==20 ) // { // getWorld().addObject(new Keg(), 130, 455); // } // // if (counter.getValue() == 30 ) // { // getWorld().addObject(new Keg(), 160, 455); // } Any help would be greatly appreciated. Thanks! Roz
JasonZhu JasonZhu

2014/3/28

#
You can set the counter back to 0 instead of repeating many if statements, although putting return in there would kick it out of the method. Is the counter an int variable? Is the if statement in the act method?
Roz Roz

2014/3/28

#
Hi Jason. Thanks for responding. I have createNewKeg(); in the act method. I think the counter is an int variable.....here is the beginning of the counter class code: 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; The beginning of class Patrick and his act method look like this: public class Patrick extends Animal { private int shamrocksEaten; private Counter counter; /** * Create Patrick with a reference to the counter in the game. */ public Patrick(Counter pointCounter) { counter = pointCounter; shamrocksEaten = 0; } /** * Act - do whatever Patrick wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { checkKeys(); lookForShamrock(); createNewKeg(); //createNewMushroom(); }
danpost danpost

2014/3/28

#
You should call 'createNewKeg' from inside the 'lookForShamrock' method within the 'if' block that adds to the 'shamrocksEaten' field. That way, it is only called once each time the value of the 'shamrocksEaten' field changes.
Roz Roz

2014/3/28

#
Thank you both SO much for your help! This has been driving me crazy. I did exactly what you said Dan, and it worked. :). Thank you , thank you, thank you!
You need to login to post a reply.