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

2013/10/3

timer coding, need help :(

mattie1606 mattie1606

2013/10/3

#
os i am working for a project and the goal is to survive 60 seconds in the game, as you can see in the end that i tried something but didnt work :/ any help will be appreciated. import greenfoot.*; /** * Write a description of class Counter1 here. * * @author * @version 1.0.0 */ public class Counter1 extends Actor { private boolean running = false; private int millisElapsed = 0; private long lastTime = 0; public Counter1() { updateImage(); } public void start() { millisElapsed = 0; lastTime = 0; } public void gamePaused() { lastTime = 0; } public void act() { long time = System.currentTimeMillis(); if(lastTime != 0) { long diff = time - lastTime; millisElapsed += diff; } lastTime = time; updateImage(); win(); } public void updateImage() { // Calculate minutes & seconds elapsed int millis = millisElapsed % 1000; int secs = (millisElapsed / 1000) % 60; int mins = millisElapsed / 60000; // Convert these into text String millisText = String.format("%03d", millis); String secsText = String.format("%02d", secs); String minsText = "" + mins; String text = minsText + ":" + secsText + "." + millisText; // Update the image GreenfootImage img = new GreenfootImage(text, 25, null, null); setImage(img); } public void win() { if (millisElapsed == 60000) { Greenfoot.playSound("fanfare.wav"); Greenfoot.stop(); } } }
davmac davmac

2013/10/3

#
You haven't said what you mean by didn't work, but one problem I see is where you check millisElapsed in win() -
 if (millisElapsed == 60000)
This requires the milliseconds elapsed to be exactly 6000 and no more. I think it's not likely you'll always get that. You should probably have:
 if (millisElapsed >= 60000)
mattie1606 mattie1606

2013/10/4

#
davmac wrote...
You haven't said what you mean by didn't work, but one problem I see is where you check millisElapsed in win() -
 if (millisElapsed == 60000)
This requires the milliseconds elapsed to be exactly 6000 and no more. I think it's not likely you'll always get that. You should probably have:
 if (millisElapsed >= 60000)
the goal of the game is to survive for 60 seconds and after 60 seconds the game had to stop, which didnt work.. but with your help it did so thanks
You need to login to post a reply.