From 527368907c2b1826cf67bb31f96ad1bb590574aa Mon Sep 17 00:00:00 2001 From: pekomon <5183385+pekomon@users.noreply.github.com> Date: Tue, 9 Sep 2025 07:35:31 +0300 Subject: [PATCH] fix: avoid premature win on mismatch --- .../presentation/viewmodel/GameViewModel.kt | 39 ++++++++++--------- .../viewmodel/GameViewModelTest.kt | 3 ++ 2 files changed, 23 insertions(+), 19 deletions(-) diff --git a/memorygame/app/src/main/java/com/example/pekomon/memorygame/presentation/viewmodel/GameViewModel.kt b/memorygame/app/src/main/java/com/example/pekomon/memorygame/presentation/viewmodel/GameViewModel.kt index a8caa82..f3b692a 100644 --- a/memorygame/app/src/main/java/com/example/pekomon/memorygame/presentation/viewmodel/GameViewModel.kt +++ b/memorygame/app/src/main/java/com/example/pekomon/memorygame/presentation/viewmodel/GameViewModel.kt @@ -74,32 +74,33 @@ class GameViewModel @Inject constructor( private fun checkForMatch() { if (selectedCards[0].imageRes == selectedCards[1].imageRes) { _score.value += 10 + _cards.update { currentCards -> + currentCards.map { card -> + if (selectedCards.any { it.id == card.id }) { + card.copy(isMatched = true) + } else card + } + } + selectedCards.clear() + soundManager.playPairSound() + checkIfGameWon() + } else { + //soundManager.playFlipSound() + viewModelScope.launch { + delay(800) _cards.update { currentCards -> currentCards.map { card -> - if (selectedCards.any { it.id == card.id }) { - card.copy(isMatched = true) - } else card + if (selectedCards.any { it.id == card.id }) { + card.copy(isFlipped = false) + } + else card } } selectedCards.clear() - soundManager.playPairSound() - } else { - //soundManager.playFlipSound() - viewModelScope.launch { - delay(800) - _cards.update { currentCards -> - currentCards.map { card -> - if (selectedCards.any { it.id == card.id }) { - card.copy(isFlipped = false) - } - else card - } - } - selectedCards.clear() - } + checkIfGameWon() } - checkIfGameWon() } +} private fun checkIfGameWon() { if (_cards.value.all { it.isMatched }) { diff --git a/memorygame/app/src/test/java/com/example/pekomon/memorygame/presentation/viewmodel/GameViewModelTest.kt b/memorygame/app/src/test/java/com/example/pekomon/memorygame/presentation/viewmodel/GameViewModelTest.kt index 7c0e917..51df8f4 100644 --- a/memorygame/app/src/test/java/com/example/pekomon/memorygame/presentation/viewmodel/GameViewModelTest.kt +++ b/memorygame/app/src/test/java/com/example/pekomon/memorygame/presentation/viewmodel/GameViewModelTest.kt @@ -60,8 +60,11 @@ class GameViewModelTest { vm.flipCard(2) vm.flipCard(3) vm.flipCard(4) + // Game should not be won immediately after a mismatch + assertFalse(vm.isGameWon.value) advanceTimeBy(800) advanceUntilIdle() + // And it should remain not won after cards reset assertFalse(vm.isGameWon.value) }