ZeppRock ZeppRock - 1 month ago 12
Java Question

Second card in memory wont turn face up

I'm trying to do a memory game and have a slight problem when i want to turn two cards up to be displayed for the player.

The thing that happen when i run my memory game is that the first cards displays correctly but when i click on the second card it keeps being face down unless it's a pair.

if (model.getCard(tile.getNr()).getCardState() == CardState.DOWN) {
model.getCard(tile.getNr()).setCardState(CardState.UP);
tile.setImg(model.getCard(tile.getNr()).getValue()); //sets the correct image onto the card
click--;
//test if equal
if (click == 0) {
for (Cards card1 : cards) {
if (card1.getCardState() == CardState.UP) {
if (tile.getNr() != cards.indexOf(card1)) {
if (model.getCard(tile.getNr()).getValue() == card1.getValue()) {
//if both cards are equal, set them both to paired
model.getCard(tile.getNr()).setCardState(CardState.PAIRED);
model.getCard(cards.indexOf(card1)).setCardState(CardState.PAIRED);
click = 2;
}
}
}
}

try {
Thread.sleep(500); //1000 milliseconds is one second.
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
for (Cards card1 : cards) {
if (card1.getCardState() != CardState.PAIRED && card1.getCardState() == CardState.UP) {
model.getCard(cards.indexOf(card1)).setCardState(CardState.DOWN);
tiles.get(cards.indexOf(card1)).setCardDown();
}
}
click = 2;
}
}


I have the delay so the player can see both of the cards before they turn over.

Thanks for helping!

Answer

With Thread.sleep(500); you block the application thread preventing the UI from updating. You need to wait in a way that allows the application thread to continue, e.g. using PauseTransition.

if (click == 0) {
    ... turn card face up ...

    PauseTransition transition = new PauseTransition(Duration.millis(500));
    transition.setOnFinished(evt -> {
        ... turn cards face down ...
    });
    transition.play();
}
Comments