状态管理问题 |Android Jetpack Compose

State Management Issue | Android Jetpack Compose

提问人:Marwan Talal 提问时间:11/8/2023 最后编辑:Marwan Talal 更新时间:11/8/2023 访问量:42

问:

我试图在 Jetpack compose 中构建一个“记忆游戏”的简单示例。我构建了一个逻辑,即当用户点击一张卡片时,这张卡片就会翻转。但问题是这张牌在找到它的对子之前不会翻转!

@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()
    }
}
人造人 科特林 android-jetpack-compose 状态管理 可组合

评论


答: 暂无答案