kart: rumble triggers, AI rubber-banding, lap-time HUD
- Commit
4c5e8119da4d29651364e10bbd90b47dc486f3d9- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-18 05:41 UTC (1 month ago)
- Parents
1efe966
Diff
games/kart/src/main/java/com/vayunmathur/games/kart/domain/LapTracker.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/domain/LapTracker.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/LapTracker.ktnew file mode 100644index 0000000000..8c4ee90c05--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/LapTracker.kt@@ -0,0 +1,47 @@+package com.vayunmathur.games.kart.domain++/**+ * Lap times for the HUD: the last completed local lap and the best one this race.+ *+ * Milliseconds on the same clock the race loop reads; null until the first lap completes.+ */+data class LapTimes(+ val lastLapMs: Long? = null,+ val bestLapMs: Long? = null,+)++/**+ * Pure lap-increment bookkeeping for the race loops.+ *+ * The ViewModel keeps the [State] and feeds each tick's lap count; when the local lap count+ * rises, the time since the previous increment becomes the last lap (and the best, if it beats+ * it). Seed [State.lastIncrementMs] with the race-start timestamp so the opening lap times+ * itself from green. Pure so the increment detection is a JVM test; the loops stay thin.+ */+object LapTracker {++ /** Carried across ticks: when the last lap completed, plus the times so far. */+ data class State(+ val lastIncrementMs: Long? = null,+ val times: LapTimes = LapTimes(),+ )++ /**+ * Fold one tick's lap count into [state]. Returns [state] unchanged unless [lap] rose above+ * [prevLap]. The increment timestamp always advances to [nowMs], so the next lap times+ * itself from this tick.+ */+ fun onLapTick(prevLap: Int, lap: Int, nowMs: Long, state: State): State {+ if (lap <= prevLap) return state+ val duration = state.lastIncrementMs?.let { (nowMs - it).coerceAtLeast(0L) }+ val times = if (duration == null) {+ state.times+ } else {+ LapTimes(+ lastLapMs = duration,+ bestLapMs = state.times.bestLapMs?.coerceAtMost(duration) ?: duration,+ )+ }+ return State(lastIncrementMs = nowMs, times = times)+ }+}
games/kart/src/main/java/com/vayunmathur/games/kart/domain/PlaceholderRace.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/domain/PlaceholderRace.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/PlaceholderRace.ktindex ded8dcf374..452c8b8f9f 100644--- a/games/kart/src/main/java/com/vayunmathur/games/kart/domain/PlaceholderRace.kt+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/PlaceholderRace.kt@@ -8,7 +8,8 @@ import com.vayunmathur.games.kart.data.CUPS * * One lap is [TRACK_LENGTH] units; karts advance by throttle × [TOP_SPEED] per second, minus a * steering scrub. Positions are fractional progress in laps; [leaderboard] sorts by total progress.- * AI drivers hold a fixed pace with a wobble so they are beatable but not statues.+ * AI drivers hold pace × wobble plus a rubber-band boost off the leader's progress (see+ * [effectiveAiPace]), so they are beatable but not statues. * * Everything here is pure and timestepped ([tick] takes seconds), so the race is a JVM test and * the native engine only has to reproduce its shape, not its code.@@ -36,6 +37,46 @@ class PlaceholderRace( /** AI pace as a fraction of top speed, before the per-driver wobble. */ const val AI_PACE = 0.78f++ /**+ * Rubber-band gain: pace points earned per [RUBBER_STEP] laps of deficit behind the leader.+ * Mirrors the native engine's `RUBBER_GAIN`.+ */+ const val RUBBER_GAIN = 0.02f++ /**+ * Deficit step (in laps, fractional) that earns one [RUBBER_GAIN].+ * Mirrors the native engine's `RUBBER_STEP`.+ */+ const val RUBBER_STEP = 0.05f++ /**+ * Hard cap on effective AI pace: backmarkers close in, never teleport past.+ * Mirrors the native engine's `AI_PACE_MAX`.+ */+ const val AI_PACE_MAX = 0.95f++ /**+ * Rubber-band boost in pace points for a [deficitLaps]-lap deficit behind the leader.+ *+ * Formula: `floor(deficit / RUBBER_STEP) * RUBBER_GAIN` — +0.02 pace per 5% of a lap+ * down, same steps as the native engine, so mid-pack pace doesn't jitter as gaps breathe.+ * The leader (deficit <= 0) gets nothing; the cap lives in [effectiveAiPace].+ */+ fun rubberBoost(deficitLaps: Float): Float {+ if (deficitLaps <= 0f) return 0f+ return kotlin.math.floor(deficitLaps / RUBBER_STEP) * RUBBER_GAIN+ }++ /**+ * Effective AI pace for a driver with [wobble] sitting [deficitLaps] behind the leader:+ * base pace times wobble, plus the rubber-band boost, capped at [AI_PACE_MAX].+ *+ * The leader always runs bare `AI_PACE * wobble` — no leader slowdown, by design (see the+ * native `effective_pace` rustdoc for why).+ */+ fun effectiveAiPace(wobble: Float, deficitLaps: Float): Float =+ (AI_PACE * wobble + rubberBoost(deficitLaps)).coerceAtMost(AI_PACE_MAX) } private data class Kart(@@ -97,14 +138,17 @@ class PlaceholderRace( * Advance the race by [dtSeconds]. * * Steering scrubs speed (full lock costs ~18%, less while drifting); AI runs its pace ×- * wobble. Progress never goes backwards: braking to a standstill holds position.+ * wobble plus a rubber-band boost off the leader's progress (see [effectiveAiPace]).+ * Progress never goes backwards: braking to a standstill holds position. */ fun tick(dtSeconds: Float) { val dt = dtSeconds.coerceIn(0f, 1f)+ val leaderProgress = karts.maxOfOrNull { it.progress } ?: 0f for (kart in karts) { if (lapOf(kart) >= laps) continue val speed = if (kart.ai) {- TOP_SPEED * AI_PACE * kart.wobble+ val deficitLaps = (leaderProgress - kart.progress) / TRACK_LENGTH+ TOP_SPEED * effectiveAiPace(kart.wobble, deficitLaps.coerceAtLeast(0f)) } else { val control = controls[kart.id] ?: KartControl.NEUTRAL val scrub = 1f - kotlin.math.abs(control.steering) *
games/kart/src/main/java/com/vayunmathur/games/kart/domain/RumbleDecider.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/domain/RumbleDecider.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/RumbleDecider.ktnew file mode 100644index 0000000000..8bbac2a095--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/RumbleDecider.kt@@ -0,0 +1,46 @@+package com.vayunmathur.games.kart.domain++/**+ * Decides which remote karts buzz when the standings shuffle.+ *+ * Pure function of the previous tick's order, the new order, and per-player cooldowns, so the+ * tick loops stay thin and the decision is a JVM test. A player buzzes only when their place+ * worsens tick-over-tick (they got passed or hit); improving, holding still, joining mid-race,+ * and the very first tick never buzz. Local seats (this device plus plugged-in gamepads) and AI+ * karts never buzz: the host only holds sockets for remote phones (its rumble send no-ops for+ * every other slot), but the loop skips them before it even gets there. A per-player cooldown+ * (~1.5 s) stops a multi-pass pile-up from becoming a buzz storm.+ */+object RumbleDecider {++ /** Minimum milliseconds between buzzes for the same player. */+ const val COOLDOWN_MS = 1_500L++ /**+ * Player ids to buzz: remote humans whose place worsened from [prevOrder] to [newOrder] and+ * whose last buzz in [lastBuzzMs] is at least [cooldownMs] old.+ *+ * Orders are player ids, leaders first. Ids in [localPlayerIds] are this device's seats and+ * never buzz; ids starting with `ai-` are engine rivals with no phone to buzz. Ids with no+ * previous place (joined mid-race) have no baseline and stay silent.+ */+ fun decide(+ prevOrder: List<String>,+ newOrder: List<String>,+ localPlayerIds: Set<String>,+ lastBuzzMs: Map<String, Long>,+ nowMs: Long,+ cooldownMs: Long = COOLDOWN_MS,+ ): List<String> {+ if (prevOrder.isEmpty()) return emptyList()+ val prevPlace = prevOrder.withIndex().associate { (place, id) -> id to place }+ return newOrder.withIndex().mapNotNull { (place, id) ->+ if (id in localPlayerIds || id.startsWith("ai-")) return@mapNotNull null+ val was = prevPlace[id] ?: return@mapNotNull null+ if (place <= was) return@mapNotNull null+ val last = lastBuzzMs[id]+ if (last != null && nowMs - last < cooldownMs) return@mapNotNull null+ id+ }+ }+}
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 12b823f30f..bb50a0806a 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@@ -8,13 +8,16 @@ import com.vayunmathur.games.kart.data.KartDataStore import com.vayunmathur.games.kart.data.KartProgress import com.vayunmathur.games.kart.domain.GameInputLoop import com.vayunmathur.games.kart.domain.KartRules+import com.vayunmathur.games.kart.domain.LapTracker import com.vayunmathur.games.kart.domain.PlaceholderRace+import com.vayunmathur.games.kart.domain.RumbleDecider import com.vayunmathur.games.kart.util.KartNative import com.vayunmathur.library.util.AchievementsManager import com.vayunmathur.library.util.DailyChallengeStore import com.vayunmathur.library.util.DailyStreakReporter import com.vayunmathur.library.work.DailyPuzzleReminder import com.vayunmathur.library.work.DailyReminderSettings+import com.vayunmathur.sdk.controller.RumbleFeedback import kotlinx.coroutines.Job import kotlinx.coroutines.delay import kotlinx.coroutines.flow.MutableStateFlow@@ -239,6 +242,11 @@ class KartViewModel(application: Application) : AndroidViewModel(application), KartNative.startRace(seats) kartHost.host?.startRace() val itemLatch = mutableMapOf<String, Boolean>()+ val localSeats = localPlayerIds()+ var prevOrder: List<String> = emptyList()+ val lastBuzzMs = mutableMapOf<String, Long>()+ var prevLap = 0+ var lapState = LapTracker.State(lastIncrementMs = android.os.SystemClock.uptimeMillis()) tickJob?.cancel() tickJob = viewModelScope.launch { while (isActive) {@@ -267,11 +275,20 @@ class KartViewModel(application: Application) : AndroidViewModel(application), 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 = ordered.map { it.player },+ order = order, lapProgress = ordered.associate { it.player to it.progress },- playerLap = ordered.firstOrNull { it.player == seat }?.lap ?: 0,+ playerLap = lap, totalLaps = RACE_LAPS,+ lastLapMs = lapState.times.lastLapMs,+ bestLapMs = lapState.times.bestLapMs, ) } }@@ -281,6 +298,11 @@ class KartViewModel(application: Application) : AndroidViewModel(application), val newRace = PlaceholderRace(playerIds = seats) race = newRace kartHost.host?.startRace()+ val localSeats = localPlayerIds()+ var prevOrder: List<String> = emptyList()+ val lastBuzzMs = mutableMapOf<String, Long>()+ var prevLap = 0+ var lapState = LapTracker.State(lastIncrementMs = android.os.SystemClock.uptimeMillis()) tickJob?.cancel() tickJob = viewModelScope.launch { var lastMs = android.os.SystemClock.uptimeMillis()@@ -316,11 +338,18 @@ class KartViewModel(application: Application) : AndroidViewModel(application), 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) },- playerLap = newRace.lapOf(seat),+ playerLap = lap, totalLaps = RACE_LAPS,+ lastLapMs = lapState.times.lastLapMs,+ bestLapMs = lapState.times.bestLapMs, ) } }@@ -328,6 +357,8 @@ class KartViewModel(application: Application) : AndroidViewModel(application), private fun finishRace(winner: String, order: List<String>) { tickJob?.cancel() tickJob = null+ // Celebration buzz for every remote phone still on the grid.+ celebrate(order) kartHost.host?.endRace() _racePhase.value = RacePhase.Results(winner = winner, order = order) val state = _uiState.value@@ -345,6 +376,45 @@ class KartViewModel(application: Application) : AndroidViewModel(application), race = null } + /**+ * 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+ * slots anyway, but there is no reason to ask. Callers thread [prevOrder] through ticks and+ * let this update [lastBuzzMs] with who buzzed when.+ */+ private fun buzzPlaceLosers(+ prevOrder: List<String>,+ order: List<String>,+ localSeats: Set<String>,+ lastBuzzMs: MutableMap<String, Long>,+ ) {+ val nowMs = android.os.SystemClock.uptimeMillis()+ val buzz = RumbleDecider.decide(+ prevOrder = prevOrder,+ newOrder = order,+ localPlayerIds = localSeats,+ lastBuzzMs = lastBuzzMs,+ nowMs = nowMs,+ )+ for (id in buzz) {+ kartHost.host?.rumble(id, RumbleFeedback(durationMs = RUMBLE_HIT_MS, highFreq = 1f))+ lastBuzzMs[id] = nowMs+ }+ }++ /** One short buzz to every remote phone on the grid, so the finish lands on all of them. */+ private fun celebrate(order: List<String>) {+ val locals = localPlayerIds()+ for (id in order) {+ if (id in locals || id.startsWith("ai-")) continue+ kartHost.host?.rumble(id, RumbleFeedback(durationMs = RUMBLE_FINISH_MS, highFreq = 1f))+ }+ }++ /** Every seat driven from this device: the touch seat plus any plugged-in gamepads. */+ private fun localPlayerIds(): Set<String> =+ kartHost.lobby.value.slots.filter { !it.remote }.map { it.playerId }.toSet()+ /** * One native standings row. Parsed by hand (not kotlinx.serialization): the engine emits a * fixed tiny shape and the game must never crash the tick on a malformed frame.@@ -462,6 +532,12 @@ class KartViewModel(application: Application) : AndroidViewModel(application), /** Ticks per second for the placeholder race loop. */ private const val TICK_MS = 50L + /** Buzz length for a place-loss hit. */+ private const val RUMBLE_HIT_MS = 180++ /** Buzz length for the finish-line celebration. */+ private const val RUMBLE_FINISH_MS = 250+ /** Laps per race. Mirrors the placeholder's default. */ private const val RACE_LAPS = 3
games/kart/src/main/java/com/vayunmathur/games/kart/platform/RacePhase.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/RacePhase.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/RacePhase.ktindex dbc542aa19..3163c537c0 100644--- a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/RacePhase.kt+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/RacePhase.kt@@ -15,12 +15,16 @@ sealed interface RacePhase { /** * Live race. [order] is player ids (humans then AI) by progress descending; [lapProgress] * maps each id to 0..1 through its current lap; [playerLap] is this device's completed laps.+ * [lastLapMs] is how long the local player's last completed lap took, [bestLapMs] the best+ * local lap this race; both are null until the first lap completes. */ data class Racing( val order: List<String>, val lapProgress: Map<String, Float>, val playerLap: Int, val totalLaps: Int,+ val lastLapMs: Long? = null,+ val bestLapMs: Long? = null, ) : RacePhase /** Across the line. [winner] may be an AI id; [order] is the final standing. */
games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGameScreen.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGameScreen.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGameScreen.ktindex 25127fc10b..338f69fc95 100644--- a/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGameScreen.kt+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/ui/KartGameScreen.kt@@ -207,6 +207,22 @@ private fun RacingBody(phase: RacePhase.Racing) { style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.primary, )+ val lastLap = phase.lastLapMs?.let(::formatLapTime)+ if (lastLap != null) {+ Text(+ stringResource(R.string.race_last_lap, lastLap),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ }+ val bestLap = phase.bestLapMs?.let(::formatLapTime)+ if (bestLap != null) {+ Text(+ stringResource(R.string.race_best_lap, bestLap),+ style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ } phase.order.forEachIndexed { place, id -> Column(Modifier.fillMaxWidth()) { Text(@@ -221,6 +237,15 @@ private fun RacingBody(phase: RacePhase.Racing) { } } +/** Format a lap time as m:ss.mmm, e.g. 0:24.318. Null-safe at the call site: only called non-null. */+private fun formatLapTime(ms: Long): String {+ val total = ms.coerceAtLeast(0L)+ val minutes = total / 60_000+ val seconds = (total % 60_000) / 1_000+ val millis = total % 1_000+ return "$minutes:%02d.%03d".format(java.util.Locale.US, seconds, millis)+}+ /** Short label for a seat: players keep their join name, AI karts show as rivals. */ private fun displayName(id: String): String = if (id.startsWith("ai-")) "Rival ${id.removePrefix("ai-")}" else "You"
games/kart/src/main/res/values/strings.xml
diff --git a/games/kart/src/main/res/values/strings.xml b/games/kart/src/main/res/values/strings.xmlindex dd56d80e0f..db38c34e5f 100644--- a/games/kart/src/main/res/values/strings.xml+++ b/games/kart/src/main/res/values/strings.xml@@ -30,6 +30,10 @@ <string name="race_lap">Lap <xliff:g id="current" example="2">%1$d</xliff:g> of <xliff:g id="total" example="3">%2$d</xliff:g></string> <!-- KartGameScreen: One standings row. %1$d = place, e.g. 1. %2$s = driver name --> <string name="race_place"><xliff:g id="place" example="1">%1$d</xliff:g>. <xliff:g id="name" example="You">%2$s</xliff:g></string>+ <!-- KartGameScreen: Last completed lap time. %1$s = formatted time, e.g. 0:24.318 -->+ <string name="race_last_lap">Last lap <xliff:g id="time" example="0:24.318">%1$s</xliff:g></string>+ <!-- KartGameScreen: Best lap this race. %1$s = formatted time, e.g. 0:23.904 -->+ <string name="race_best_lap">Best lap <xliff:g id="time" example="0:23.904">%1$s</xliff:g></string> <!-- KartGameScreen: Results header. Noun phrase --> <string name="results_title">Final Standings</string> <!-- KartGameScreen: Back to the lobby from results. Verb phrase -->
games/kart/src/main/rust/src/items.rs
diff --git a/games/kart/src/main/rust/src/items.rs b/games/kart/src/main/rust/src/items.rsindex 4c62c44f8f..cdef9b09e5 100644--- a/games/kart/src/main/rust/src/items.rs+++ b/games/kart/src/main/rust/src/items.rs@@ -4,6 +4,9 @@ //! green shell that spins whoever it touches. AI drivers follow the racing //! line with per-driver pace and wobble, and fire shells forward when they //! hold one — beatable but not statues, mirroring the placeholder's 0.78 pace.+//! Backmarkers get a rubber-band pace boost that scales with their deficit+//! behind the leader (capped, so they close in without teleporting past);+//! the leader always runs base pace — no leader slowdown, by design. use crate::physics::{DriveInput, KartBody}; use crate::track;@@ -18,6 +21,12 @@ pub const SHELL_LIFE: f32 = 6.0; pub const BOX_RADIUS: f32 = 3.5; /// AI pace as a fraction of top speed, before the per-driver wobble. pub const AI_PACE: f32 = 0.78;+/// Rubber-band gain: pace points earned per [RUBBER_STEP] laps of deficit.+pub const RUBBER_GAIN: f32 = 0.02;+/// Deficit step (in laps, fractional) that earns one [RUBBER_GAIN].+pub const RUBBER_STEP: f32 = 0.05;+/// Hard cap on effective AI pace: backmarkers close in, never teleport past.+pub const AI_PACE_MAX: f32 = 0.95; /// What a kart is holding. One slot: firing spends it. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]@@ -82,6 +91,33 @@ pub struct AiDriver { pub steer: f32, } +/// Rubber-band boost in pace points for a deficit of [deficit_laps] laps+/// behind the leader (fractional, clamped at zero below).+///+/// Formula: `floor(deficit / RUBBER_STEP) * RUBBER_GAIN` — +0.02 pace per 5%+/// of a lap down. Steps (not a smooth ramp) so mid-pack pace doesn't jitter+/// every tick as gaps breathe; the leader (`deficit <= 0`) gets nothing.+/// The cap lives in [`effective_pace`], not here.+pub fn rubber_boost(deficit_laps: f32) -> f32 {+ if deficit_laps <= 0.0 {+ return 0.0;+ }+ (deficit_laps / RUBBER_STEP).floor() * RUBBER_GAIN+}++/// Effective AI pace for a driver with [wobble] sitting [deficit_laps] behind+/// the leader: base pace times wobble, plus the rubber-band boost, capped at+/// [`AI_PACE_MAX`].+///+/// The cap is what keeps the field together without teleporting: a far-back+/// rival closes at most ~0.95 pace, still beatable flat-out by a clean human+/// lap, while the leader always runs bare `AI_PACE * wobble` (no slowdown —+/// punishing clean driving up front felt worse in playtesting than letting a+/// spun-out rival catch back up).+pub fn effective_pace(wobble: f32, deficit_laps: f32) -> f32 {+ (AI_PACE * wobble + rubber_boost(deficit_laps)).min(AI_PACE_MAX)+}+ impl AiDriver { /// Create driver `index` of `count`: spread the wobble across the field. pub fn new(index: usize, count: usize) -> Self {@@ -97,8 +133,9 @@ impl AiDriver { } /// Drive one tick: steer toward a lookahead point on the racing line,- /// hold the throttle at pace, drift when the corner is tight.- pub fn control(&mut self, kart: &KartBody) -> DriveInput {+ /// hold the throttle at pace (plus the rubber-band boost for+ /// [deficit_laps] behind the leader), drift when the corner is tight.+ pub fn control(&mut self, kart: &KartBody, deficit_laps: f32) -> DriveInput { let ahead_s = track::advance(kart.track_s, 12.0); let ahead = track::point_at(ahead_s); let dx = ahead.x - kart.x;@@ -110,7 +147,7 @@ impl AiDriver { self.steer += (target - self.steer) * 0.18; let tight = err.abs() > 0.45; DriveInput {- throttle: AI_PACE * self.wobble,+ throttle: effective_pace(self.wobble, deficit_laps), steering: self.steer, brake: 0.0, drift: tight,@@ -163,7 +200,7 @@ mod tests { kart.speed = crate::physics::TOP_SPEED * AI_PACE; let mut ai = AiDriver::new(0, 4); for _ in 0..1200 {- let c = ai.control(&kart);+ let c = ai.control(&kart, 0.0); kart.tick(&c, 1.0 / 60.0); } let p = track::point_at(kart.track_s);@@ -176,6 +213,45 @@ mod tests { ); } + #[test]+ fn backmarker_gets_pace_boost_leader_gets_none() {+ let wobble = 0.95;+ let base = AI_PACE * wobble;+ assert_eq!(rubber_boost(0.0), 0.0, "leader runs bare base pace");+ assert_eq!(effective_pace(wobble, 0.0), base);+ assert!(+ effective_pace(wobble, 0.10) > base,+ "a tenth of a lap down should earn a boost"+ );+ }++ #[test]+ fn boost_steps_and_shrinks_as_deficit_closes() {+ // One step (5% of a lap) earns exactly RUBBER_GAIN a step.+ assert_eq!(rubber_boost(RUBBER_STEP), RUBBER_GAIN);+ assert_eq!(rubber_boost(RUBBER_STEP * 2.0), RUBBER_GAIN * 2.0);+ // Below one step earns nothing; closing the gap shrinks the boost.+ assert_eq!(rubber_boost(RUBBER_STEP * 0.5), 0.0);+ assert!(+ rubber_boost(0.20) > rubber_boost(0.05),+ "closer to the leader means less boost"+ );+ // Non-positive deficits (leader, rounding noise) never boost.+ assert_eq!(rubber_boost(-0.5), 0.0);+ }++ #[test]+ fn pace_cap_holds_for_far_backmarkers() {+ assert!(+ effective_pace(1.0, 10.0) <= AI_PACE_MAX,+ "even a lap down stays at or under the cap"+ );+ assert!(+ effective_pace(0.90, 10.0) <= AI_PACE_MAX,+ "slow-wobble drivers cap too"+ );+ }+ #[test] fn shell_hits_a_kart_ahead() { let owner = KartBody::spawn(0.0, 0.0);
games/kart/src/main/rust/src/race.rs
diff --git a/games/kart/src/main/rust/src/race.rs b/games/kart/src/main/rust/src/race.rsindex f76b0f850d..bd073cf4bb 100644--- a/games/kart/src/main/rust/src/race.rs+++ b/games/kart/src/main/rust/src/race.rs@@ -135,20 +135,26 @@ impl Race { b.respawn_left -= dt; } }- // Order first: items deal by race position.+ // Order first: items deal by race position, and AI paces itself off+ // the leader's progress (rubber-banding). let mut order: Vec<usize> = (0..self.seats.len()).collect(); order.sort_by(|&a, &b| { progress_key(&self.seats[b].kart) .partial_cmp(&progress_key(&self.seats[a].kart)) .unwrap_or(std::cmp::Ordering::Equal) });+ let leader_progress = order+ .first()+ .map(|&si| progress_key(&self.seats[si].kart))+ .unwrap_or(0.0); for (pos, &si) in order.iter().enumerate() { // Read the seat's state first (immutable borrows end here). let seat_count = self.seats.len(); let (control, should_fire, held_item, kx, kz) = { let seat = &mut self.seats[si]; let mut control = if let Some(ai) = &mut seat.ai {- let mut c = ai.control(&seat.kart);+ let deficit = leader_progress - progress_key(&seat.kart);+ let mut c = ai.control(&seat.kart, deficit.max(0.0)); // AI fires shells at the kart ahead, mushrooms on straights. if seat.held == HeldItem::Shell && pos > 0 { c.item = true;
games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartRaceTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartRaceTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartRaceTest.ktindex 59f9eb2e84..0c8f5d71f3 100644--- a/games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartRaceTest.kt+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/domain/KartRaceTest.kt@@ -143,4 +143,139 @@ class KartRaceTest { straight.tick(1f) assertTrue(drift.lapProgress("p1") < straight.lapProgress("p1")) }++ @Test+ fun placeLossTriggersRumble() {+ // remote-1 drops from 2nd to 3rd (got passed); remote-2 climbs past them.+ val buzzed = RumbleDecider.decide(+ prevOrder = listOf("you", "remote-1", "remote-2"),+ newOrder = listOf("you", "remote-2", "remote-1"),+ localPlayerIds = setOf("you"),+ lastBuzzMs = emptyMap(),+ nowMs = 10_000L,+ )+ assertEquals(listOf("remote-1"), buzzed)+ }++ @Test+ fun noRumbleOnImprovementOrUnchanged() {+ // remote-2 climbs past the local seat; nobody remote worsens.+ assertEquals(+ emptyList(),+ RumbleDecider.decide(+ prevOrder = listOf("remote-1", "you", "remote-2"),+ newOrder = listOf("remote-1", "remote-2", "you"),+ localPlayerIds = setOf("you"),+ lastBuzzMs = emptyMap(),+ nowMs = 10_000L,+ ),+ )+ assertEquals(+ emptyList(),+ RumbleDecider.decide(+ prevOrder = listOf("you", "remote-1"),+ newOrder = listOf("you", "remote-1"),+ localPlayerIds = setOf("you"),+ lastBuzzMs = emptyMap(),+ nowMs = 10_000L,+ ),+ )+ }++ @Test+ fun cooldownSuppressesRepeatBuzz() {+ val prev = listOf("remote-1", "you")+ val new = listOf("you", "remote-1")+ val locals = setOf("you")+ val first = RumbleDecider.decide(prev, new, locals, emptyMap(), nowMs = 10_000L)+ assertEquals(listOf("remote-1"), first)+ assertEquals(+ emptyList(),+ RumbleDecider.decide(prev, new, locals, mapOf("remote-1" to 10_000L), nowMs = 10_500L),+ )+ assertEquals(+ listOf("remote-1"),+ RumbleDecider.decide(prev, new, locals, mapOf("remote-1" to 10_000L), nowMs = 11_500L),+ )+ }++ @Test+ fun localSeatsAndAiNeverBuzz() {+ // The touch seat, a plugged-in gamepad, and AI rivals all worsen — none buzz; only the+ // remote phone that dropped from 1st to 4th does.+ val buzzed = RumbleDecider.decide(+ prevOrder = listOf("remote-1", "you", "pad-1", "ai-0"),+ newOrder = listOf("you", "pad-1", "ai-0", "remote-1"),+ localPlayerIds = setOf("you", "pad-1"),+ lastBuzzMs = emptyMap(),+ nowMs = 10_000L,+ )+ assertEquals(listOf("remote-1"), buzzed)+ }++ @Test+ fun firstTickAndNewcomersStaySilent() {+ assertEquals(+ emptyList(),+ RumbleDecider.decide(+ prevOrder = emptyList(),+ newOrder = listOf("you", "remote-1"),+ localPlayerIds = setOf("you"),+ lastBuzzMs = emptyMap(),+ nowMs = 10_000L,+ ),+ )+ assertEquals(+ emptyList(),+ RumbleDecider.decide(+ prevOrder = listOf("you"),+ newOrder = listOf("you", "remote-1"),+ localPlayerIds = setOf("you"),+ lastBuzzMs = emptyMap(),+ nowMs = 10_000L,+ ),+ )+ }++ @Test+ fun lapIncrementRecordsDurationAndBest() {+ var state = LapTracker.State(lastIncrementMs = 1_000L)+ state = LapTracker.onLapTick(prevLap = 0, lap = 1, nowMs = 26_000L, state = state)+ assertEquals(25_000L, state.times.lastLapMs)+ assertEquals(25_000L, state.times.bestLapMs)+ state = LapTracker.onLapTick(prevLap = 1, lap = 2, nowMs = 49_000L, state = state)+ assertEquals(23_000L, state.times.lastLapMs)+ assertEquals(23_000L, state.times.bestLapMs)+ }++ @Test+ fun sameLapTickKeepsState() {+ val state = LapTracker.State(lastIncrementMs = 1_000L)+ assertEquals(state, LapTracker.onLapTick(prevLap = 1, lap = 1, nowMs = 26_000L, state = state))+ }++ @Test+ fun backmarkerPaceBoostsLeaderStaysBase() {+ val wobble = 0.95f+ val base = PlaceholderRace.AI_PACE * wobble+ assertEquals(base, PlaceholderRace.effectiveAiPace(wobble, 0f))+ assertTrue(PlaceholderRace.effectiveAiPace(wobble, 0.10f) > base)+ }++ @Test+ fun rubberBoostStepsAndShrinks() {+ assertEquals(+ PlaceholderRace.RUBBER_GAIN,+ PlaceholderRace.rubberBoost(PlaceholderRace.RUBBER_STEP),+ )+ assertEquals(0f, PlaceholderRace.rubberBoost(PlaceholderRace.RUBBER_STEP * 0.5f))+ assertTrue(PlaceholderRace.rubberBoost(0.20f) > PlaceholderRace.rubberBoost(0.05f))+ assertEquals(0f, PlaceholderRace.rubberBoost(-0.5f))+ }++ @Test+ fun aiPaceCapHolds() {+ assertTrue(PlaceholderRace.effectiveAiPace(1f, 10f) <= PlaceholderRace.AI_PACE_MAX)+ assertTrue(PlaceholderRace.effectiveAiPace(0.90f, 10f) <= PlaceholderRace.AI_PACE_MAX)+ } }