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

2012/12/27

Countdown Issues

ctgreenfoot ctgreenfoot

2012/12/27

#
Hi again, I'm having some difficulties figuring out why the scenario doesn't stop when the countdown reaches zero. Any help would be greatly appreciated!
import greenfoot.*;  // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
import java.awt.Color;
import java.util.Calendar;

/**
 *  Displays a digital clock in HH:MM:SS format.
 */
public class CountdownClock extends Actor
{
    private int width  = 50;        // Dimensions of the display
    private int height = 20;
    private int prevSecond = -1;
    private int counter = 10;

    /**
     *  The constructor creates the actor's image.
     */
    public CountdownClock() {
        GreenfootImage image = new GreenfootImage(width, height);
        image.setColor(Color.WHITE);
        image.fill();
        image.setColor(Color.BLACK);
        image.drawRect(0, 0 ,width - 1, height - 1);
        setImage(image);
        updateDisplay(counter + ".0");
    }

    /**
     *  The clock is tick'd on every act() call, but the display changes
     *  only when the second's increments.
     */
    public void act()
    {
       if (counter > 0)
       {
           updateDisplay(tick());
       }
    }

    /**
     *  Increment the display string for the clock.
     */
    public String tick()
    {
        // Compose new display string
        Calendar calendar = Calendar.getInstance();
        int    sec  = calendar.get(Calendar.SECOND);
        int    tsec = calendar.get(Calendar.MILLISECOND) / 100;

        if (counter == 0)
        {
            return("0.0");
        }
        if (sec != prevSecond )
        {
            prevSecond = sec;
            counter = counter - 1;
        }
        return(counter + "." + tsec);
    }

    /**
     *  Update the clock with the new time string.
     */
    public void updateDisplay(String newTime)
    {
        // x and y relative to the image. baseline of leftmost character.
        int x = 5;
        int y = 15;
        // Repaint the clock display
        GreenfootImage image = getImage();
        image.setColor(Color.WHITE);
        image.fillRect(1, 1, width-2, height-2);    // "erase" the display
        image.setColor(Color.BLACK);
        image.drawString(newTime, x, y);
        setImage(image);
    }

    /**
     *	Returns the current value of the clock.
     */
    public int getCounter()
    {
	return counter;
    }
    
    private void endOfGame()
    {
        if (counter == 0)
        Greenfoot.stop() ;
    }
}
vonmeth vonmeth

2012/12/27

#
endOfGame method is never called to be checked. Add this to the act method:
public void act()  
    {  
       if (counter > 0)  
       {  
           updateDisplay(tick());  
       }
		endOfGame();
    }  
ctgreenfoot ctgreenfoot

2012/12/27

#
thanks!
You need to login to post a reply.