Modern Apps git

← Modern-Apps.git

kart: bank race wins and best laps at race finish

Commit
e3bde5f54170a74b3083cf8aa1e5252a45a1c048
Author
Vayun Mathur <[email protected]>
When
2026-11-21 11:14 UTC (15 days ago)
Parents
85bcaa2
races_won and best_lap_ms were read by the garage and
achievements but never written - permanently 0. finishRace
now banks through KartDataStore.recordRaceResult: a win (the
local seat finishing 1st) increments races_won, and a real
best lap replaces the stored one only when faster. The final
lap is folded in before the finish check so it counts.
Placeholder races (native engine unavailable) write nothing.

Tests cover the win rule, store monotonicity (worse/null laps
never write), the native gate end-to-end, and that placeholder
races still bank cups but not stats.
Verified: :games:kart:testDevUnitTest passes.

Diff

games/kart/src/main/java/com/vayunmathur/games/kart/data/KartDataStore.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/data/KartDataStore.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/data/KartDataStore.ktindex e4040ff2ba..6b2039a56a 100644--- a/games/kart/src/main/java/com/vayunmathur/games/kart/data/KartDataStore.kt+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/data/KartDataStore.kt@@ -19,7 +19,7 @@ class KartDataStore(private val context: Context) {      val currentCup: Flow<Int> = context.dataStore.data.map { it[CUP_KEY] ?: 0 } -    /** Lifetime race wins, counted by the race flow once it exists. */+    /** Lifetime race wins, banked by [recordRaceResult] when a native race finishes. */     val racesWon: Flow<Int> = context.dataStore.data.map { it[RACES_WON_KEY] ?: 0 }      /** Best lap in milliseconds; zero means no lap has been timed yet. */@@ -30,6 +30,26 @@ class KartDataStore(private val context: Context) {         context.dataStore.edit { prefs -> prefs[CUP_KEY] = cup }     } +    /**+     * Bank one finished native race: +1 win when [won], and [bestLapMs] replaces the stored+     * best only when it beats it.+     *+     * [bestLapMs] must be a real timed lap (from `LapTracker`): null (no lap completed) and+     * non-positive values never write. Zero stored means no lap has been timed yet, so the+     * first real lap always replaces it. Callers gate placeholder races out entirely (see+     * `KartViewModel.bankRaceStats`): this owner just applies the counters it is given, in a+     * single edit so a win and a new best land together.+     */+    suspend fun recordRaceResult(won: Boolean, bestLapMs: Long?) {+        context.dataStore.edit { prefs ->+            if (won) prefs[RACES_WON_KEY] = (prefs[RACES_WON_KEY] ?: 0) + 1+            if (bestLapMs != null && bestLapMs > 0L) {+                val stored = prefs[BEST_LAP_KEY] ?: 0L+                if (stored == 0L || bestLapMs < stored) prefs[BEST_LAP_KEY] = bestLapMs+            }+        }+    }+     private companion object {         val CUP_KEY = intPreferencesKey("current_cup")         val RACES_WON_KEY = intPreferencesKey("races_won")
games/kart/src/main/java/com/vayunmathur/games/kart/domain/KartRules.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/domain/KartRules.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/KartRules.ktindex cce664ddf2..1ed2e9aec4 100644--- a/games/kart/src/main/java/com/vayunmathur/games/kart/domain/KartRules.kt+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/KartRules.kt@@ -20,4 +20,14 @@ object KartRules {     /** The next cup after [cupIndex], or null once the last cup is cleared. */     fun nextCup(cupIndex: Int): Int? =         if (cupIndex + 1 < CUPS.size) cupIndex + 1 else null++    /**+     * Whether [winner] is a win for the local seat: 1st place in the final standings.+     *+     * Both race loops order standings by place/progress descending and pass the head of that+     * order as the winner, so a win is exactly `winner == localPlayerId`. A race with no+     * local seat (null id) or no winner is never a win.+     */+    fun isPlayerWin(winner: String?, localPlayerId: String?): Boolean =+        winner != null && localPlayerId != null && winner == localPlayerId }
games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartViewModel.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartViewModel.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartViewModel.ktindex b622c12390..571471d9e5 100644--- a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartViewModel.kt+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartViewModel.kt@@ -218,22 +218,25 @@ class KartViewModel(application: Application) : AndroidViewModel(application),                 }                 val standings = parseStandings(KartNative.getStandingsJson())                 if (standings.isEmpty()) continue+                val ordered = standings.sortedBy { it.place }+                val order = ordered.map { it.player }+                // Fold the local lap in before the finish check so the final lap's+                // time can count as this race's best lap.+                val nowMs = android.os.SystemClock.uptimeMillis()+                val lap = ordered.firstOrNull { it.player == seat }?.lap ?: 0+                lapState = LapTracker.onLapTick(prevLap, lap, nowMs, lapState)+                prevLap = lap                 if (standings.any { it.lap >= RACE_LAPS }) {-                    val ordered = standings.sortedBy { it.place }+                    // Standings sort by place ascending, so place 1 heads the order.                     finishRace(                         winner = ordered.first().player,-                        order = ordered.map { it.player },+                        order = order,+                        bestLapMs = lapState.times.bestLapMs,                     )                     return@launch                 }-                val ordered = standings.sortedBy { it.place }-                val order = ordered.map { it.player }                 buzzPlaceLosers(prevOrder, order, localSeats, lastBuzzMs)                 prevOrder = order-                val nowMs = android.os.SystemClock.uptimeMillis()-                val lap = ordered.firstOrNull { it.player == seat }?.lap ?: 0-                lapState = LapTracker.onLapTick(prevLap, lap, nowMs, lapState)-                prevLap = lap                 _racePhase.value = RacePhase.Racing(                     order = order,                     lapProgress = ordered.associate { it.player to it.progress },@@ -281,20 +284,24 @@ class KartViewModel(application: Application) : AndroidViewModel(application),                     }                 }                 newRace.tick(dt)+                // Same fold-before-finish as the native loop, so both loops hand+                // finishRace the same shape (the gate there drops placeholder stats).+                val lap = newRace.lapOf(seat)+                lapState = LapTracker.onLapTick(prevLap, lap, nowMs, lapState)+                prevLap = lap                 if (newRace.finished) {+                    // The leaderboard sorts by progress descending, so its head won.                     val order = newRace.leaderboard()                     finishRace(                         winner = newRace.winner() ?: order.first(),                         order = order,+                        bestLapMs = lapState.times.bestLapMs,                     )                     return@launch                 }                 val order = newRace.leaderboard()                 buzzPlaceLosers(prevOrder, order, localSeats, lastBuzzMs)                 prevOrder = order-                val lap = newRace.lapOf(seat)-                lapState = LapTracker.onLapTick(prevLap, lap, nowMs, lapState)-                prevLap = lap                 _racePhase.value = RacePhase.Racing(                     order = order,                     lapProgress = order.associateWith { newRace.lapProgress(it) },@@ -306,7 +313,7 @@ class KartViewModel(application: Application) : AndroidViewModel(application),             }         }     }-    private fun finishRace(winner: String, order: List<String>) {+    private fun finishRace(winner: String, order: List<String>, bestLapMs: Long?) {         tickJob?.cancel()         tickJob = null         // Celebration buzz for every remote phone still on the grid.@@ -320,10 +327,28 @@ class KartViewModel(application: Application) : AndroidViewModel(application),         val state = _uiState.value         viewModelScope.launch {             KartRules.nextCup(state.progress.currentCup)?.let { dataStore.saveCup(it) }+            bankRaceStats(winner, localPlayerId, bestLapMs)         }         race = null     } +    /**+     * Bank the lifetime counters for one finished race.+     *+     * [KartNative.isAvailable] is the gate: without the native engine the finish came from+     * the placeholder model, whose laps are model ticks rather than real lap times, so a+     * placeholder race writes nothing (no win, no best lap). A win is 1st place for the+     * local seat (see [KartRules.isPlayerWin]); [bestLapMs] is the local player's best lap+     * this race from `LapTracker`, already folded to include the final lap.+     */+    internal suspend fun bankRaceStats(winner: String, localPlayerId: String?, bestLapMs: Long?) {+        if (!KartNative.isAvailable) return+        dataStore.recordRaceResult(+            won = KartRules.isPlayerWin(winner, localPlayerId),+            bestLapMs = bestLapMs,+        )+    }+     /**      * Buzz the remote phones whose place worsened since the last tick. Local seats (this device      * plus gamepads) and AI karts are skipped before the host — its send no-ops for non-remote
games/kart/src/test/java/com/vayunmathur/games/kart/data/KartStoresTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/data/KartStoresTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/data/KartStoresTest.ktindex 62910baef2..e02bb7bbfd 100644--- a/games/kart/src/test/java/com/vayunmathur/games/kart/data/KartStoresTest.kt+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/data/KartStoresTest.kt@@ -30,6 +30,28 @@ class KartStoresTest {         assertEquals(0L, store.bestLapMs.first())         store.saveCup(0)         assertEquals(0, store.currentCup.first())+        // Lifetime counters: a win increments, a non-win does not; only a better+        // real lap replaces the best, and untimed/zero laps never write.+        store.recordRaceResult(won = true, bestLapMs = 60_000L)+        assertEquals(1, store.racesWon.first())+        assertEquals(60_000L, store.bestLapMs.first())+        store.recordRaceResult(won = false, bestLapMs = 70_000L)+        assertEquals(1, store.racesWon.first())+        assertEquals(60_000L, store.bestLapMs.first())+        store.recordRaceResult(won = true, bestLapMs = null)+        assertEquals(2, store.racesWon.first())+        assertEquals(60_000L, store.bestLapMs.first())+        store.recordRaceResult(won = false, bestLapMs = 0L)+        store.recordRaceResult(won = false, bestLapMs = -5L)+        assertEquals(2, store.racesWon.first())+        assertEquals(60_000L, store.bestLapMs.first())+        store.recordRaceResult(won = false, bestLapMs = 59_999L)+        assertEquals(2, store.racesWon.first())+        assertEquals(59_999L, store.bestLapMs.first())+        // Saving the cup still leaves the banked counters untouched.+        store.saveCup(0)+        assertEquals(2, store.racesWon.first())+        assertEquals(59_999L, store.bestLapMs.first())     }      @Test fun pairingStoreBytesKeysAndDeviceId() = runBlocking {
games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartLogicExtraTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartLogicExtraTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartLogicExtraTest.ktindex 3bc28bcce2..189ac479ca 100644--- a/games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartLogicExtraTest.kt+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartLogicExtraTest.kt@@ -39,6 +39,17 @@ class KartLogicExtraTest {         assertNull(KartRules.nextCup(CUPS.size + 5))     } +    @Test fun playerWinIsFirstPlaceForLocalSeatOnly() {+        // Standings order heads are the winners (place 1 / most progress), so a win+        // is exactly the local seat heading that order.+        assertTrue(KartRules.isPlayerWin("you", "you"))+        assertFalse(KartRules.isPlayerWin("ai-0", "you"))+        assertFalse(KartRules.isPlayerWin("remote-1", "you"))+        assertFalse(KartRules.isPlayerWin("you", null))+        assertFalse(KartRules.isPlayerWin(null, "you"))+        assertFalse(KartRules.isPlayerWin(null, null))+    }+     // --- LapTracker ---      @Test fun lapTickWithoutSeedRecordsNoDurationButAdvances() {
games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartViewModelTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartViewModelTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartViewModelTest.ktindex b41c40f86c..81a672b78f 100644--- a/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartViewModelTest.kt+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/platform/KartViewModelTest.kt@@ -7,6 +7,8 @@ import com.vayunmathur.games.kart.util.KartNative import com.vayunmathur.sdk.controller.ControllerButton import com.vayunmathur.sdk.controller.ControllerInput import java.util.concurrent.TimeUnit+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.runBlocking import org.junit.runner.RunWith import org.robolectric.RobolectricTestRunner import org.robolectric.Shadows.shadowOf@@ -102,6 +104,8 @@ class KartViewModelTest {             val vm = KartViewModel(app)             await("cup loads") { vm.uiState.value.cup != null }             val cupBefore = vm.uiState.value.progress.currentCup+            val wonBefore = vm.uiState.value.progress.racesWon+            val bestBefore = vm.uiState.value.progress.bestLapMs             vm.startRace()             pump(4_000)             await("placeholder racing") { vm.racePhase.value is RacePhase.Racing }@@ -117,6 +121,9 @@ class KartViewModelTest {             assertTrue(results.winner in results.order)             val expectedCup = com.vayunmathur.games.kart.domain.KartRules.nextCup(cupBefore) ?: cupBefore             await("cup banked") { vm.uiState.value.progress.currentCup == expectedCup }+            // A placeholder race writes no lifetime stats, even though it banked the cup.+            assertEquals(wonBefore, vm.uiState.value.progress.racesWon)+            assertEquals(bestBefore, vm.uiState.value.progress.bestLapMs)             vm.backToLobby()             assertTrue(vm.racePhase.value is RacePhase.Lobby)             // Starting from the lobby again works after results.@@ -133,6 +140,43 @@ class KartViewModelTest {         // Whatever cup a previous race banked, the garage mirrors the store exactly.         val cupIndex = vm.uiState.value.progress.currentCup         assertEquals(com.vayunmathur.games.kart.domain.KartRules.cupAt(cupIndex), vm.uiState.value.cup)-        assertEquals(0, vm.uiState.value.progress.racesWon)+        // Lifetime counters mirror the store exactly (a sibling test may have banked wins).+        assertEquals(runBlocking { vm.dataStore.racesWon.first() }, vm.uiState.value.progress.racesWon)+        assertEquals(runBlocking { vm.dataStore.bestLapMs.first() }, vm.uiState.value.progress.bestLapMs)+    }++    @Test fun nativeRaceStatsBankWinAndBestLapOnlyWhenNative() {+        val wasAvailable = KartNative.isAvailable+        try {+            val vm = KartViewModel(app)+            await("cup loads") { vm.uiState.value.cup != null }+            val won0 = vm.uiState.value.progress.racesWon+            val best0 = vm.uiState.value.progress.bestLapMs+            val fast = if (best0 > 1_000L) best0 - 1_000L else 45_000L+            KartNative.isAvailable = true+            // Win for the local seat (1st in the standings): win + better lap bank.+            runBlocking { vm.bankRaceStats("me", "me", fast) }+            await("win banked") {+                vm.uiState.value.progress.racesWon == won0 + 1 &&+                    vm.uiState.value.progress.bestLapMs == fast+            }+            // Non-win with a worse lap: neither counter moves.+            runBlocking { vm.bankRaceStats("ai-0", "me", fast + 10_000L) }+            pump(500)+            assertEquals(won0 + 1, vm.uiState.value.progress.racesWon)+            assertEquals(fast, vm.uiState.value.progress.bestLapMs)+            // A better lap without a win still replaces the best.+            runBlocking { vm.bankRaceStats("ai-0", "me", fast - 1L) }+            await("better lap banked") { vm.uiState.value.progress.bestLapMs == fast - 1L }+            assertEquals(won0 + 1, vm.uiState.value.progress.racesWon)+            // Placeholder gate: the same win with a far faster lap writes nothing.+            KartNative.isAvailable = false+            runBlocking { vm.bankRaceStats("me", "me", 1_000L) }+            pump(500)+            assertEquals(won0 + 1, vm.uiState.value.progress.racesWon)+            assertEquals(fast - 1L, vm.uiState.value.progress.bestLapMs)+        } finally {+            KartNative.isAvailable = wasAvailable+        }     } }