State Management Issue | Android Jetpack Compose

70 views Asked by At

I trying to build a simple example of a "Memory Game" in Jetpack compose. I built the logic that when a user clicks on a card that card will flip. But the issue is that the card won't flip until it finds its pair!

@Composable
fun MemoryGameApp() {

    val scope = rememberCoroutineScope()
    val cards = allCards
    val flippedCards = mutableListOf<MemoryGameCard>()
    var matchedPairs by remember { mutableIntStateOf(0) }

    
    MemoryGameBoard(cards = cards) { card ->


        if (card.isFaceUp || card.isMatched ) return@MemoryGameBoard

        if (flippedCards.size < 2) {
            card.isFaceUp = true
            flippedCards += card
            if (flippedCards.size == 2) {
                if (flippedCards[0].imageResId == flippedCards[1].imageResId) {
                    flippedCards.forEach {it.isMatched = true }
                    matchedPairs++
                    flippedCards.clear()
                }

   
                scope.launch {
                    delay(1000)  
                    flippedCards.forEach {it.isFaceUp = false}
                    flippedCards.clear()
                }
            }
        }
    }

    if (matchedPairs == cards.size / 2) {
        WinningMessage()
    }
}
0

There are 0 answers