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

2018/9/23

Issues with executing code

Facehugger Facehugger

2018/9/23

#
I have these lines of code setup to change a boolean to false after a period of one second. Unfortunately the code within this class does not appear to execute when the run button is pressed. What would be the best way to ensure that this is triggered with the run button is utilized?
public class Cooldown{
    boolean Go=true;
    public void run(){
        if(Globals.cooldown==true){
                    
            try{
                Thread.sleep(1000);
            }
            catch(InterruptedException e){
                        
            }
            Globals.cooldown=false;
        }
    }
}
Super_Hippo Super_Hippo

2018/9/23

#
First, you don't need a class to switch a boolean. Second, the "run" method is probably not called from anywhere. And third, don't use threads.
private boolean bol = false;
private int bolTimer = 1000;

public void act()
{
    if (!bol)
    {
        if (--bolTimer<1) bol = true;
    }
}
Or just:
private int bolTimer = 1000;

public void act()
{
    if (bolTimer>0) bolTimer--;
}

public boolean getBol()
{
    return bolTimer==0;
}
danpost danpost

2018/9/23

#
If I understand what you are looking for correctly, Hippo is correct about not needing a Cooldown class; but, my interpretation is that you just need the following in your World subclass:
private long startTime;

/** the following method is automatically called when the 'Run' button is clicked
public void started()
{
    if (startTime == 0) cooldown();
}

private void cooldown()
{
    startTime =  = System.currentTimeMillis();
    while (System.currentTimeMillis() < startTime+1000) ; // ';' is same as '{ }'
}
With this, there will be a 1 second delay before act cycles begin when the 'Run' button is clicked to start the scenario. Pausing and clicking 'Run' a second time will not cause a delay. The cooldown method can also be called during run-time -- and can be used for any number of seconds. For example:
for (int i=0; i<10; i++) cooldown();
will create a 10 second cool-down period.
You need to login to post a reply.