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

2015/3/6

Stopping a counter at zero

sophiaking sophiaking

2015/3/6

#
in my game i have a counter that decreases by a random negative number. I want the counter to stop running once it reaches zero. I know i must put an if statement inside the act method of the counter but im not sure what to put inside of the if statement.
Douggresham Douggresham

2015/3/6

#
do you think that you could post some of your code so that i can see what you are working with?
sophiaking sophiaking

2015/3/6

#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public void act()
    {
        if (target <= 0 )
        {
            System.out.println("Stop");
            Greenfoot.stop();
        }// ends the game when the counter equals zero
         
        if (value < target) {
            value++;
            updateImage();
        }
        else if (value > target) {
            value--;
            updateImage();
        }
        }
sophiaking sophiaking

2015/3/6

#
the "greenfoot.stop();" works except that because it decreases by a random number it will stop before it hits zero. i want it to stop directly at zero.
Douggresham Douggresham

2015/3/6

#
i would try making two separate methods inside the timer class. try making one that is called to start the timer which will begin to decrement the timer by some random number an update the image, then when the that method returns zero, call the stop timer method which will stop the program.
danpost danpost

2015/3/6

#
How about this for the 'if' block:
1
2
3
4
5
6
7
8
9
10
11
if (target <= 0)
{
    while (value > 0)
    {
        value--;
        updateImage();
        Greenfoot.delay(15); // adjust the value as needed
    }
    System.out.println("Stop");
    Greenfoot.stop();
}
If you do not want it to count down like that while all the actors are frozen, you could just set the value to zero:
1
2
3
4
5
6
7
if (target <= 0)
{
    value = 0;
    updateImage();
    System.out.println("Stop");
    Greenfoot.stop();
}
sophiaking sophiaking

2015/3/6

#
Thanks that worked!
You need to login to post a reply.