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

2016/10/28

Countdown Fuel

mmoodle mmoodle

2016/10/28

#
Im building a rocket game where I want my fuel to countdown from 100 when the play presses the space bar. This is the code I have so far and nothing is working. Could someone give me a hand with this? private void updateFuelDisplay() { fuelElapsed=100; fuelElapsed=fuelElapsed-1; fuelDisplay.setImage(new GreenfootImage("Fuel:"+fuelElapsed, 24, java.awt.Color.white,null)); if (Greenfoot.isKeyDown("Space")) { fuelElapsed=(fuelElapsed-1)%10; updateFuelDisplay(); } }
danpost danpost

2016/10/28

#
The first statement within the method will reset the value of 'fuelElapsed' back to '100' every time the method is called. Its value should be set to 100 when the Rocket object is created (or when it is added into the world). Next, "Space" should be "space" (with a lowercase 's'). The two lines executed when the spacebar is pressed are both problematic. The first line will automatically sets 'fuelElapsed' to a value less then '10' and the second line called the method that is currently being executed. This is not unlike an infinite loop and will freeze the program until an exception is thrown (possibly a stack overflow). If you only want fuel to go down when the key is pressed, then any and all code you have in this method should be within the 'if' block (decreasing the value of 'fuelElapsed' and updating the display). You may also want to check the new value of the field to see if zero is reached and do something if so.
You need to login to post a reply.