I'm new to Java and making a small game for practice.
if (doAllFaceUpCardsMatch == false) {
//run pause here//
concentration.flipAllCardsFaceDown();
} else {
concentration.makeAllFaceUpCardsInvisible();
}
I want to pause the game for two seconds here before it does
concentration.flipAllCardsFaceDown();
How would I go about pausing it?
Thread. sleep(5000) pause your execution for 5 sec and resume it again. If your have any code after this statement than it will executed after 5 sec of pause. OR it will execute code written after your if/else is completed.
Simply put, wait() is an instance method that's used for thread synchronization. It can be called on any object, as it's defined right on java.
sleep() Method: Method Whenever Thread. sleep() functions to execute, it always pauses the current thread execution. If any other thread interrupts when the thread is sleeping, then InterruptedException will be thrown.
You can use:
Thread.sleep(2000);
or
java.util.concurrent.TimeUnit.SECONDS.sleep(2);
Please note that both of these methods throw InterruptedException
, which is a checked Exception, So you will have to catch that or declare in the method.
Edit: After Catching the exception, your code will look like this:
if (doAllFaceUpCardsMatch == false) {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
concentration.flipAllCardsFaceDown();
} else {
concentration.makeAllFaceUpCardsInvisible();
}
Since you are new, I would recommend learning how to do exception handling once you are little bit comfortable with java.
For those just wanting a quick hack without having to bring in a library...
public class Timing {
public static void main(String[] args) {
int delay = 1000; // number of milliseconds to sleep
long start = System.currentTimeMillis();
while(start >= System.currentTimeMillis() - delay); // do nothing
System.out.println("Time Slept: " + Long.toString(System.currentTimeMillis() - start));
}
}
For high precision 60fps gaming this probably isn't what you want, but perhaps some could find it useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With