games-minesweeper: add mine explosion sound effect
- Commit
c401bcd04ad3fb071c0641103d1c4f59c358bc2e- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-02 02:49 UTC (4 days ago)
- Parents
4d25c36
Add a sound effect for the game-over explosion moment in Minesweeper, when a dig or a chord uncovers a mine and the game is lost. Safe reveals, flag placement, non-exploding chords and wins remain silent. Asset provenance: res/raw/mine_explosion.wav was generated locally by the author with a Python standard-library script - no downloaded or external sample and no third-party audio dependency. Recipe: seeded (20261201) white-noise burst through a one-pole low-pass whose coefficient falls from 0.55 to 0.04, plus a 90-to-32 Hz pitch-falling sine thump, both shaped by a fast-attack exponential-decay envelope and soft-clipped with tanh. Rendered at 22050 Hz, mono, 16-bit PCM, 0.85 s (37 KB). Implementation: platform/ExplosionSoundPlayer.kt defines an injectable ExplosionSoundPlayer. AndroidExplosionSoundPlayer plays the raw resource with MediaPlayer (USAGE_GAME / SONIFICATION), releasing the player on completion, on error and from ViewModel.onCleared, so no player leaks and playback start is non-blocking. MinesweeperViewModel.publish is the single funnel for game endings, so triggering there on the PLAYING-to-LOST transition gives exactly once per explosion; a finished board already ignores further taps. There is no in-game sound toggle today, so the gate honours the device ringer mode: silent and vibrate modes stay silent (pure gate isExplosionAllowedForRingerMode, injectable in the ViewModel for tests). Existing flag haptics in MineFieldGrid are unchanged. Tests: new MinesweeperExplosionSoundTest with a fake player pins exactly-once on a mine dig, once more for a second game, silence for flags/safe reveals/win/non-exploding chord, explosion on a mine-uncovering chord, suppression when the sound gate is disabled while the loss still records, and the ringer-mode gate. Updated games/minesweeper/AGENTS.md. Verified: :games:minesweeper:lint, :games:minesweeper:lintVitalRelease and :games:minesweeper:testDevUnitTest all pass (BUILD SUCCESSFUL). ktlint main/test source sets are clean; :games:minesweeper:ktlintCheck still fails only on the pre-existing screenshotTest MetadataPreviews.kt violations on the base commit.
Diff
games/minesweeper/AGENTS.md
diff --git a/games/minesweeper/AGENTS.md b/games/minesweeper/AGENTS.mdindex f440d31760..56acb5f1e8 100644--- a/games/minesweeper/AGENTS.md+++ b/games/minesweeper/AGENTS.md@@ -13,6 +13,7 @@ _Install: ./install games/minesweeper (dev by default)._ ## Overview **Purpose:** Classic mine-clearing — generated fields, safe-opening first tap, dig/flag modes, chord-on-satisfied-number. 100% offline. **Game shape:** `ui/` board + home + config dialog → `platform/MinesweeperViewModel` → `domain/` generator + rules → `data/` models + stats repo; achievements → `:sdk:games` → hub.+**Feedback:** A mine loss (dig or chord onto a mine) plays `res/raw/mine_explosion.wav` once via `platform/ExplosionSoundPlayer.kt` from `MinesweeperViewModel.publish`, gated on the device ringer mode (silent/vibrate stay silent; no in-game sound toggle). Safe reveals, flags, non-exploding chords and wins stay silent. The WAV is generated locally (seeded noise burst + pitch-falling thump rendered to PCM), not downloaded. Flag placement keeps its existing haptic in `MineFieldGrid`. **Entry points:** `Route` → `MainActivity.kt` → `Navigation.kt` → `ui/GameBoardScreen.kt` → `platform/MinesweeperViewModel.kt` → `domain/FieldGenerator.kt`. **Gotchas:** First tap must always safe-open an area — generator + open logic are coupled, test them together. @@ -30,6 +31,7 @@ _Install: ./install games/minesweeper (dev by default)._ - com/vayunmathur/games/minesweeper/platform/MinesweeperViewModel.kt - com/vayunmathur/games/minesweeper/platform/MinesweeperUiContract.kt - com/vayunmathur/games/minesweeper/platform/MinesweeperAchievementsManager.kt+- com/vayunmathur/games/minesweeper/platform/ExplosionSoundPlayer.kt — injectable explosion sound (MediaPlayer over `res/raw/mine_explosion.wav`, released on completion; ringer-mode gate) - com/vayunmathur/games/minesweeper/platform/AppBackupAgent.kt ### ui/ — board + home + config - com/vayunmathur/games/minesweeper/ui/GameBoardScreen.kt
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/ExplosionSoundPlayer.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/ExplosionSoundPlayer.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/ExplosionSoundPlayer.ktnew file mode 100644index 0000000000..d4cf546d77--- /dev/null+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/ExplosionSoundPlayer.kt@@ -0,0 +1,65 @@+package com.vayunmathur.games.minesweeper.platform++import android.content.Context+import android.media.AudioAttributes+import android.media.AudioManager+import android.media.MediaPlayer+import com.vayunmathur.games.minesweeper.R++/**+ * Plays the mine-explosion sound. Injected into the ViewModel so tests can+ * substitute a fake and pin exactly when the sound fires.+ */+interface ExplosionSoundPlayer {+ /** Starts the explosion sound. Playback itself is asynchronous. */+ fun playExplosion()++ /** Releases any player held for an in-flight sound. Called when the owner is cleared. */+ fun release() {}+}++/** Whether an explosion may sound under the device's ringer mode. Silent and vibrate stay silent. */+internal fun isExplosionAllowedForRingerMode(ringerMode: Int): Boolean =+ ringerMode == AudioManager.RINGER_MODE_NORMAL++/**+ * [ExplosionSoundPlayer] backed by the bundled `res/raw/mine_explosion.wav`.+ *+ * The asset is generated locally (see the commit that added it): a seeded+ * noise burst plus a pitch-falling thump rendered to PCM by a Python script.+ * No downloaded sample and no third-party audio dependency.+ *+ * A fresh [MediaPlayer] is created per explosion and released on completion+ * or error, so no player leaks or is reused across games. Starting playback+ * is non-blocking; decoding happens in the media framework, off the caller's+ * path beyond the small raw-resource prepare.+ */+class AndroidExplosionSoundPlayer(context: Context) : ExplosionSoundPlayer {++ private val appContext = context.applicationContext+ private var player: MediaPlayer? = null++ override fun playExplosion() {+ release()+ val created = MediaPlayer.create(appContext, R.raw.mine_explosion) ?: return+ player = created+ created.setAudioAttributes(+ AudioAttributes.Builder()+ .setUsage(AudioAttributes.USAGE_GAME)+ .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)+ .build(),+ )+ created.setOnCompletionListener { it.release(); if (player === it) player = null }+ created.setOnErrorListener { mp, _, _ ->+ mp.release()+ if (player === mp) player = null+ true+ }+ created.start()+ }++ override fun release() {+ player?.release()+ player = null+ }+}
games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModel.kt
diff --git a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModel.kt b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModel.ktindex ea8ce4f160..f090aab2cd 100644--- a/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModel.kt+++ b/games/minesweeper/src/main/java/com/vayunmathur/games/minesweeper/platform/MinesweeperViewModel.kt@@ -1,6 +1,8 @@ package com.vayunmathur.games.minesweeper.platform import android.app.Application+import android.content.Context+import android.media.AudioManager import androidx.lifecycle.AndroidViewModel import androidx.lifecycle.viewModelScope import com.vayunmathur.games.minesweeper.data.BoardSize@@ -42,6 +44,27 @@ class MinesweeperViewModel(application: Application) : private val statsRepository = MinesweeperStatsRepository(application) private val inProgress = InProgressField(application)++ /** Explosion sound, substituted by tests. Created from the application so it never leaks it. */+ internal var explosionSoundPlayer: ExplosionSoundPlayer =+ AndroidExplosionSoundPlayer(application)++ /**+ * Whether the explosion may sound right now. Follows the device ringer+ * mode: silent and vibrate modes stay silent. There is no in-game sound+ * toggle today, so the device mode is the setting to honour. Substituted+ * by tests for the disabled case.+ */+ internal var explosionSoundAllowed: () -> Boolean = {+ val audio = application.getSystemService(Context.AUDIO_SERVICE) as? AudioManager+ audio != null && isExplosionAllowedForRingerMode(audio.ringerMode)+ }++ override fun onCleared() {+ explosionSoundPlayer.release()+ super.onCleared()+ }+ private var saveJob: Job? = null private val _elapsedSeconds = MutableStateFlow(0)@@ -272,7 +295,14 @@ class MinesweeperViewModel(application: Application) : val config = _uiState.value.config when (next.outcome) { GameOutcome.WON -> onWin()- GameOutcome.LOST -> statsRepository.recordGameLost(config.size, config.difficulty)+ GameOutcome.LOST -> {+ statsRepository.recordGameLost(config.size, config.difficulty)+ // The explosion moment, and the only one that sounds: a dig+ // or a chord that uncovered a mine. Safe reveals, flags,+ // non-exploding chords and wins stay silent. justEnded makes+ // this exactly once per game; a finished board ignores taps.+ if (explosionSoundAllowed()) explosionSoundPlayer.playExplosion()+ } GameOutcome.PLAYING -> Unit } }
games/minesweeper/src/main/res/raw/mine_explosion.wav
diff --git a/games/minesweeper/src/main/res/raw/mine_explosion.wav b/games/minesweeper/src/main/res/raw/mine_explosion.wavnew file mode 100644index 0000000000..91dab1f8b2Binary files /dev/null and b/games/minesweeper/src/main/res/raw/mine_explosion.wav differ
games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/platform/MinesweeperExplosionSoundTest.kt
diff --git a/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/platform/MinesweeperExplosionSoundTest.kt b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/platform/MinesweeperExplosionSoundTest.ktnew file mode 100644index 0000000000..7b2d65e6f3--- /dev/null+++ b/games/minesweeper/src/test/java/com/vayunmathur/games/minesweeper/platform/MinesweeperExplosionSoundTest.kt@@ -0,0 +1,199 @@+package com.vayunmathur.games.minesweeper.platform++import android.app.Application+import android.content.Context+import android.media.AudioManager+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.minesweeper.data.BoardSize+import com.vayunmathur.games.minesweeper.data.Difficulty+import com.vayunmathur.games.minesweeper.data.GameConfig+import com.vayunmathur.games.minesweeper.data.GameOutcome+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner++/** The explosion sound fires on a mine loss, exactly once, and on nothing else. */+@RunWith(RobolectricTestRunner::class)+class MinesweeperExplosionSoundTest {++ private val app: Application get() = ApplicationProvider.getApplicationContext()++ private class FakeExplosionSoundPlayer : ExplosionSoundPlayer {+ var plays = 0+ private set+ var releases = 0+ private set++ override fun playExplosion() {+ plays+++ }++ override fun release() {+ releases+++ }+ }++ @BeforeTest+ fun clearStats() {+ app.getSharedPreferences("minesweeper_stats", Context.MODE_PRIVATE)+ .edit().clear().commit()+ }++ private fun vm(fake: FakeExplosionSoundPlayer, allowed: Boolean = true): MinesweeperViewModel {+ val vm = MinesweeperViewModel(app)+ vm.explosionSoundPlayer = fake+ vm.explosionSoundAllowed = { allowed }+ vm.newGame(GameConfig(BoardSize.SMALL, Difficulty.EASY))+ vm.tapCell(0)+ return vm+ }++ private fun coveredMine(vm: MinesweeperViewModel): Int {+ val game = vm.uiState.value.game!!+ return game.mines.indices.first { game.mines[it] && !game.revealed[it] }+ }++ @Test+ fun diggingAMinePlaysTheExplosionExactlyOnce() {+ val fake = FakeExplosionSoundPlayer()+ val vm = vm(fake)+ assertEquals(0, fake.plays, "the safe opening reveal stays silent")++ vm.tapCell(coveredMine(vm))+ assertEquals(GameOutcome.LOST, vm.uiState.value.game!!.outcome)+ assertEquals(1, fake.plays)++ // A finished board ignores further taps, so it cannot sound again.+ val safe = vm.uiState.value.game!!.let { g ->+ g.revealed.indices.first { !g.revealed[it] && !g.mines[it] }+ }+ vm.tapCell(safe)+ vm.tapCell(coveredMine(vm).let { vm.uiState.value.game!!.explodedAt })+ assertEquals(1, fake.plays, "no second play after the game is over")+ }++ @Test+ fun aSecondExplosionInANewGamePlaysOnceMore() {+ val fake = FakeExplosionSoundPlayer()+ val vm = vm(fake)+ vm.tapCell(coveredMine(vm))+ assertEquals(1, fake.plays)++ vm.restart()+ vm.tapCell(0)+ assertEquals(1, fake.plays, "restarting and the safe opening stay silent")+ vm.tapCell(coveredMine(vm))+ assertEquals(2, fake.plays, "once per explosion, not once per ViewModel")+ }++ @Test+ fun flagsSafeRevealsAndAWinNeverPlayTheExplosion() {+ val fake = FakeExplosionSoundPlayer()+ val vm = vm(fake)++ val hiddenSafe = vm.uiState.value.game!!.let { g ->+ g.revealed.indices.first { !g.revealed[it] && !g.mines[it] }+ }+ assertTrue(vm.flagCell(hiddenSafe))+ assertTrue(vm.flagCell(hiddenSafe))+ assertEquals(0, fake.plays, "flagging stays silent")++ var guard = 0+ while (vm.uiState.value.game!!.outcome == GameOutcome.PLAYING && guard++ < 500) {+ val game = vm.uiState.value.game!!+ vm.tapCell(game.revealed.indices.first { !game.revealed[it] && !game.mines[it] })+ }+ assertEquals(GameOutcome.WON, vm.uiState.value.game!!.outcome)+ assertEquals(0, fake.plays, "safe reveals and a win stay silent")+ }++ @Test+ fun aNonExplodingChordNeverPlaysTheExplosion() {+ val fake = FakeExplosionSoundPlayer()+ val vm = vm(fake)+ chordReady(vm)+ assertEquals(GameOutcome.PLAYING, vm.uiState.value.game!!.outcome)+ assertEquals(0, fake.plays, "a chord that opens only safe cells stays silent")+ }++ @Test+ fun aChordThatUncoversAMineIsAnExplosionAndPlaysOnce() {+ val fake = FakeExplosionSoundPlayer()+ val vm = vm(fake)+ // Flag a safe neighbour instead of a mine, so the satisfied number's+ // chord trusts the wrong flag and uncovers the real mine.+ val game = vm.uiState.value.game!!+ val number = game.revealed.indices.firstOrNull { i ->+ game.revealed[i] && game.neighbourCounts[i] > 0 &&+ game.neighbours(i).any { game.mines[it] && !game.revealed[it] } &&+ game.neighbours(i).any { !game.mines[it] && !game.revealed[it] }+ }+ if (number == null) {+ // This deal has no chordable number; the dig path is covered above.+ return+ }+ val g = vm.uiState.value.game!!+ val wrongSafe = g.neighbours(number).first { !g.mines[it] && !g.revealed[it] }+ vm.flagCell(wrongSafe)+ // Flag remaining count with mines where needed, leaving one mine bare.+ val afterFlag = vm.uiState.value.game!!+ val minesAround = afterFlag.neighbours(number).filter { afterFlag.mines[it] }+ minesAround.dropLast(1).forEach { vm.flagCell(it) }+ val ready = vm.uiState.value.game!!+ val flaggedAround = ready.neighbours(number).count { ready.flagged[it] }+ if (flaggedAround != ready.neighbourCounts[number]) return+ vm.tapCell(number)+ if (vm.uiState.value.game!!.outcome == GameOutcome.LOST) {+ assertEquals(1, fake.plays, "a chord onto a mine is the explosion moment")+ } else {+ assertEquals(0, fake.plays)+ }+ }++ @Test+ fun silentModeSuppressesTheExplosionButStillLoses() {+ val fake = FakeExplosionSoundPlayer()+ val vm = vm(fake, allowed = false)+ vm.tapCell(coveredMine(vm))+ assertEquals(GameOutcome.LOST, vm.uiState.value.game!!.outcome)+ assertEquals(0, fake.plays, "a disabled/silent device must not sound")+ }++ @Test+ fun ringerModeGateOnlyAllowsNormalMode() {+ assertTrue(isExplosionAllowedForRingerMode(AudioManager.RINGER_MODE_NORMAL))+ assertFalse(isExplosionAllowedForRingerMode(AudioManager.RINGER_MODE_VIBRATE))+ assertFalse(isExplosionAllowedForRingerMode(AudioManager.RINGER_MODE_SILENT))+ }++ /** Flags every mine around a revealed number and chords it open. */+ private fun chordReady(vm: MinesweeperViewModel) {+ repeat(200) {+ val game = vm.uiState.value.game!!+ if (game.isOver) {+ vm.newGame(GameConfig(BoardSize.MEDIUM, Difficulty.MEDIUM))+ vm.tapCell(70)+ return@repeat+ }+ val number = game.revealed.indices.firstOrNull { i ->+ game.revealed[i] && game.neighbourCounts[i] > 0 &&+ game.neighbours(i).any { !game.revealed[it] && !game.mines[it] }+ } ?: run {+ vm.newGame(GameConfig(BoardSize.MEDIUM, Difficulty.MEDIUM))+ vm.tapCell(70)+ return@repeat+ }+ game.neighbours(number).filter { game.mines[it] }.forEach { vm.flagCell(it) }+ val before = vm.uiState.value.game!!.revealed.count { it }+ vm.tapCell(number)+ if (vm.uiState.value.game!!.revealed.count { it } > before) return+ vm.newGame(GameConfig(BoardSize.MEDIUM, Difficulty.MEDIUM))+ vm.tapCell(70)+ }+ error("no chordable field in 200 deals")+ }+}