kart: on-screen touch controls for phone racing
- Commit
daaf93d3ed0812fb37a0721aebe508168fe67161- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-05 13:44 UTC (20 hours ago)
- Parents
d40827d
Kart could only be driven by a phone-as-controller or a gamepad: the local seat had no input source of its own, so a solo race against the bots could be started and finished but not driven. - New domain/TouchControls: TouchDriveState (held steering, gas, brake, drift, item) with a pure conversion to KartControl and an encoding onto the same ControllerInput slots (left-stick X, throttle/brake axes, right shoulder, A) that GameInputLoop already normalizes for network phones and gamepads. - KartGameScreen racing body gains hold-to-drive touch buttons (Left/Right on the left, Brake/Drift/Item/Gas on the right), reporting the whole held state on every press/release through a new KartGameActions.onTouchDrive. - KartViewModel records local samples (touch, stick shim, gamepad) in its own localInputs flow and merges them over the host fan-in in both race loops, so local driving never depends on the LAN host being up; samples still mirror into the host for lobby and rumble. The loops and the race-start snapshot now read the host flows directly (KartHost.latestLobby/latestInputs) instead of the hop-lagged mirrors, and the lobby host starts in parallel with identity load instead of after it. Tests first: TouchControlsTest covers the neutral/direction/brake semantics and the encode-normalize round trip plus a placeholder race that moves under touch gas; KartViewModelTest gains a race driven end-to-end by onTouchDrive; KartGameScreenTest asserts the six touch controls render while racing.
Diff
games/kart/src/main/java/com/vayunmathur/games/kart/domain/TouchControls.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/domain/TouchControls.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/TouchControls.ktnew file mode 100644index 0000000000..6a7d0dc246--- /dev/null+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/domain/TouchControls.kt@@ -0,0 +1,62 @@+package com.vayunmathur.games.kart.domain++import com.vayunmathur.sdk.controller.AXIS_BRAKE+import com.vayunmathur.sdk.controller.AXIS_COUNT+import com.vayunmathur.sdk.controller.AXIS_LEFT_X+import com.vayunmathur.sdk.controller.AXIS_THROTTLE+import com.vayunmathur.sdk.controller.ControllerButton+import com.vayunmathur.sdk.controller.ControllerInput++/**+ * Which on-screen touch controls are held right now.+ *+ * The phone's primary input: two steering thumbs on the left, pedals and the+ * drift/item buttons on the right. Each flag is a held button, not an event โ+ * the UI reports the whole state on every press and release, and the race+ * loop reads the latest sample, so a dropped report costs one tick and+ * repairs itself exactly like a network sample does.+ */+data class TouchDriveState(+ val steerLeft: Boolean = false,+ val steerRight: Boolean = false,+ val gas: Boolean = false,+ val brake: Boolean = false,+ val drift: Boolean = false,+ val item: Boolean = false,+) {+ /** Shared constants and helpers for TouchDriveState. */+ companion object {+ /** Nothing held: the kart coasts. */+ val RELEASED = TouchDriveState()+ }++ /** The kart control these held buttons mean, before the stick curve. */+ fun toKartControl(): KartControl = KartControl(+ throttle = if (gas) 1f else 0f,+ // Both thumbs down at once is a panic, not a direction.+ steering = (if (steerRight) 1f else 0f) + (if (steerLeft) -1f else 0f),+ brake = if (brake) 1f else 0f,+ drift = drift,+ itemUse = item,+ )++ /**+ * Encode as the [ControllerInput] every other input source (network+ * phones, gamepads) produces, so the race loop has exactly one input+ * shape to read. Steering rides the left-stick X axis, gas and brake the+ * trigger axes, drift the right shoulder and item the A button โ the+ * slots [GameInputLoop.normalize] already maps, so the round trip+ * through it reproduces [toKartControl].+ */+ fun toControllerInput(playerId: String, seq: Long = 0L): ControllerInput {+ val control = toKartControl()+ val axes = MutableList(AXIS_COUNT) { 0f }+ axes[AXIS_LEFT_X] = control.steering+ axes[AXIS_THROTTLE] = control.throttle+ axes[AXIS_BRAKE] = control.brake+ var buttons = 0L+ if (drift) buttons = buttons or ControllerButton.RIGHT_SHOULDER.bit+ if (item) buttons = buttons or ControllerButton.A.bit+ return ControllerInput(playerId = playerId, seq = seq, buttons = buttons, axes = axes)+ }+}
games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartHost.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartHost.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartHost.ktindex 5a9e8c3415..d3464a739e 100644--- a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartHost.kt+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartHost.kt@@ -67,6 +67,12 @@ class KartHost( val host: ControllerHost? get() = inner + /** Latest lobby, read from the host itself once it exists: the mirror above lags a hop. */+ fun latestLobby(): LobbyState = inner?.lobby?.value ?: _lobby.value++ /** Latest inputs, read from the host itself once it exists: the mirror above lags a hop. */+ fun latestInputs(): Map<String, ControllerInput> = inner?.inputs?.value ?: _inputs.value+ private val advertiser = ControllerAdvertiser(context) private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO) private var server: ServerSocket? = null
games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartUiContract.kt
diff --git a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartUiContract.kt b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartUiContract.ktindex e1b51c2516..d7d0d2fcc3 100644--- a/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartUiContract.kt+++ b/games/kart/src/main/java/com/vayunmathur/games/kart/platform/KartUiContract.kt@@ -2,6 +2,7 @@ package com.vayunmathur.games.kart.platform import com.vayunmathur.games.kart.data.KartCup import com.vayunmathur.games.kart.data.KartProgress+import com.vayunmathur.games.kart.domain.TouchDriveState /** * The UI contract between [KartViewModel] and the garage screen.@@ -20,6 +21,12 @@ interface KartGameActions { /** Back to the lobby from the results screen. */ fun backToLobby() {} + /**+ * The held on-screen touch controls changed. Reported on every press and+ * release while racing; the race loop reads the latest sample.+ */+ fun onTouchDrive(state: TouchDriveState) {}+ /** Shared constants and helpers for KartGameActions. */ companion object { val Noop: KartGameActions = object : KartGameActions {} } }
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 571471d9e5..dd05b6b847 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@@ -10,6 +10,7 @@ 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.domain.TouchDriveState import com.vayunmathur.games.kart.util.KartNative import com.vayunmathur.library.util.AchievementsManager import com.vayunmathur.sdk.controller.RumbleFeedback@@ -76,6 +77,16 @@ class KartViewModel(application: Application) : AndroidViewModel(application), private var tickJob: Job? = null private var race: PlaceholderRace? = null + /**+ * Latest input sample per seat driven from this device (touch, gamepad).+ *+ * Local input must not depend on the LAN host: a solo race against the+ * bots has to drive even when the host is still starting or could not+ * bind at all. The tick loops merge this over the host's fan-in; both+ * carry the same [ControllerInput] shape.+ */+ private val localInputs = MutableStateFlow<Map<String, com.vayunmathur.sdk.controller.ControllerInput>>(emptyMap())+ /** This device's seat, so the HUD knows which kart is ours. Null until the race starts. */ var localPlayerId: String? = null private set@@ -83,14 +94,18 @@ class KartViewModel(application: Application) : AndroidViewModel(application), init { achievementsManager.checkExistingAchievements() - // Load (or mint) the PQC identity off the main thread, then open the- // lobby. First run pays keygen; every later start reads persisted keys.+ // Load (or mint) the PQC identity off the main thread. First run pays+ // keygen; every later start reads persisted keys. The lobby opens in+ // parallel: the host only reads the identity when a phone handshakes,+ // and until it lands handshakes are refused cleanly. viewModelScope.launch { pqcIdentity = runCatching {+ // The prefix is a persisted key name, not a surface label: changing+ // it would mint a fresh identity and orphan every paired phone. com.vayunmathur.e2ee.PqcIdentity.loadOrCreate(pairingStore, prefix = "kartTv") }.getOrNull()- kartHost.start() }+ viewModelScope.launch { kartHost.start() } viewModelScope.launch { kartHost.lobby.collectLatest { lobby ->@@ -133,10 +148,10 @@ class KartViewModel(application: Application) : AndroidViewModel(application), // The garage button starts the lobby countdown; the tick loop banks the cup clear when // the race finishes. if (_racePhase.value !is RacePhase.Lobby) return- // Solo seat for the scaffold: this device drives kart one until phones join.+ // This device drives kart one; phones that joined the lobby take the rest. localPlayerId = localPlayerId ?: "local-${System.currentTimeMillis()}" val seat = requireNotNull(localPlayerId)- kartHost.host?.addLocalPlayer(seat, "You")+ ensureLocalSeat(seat) viewModelScope.launch { for (count in COUNTDOWN_SECONDS downTo 1) { _racePhase.value = RacePhase.Countdown(count)@@ -147,15 +162,59 @@ class KartViewModel(application: Application) : AndroidViewModel(application), } /**- * Feed one raw stick sample for the local seat. Called by the placeholder touch controls below;- * gamepads and network phones arrive through the host instead.+ * Seat this device with the host, waiting out host startup if a fast+ * Start tap beat it. The seat is what the lobby shows and what+ * [beginRace] snapshots; local inputs are recorded either way (see+ * [feedLocalInput]), so registering late beats never.+ */+ private fun ensureLocalSeat(seat: String) {+ if (kartHost.host != null) {+ kartHost.host?.addLocalPlayer(seat, "You")+ return+ }+ viewModelScope.launch {+ while (kartHost.host == null && _racePhase.value !is RacePhase.Results) {+ delay(HOST_WAIT_MS)+ }+ kartHost.host?.addLocalPlayer(seat, "You")+ }+ }++ /**+ * The held on-screen touch controls changed, for the local seat. This is+ * the phone's primary input; gamepads and network phones arrive through+ * the host instead.+ *+ * Encodes to the same [ControllerInput] shape every other source builds+ * and routes it through the same session, so the tick loop has exactly+ * one input path per seat to read.+ */+ override fun onTouchDrive(state: TouchDriveState) {+ if (_racePhase.value !is RacePhase.Racing) return+ val seat = localPlayerId ?: return+ feedLocalInput(state.toControllerInput(seat))+ }++ /**+ * Record one input sample from this device and mirror it into the host+ * fan-in when the host is up, so lobby seats and rumble keep working.+ * The race loop reads the merge, so a missing host never starves a+ * local seat.+ */+ private fun feedLocalInput(input: com.vayunmathur.sdk.controller.ControllerInput) {+ localInputs.value = localInputs.value + (input.playerId to input)+ kartHost.host?.onLocalInput(input)+ }++ /**+ * Feed one raw stick sample for the local seat. * * Builds the same [ControllerInput] shape every other source builds and routes it through the * same session, so the tick loop has exactly one input path per seat to read. */ fun onLocalStick(playerId: String, x: Float, y: Float) { if (_racePhase.value !is RacePhase.Racing) return- kartHost.host?.onLocalInput(+ feedLocalInput( com.vayunmathur.sdk.controller.ControllerInput( playerId = playerId, seq = 0L,@@ -173,11 +232,11 @@ class KartViewModel(application: Application) : AndroidViewModel(application), /** One gamepad sample, already shaped as a [ControllerInput] by [GamepadDirect]. */ fun onGamepadInput(input: com.vayunmathur.sdk.controller.ControllerInput) { if (_racePhase.value !is RacePhase.Racing) return- kartHost.host?.onLocalInput(input)+ feedLocalInput(input) } private fun beginRace(seat: String) {- val playerIds = kartHost.lobby.value.slots.map { it.playerId }+ val playerIds = kartHost.latestLobby().slots.map { it.playerId } val seats = if (playerIds.isEmpty()) listOf(seat) else playerIds if (KartNative.isAvailable) { beginNativeRace(seat, seats)@@ -203,7 +262,7 @@ class KartViewModel(application: Application) : AndroidViewModel(application), tickJob = viewModelScope.launch { while (isActive) { delay(TICK_MS)- val latest = kartHost.inputs.value+ val latest = kartHost.latestInputs() + localInputs.value for (id in seats) { val sample = latest[id] ?: continue val control = GameInputLoop.normalize(sample)@@ -266,7 +325,7 @@ class KartViewModel(application: Application) : AndroidViewModel(application), val nowMs = android.os.SystemClock.uptimeMillis() val dt = ((nowMs - lastMs).coerceAtMost(250L)) / 1_000f lastMs = nowMs- val latest = kartHost.inputs.value+ val latest = kartHost.latestInputs() + localInputs.value for (id in seats) { val sample = latest[id] ?: continue val control = GameInputLoop.normalize(sample)@@ -386,7 +445,7 @@ class KartViewModel(application: Application) : AndroidViewModel(application), /** 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()+ kartHost.latestLobby().slots.filter { !it.remote }.map { it.playerId }.toSet() /** * One native standings row. Parsed by hand (not kotlinx.serialization): the engine emits a@@ -427,7 +486,7 @@ class KartViewModel(application: Application) : AndroidViewModel(application), /** Back to the lobby from results. Seats stay; the next Start Race counts down again. */ override fun backToLobby() {- _racePhase.value = RacePhase.Lobby(kartHost.lobby.value)+ _racePhase.value = RacePhase.Lobby(kartHost.latestLobby()) } override fun onCleared() {@@ -454,5 +513,8 @@ class KartViewModel(application: Application) : AndroidViewModel(application), /** One countdown tick: a single second. */ private const val COUNTDOWN_STEP_MS = 1_000L++ /** Poll step while waiting for the controller host to come up. */+ private const val HOST_WAIT_MS = 50L } }
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 9a6e3995de..08ffd16786 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@@ -1,5 +1,7 @@ package com.vayunmathur.games.kart.ui +import androidx.compose.foundation.background+import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column@@ -9,15 +11,22 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.rememberScrollState+import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier+import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.res.pluralStringResource import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.viewinterop.AndroidView import com.vayunmathur.games.kart.R+import com.vayunmathur.games.kart.domain.TouchDriveState import com.vayunmathur.games.kart.platform.KartGameActions import com.vayunmathur.games.kart.platform.KartUiState import com.vayunmathur.games.kart.platform.RacePhase@@ -63,7 +72,7 @@ fun KartGameScreen( when (val p = phase) { is RacePhase.Lobby -> LobbyBody(state, p, actions) is RacePhase.Countdown -> CountdownBody(p)- is RacePhase.Racing -> RacingBody(p)+ is RacePhase.Racing -> RacingBody(p, actions) is RacePhase.Results -> ResultsBody(p, actions) } }@@ -141,7 +150,7 @@ private fun CountdownBody(phase: RacePhase.Countdown) { } @Composable-private fun ColumnScope.RacingBody(phase: RacePhase.Racing) {+private fun ColumnScope.RacingBody(phase: RacePhase.Racing, actions: KartGameActions) { // The native 3D viewport sits behind the standings HUD. With no // libkart_engine it is never composed and the HUD is the whole screen; // in a @Preview (Layoutlib) a SurfaceView is a blank rect, so listing@@ -200,6 +209,78 @@ private fun ColumnScope.RacingBody(phase: RacePhase.Racing) { ) } }+ TouchControls(actions)+}++/**+ * The on-screen driving controls: steering thumbs on the left, pedals and+ * drift/item on the right. In-screen state only โ each press or release+ * reports the whole held state, and the race loop reads the latest sample.+ */+@Composable+private fun TouchControls(actions: KartGameActions) {+ var held by remember { mutableStateOf(TouchDriveState.RELEASED) }+ fun report(next: TouchDriveState) {+ held = next+ actions.onTouchDrive(next)+ }+ Row(+ Modifier.fillMaxWidth(),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Row(horizontalArrangement = Arrangement.spacedBy(Spacing.sm)) {+ TouchButton(stringResource(R.string.touch_left), held.steerLeft) {+ report(held.copy(steerLeft = it))+ }+ TouchButton(stringResource(R.string.touch_right), held.steerRight) {+ report(held.copy(steerRight = it))+ }+ }+ Row(horizontalArrangement = Arrangement.spacedBy(Spacing.sm)) {+ TouchButton(stringResource(R.string.touch_brake), held.brake) {+ report(held.copy(brake = it))+ }+ TouchButton(stringResource(R.string.touch_drift), held.drift) {+ report(held.copy(drift = it))+ }+ TouchButton(stringResource(R.string.touch_item), held.item) {+ report(held.copy(item = it))+ }+ TouchButton(stringResource(R.string.touch_gas), held.gas) {+ report(held.copy(gas = it))+ }+ }+ }+}++/** One hold-to-drive button: held from press until release, never a click. */+@Composable+private fun TouchButton(label: String, held: Boolean, onHold: (Boolean) -> Unit) {+ Box(+ Modifier+ .background(+ if (held) MaterialTheme.colorScheme.primary+ else MaterialTheme.colorScheme.surfaceVariant,+ RoundedCornerShape(Spacing.sm),+ )+ .pointerInput(label) {+ detectTapGestures(onPress = {+ onHold(true)+ tryAwaitRelease()+ onHold(false)+ })+ }+ .padding(horizontal = Spacing.md, vertical = Spacing.md),+ contentAlignment = Alignment.Center,+ ) {+ Text(+ label,+ style = MaterialTheme.typography.labelLarge,+ color = if (held) MaterialTheme.colorScheme.onPrimary+ else MaterialTheme.colorScheme.onSurfaceVariant,+ )+ } } /** Format a lap time as m:ss.mmm, e.g. 0:24.318. Null-safe at the call site: only called non-null. */
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 fc586c48da..fccc67cfeb 100644--- a/games/kart/src/main/res/values/strings.xml+++ b/games/kart/src/main/res/values/strings.xml@@ -36,6 +36,18 @@ <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: Touch steering, hold to steer left. Label -->+ <string name="touch_left">Left</string>+ <!-- KartGameScreen: Touch steering, hold to steer right. Label -->+ <string name="touch_right">Right</string>+ <!-- KartGameScreen: Touch pedal, hold to brake. Label -->+ <string name="touch_brake">Brake</string>+ <!-- KartGameScreen: Touch button, hold to drift. Label -->+ <string name="touch_drift">Drift</string>+ <!-- KartGameScreen: Touch button, tap to use the held item. Label -->+ <string name="touch_item">Item</string>+ <!-- KartGameScreen: Touch pedal, hold to accelerate. Label -->+ <string name="touch_gas">Gas</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/test/java/com/vayunmathur/games/kart/domain/TouchControlsTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/domain/TouchControlsTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/domain/TouchControlsTest.ktnew file mode 100644index 0000000000..941037129e--- /dev/null+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/domain/TouchControlsTest.kt@@ -0,0 +1,61 @@+package com.vayunmathur.games.kart.domain++import com.vayunmathur.sdk.controller.ControllerButton+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++class TouchControlsTest {++ @Test fun releasedIsNeutral() {+ assertEquals(KartControl.NEUTRAL, TouchDriveState.RELEASED.toKartControl())+ }++ @Test fun gasIsFullThrottle() {+ val control = TouchDriveState(gas = true).toKartControl()+ assertEquals(1f, control.throttle)+ assertEquals(0f, control.brake)+ }++ @Test fun steeringDirectionsAndCancel() {+ assertEquals(-1f, TouchDriveState(steerLeft = true).toKartControl().steering)+ assertEquals(1f, TouchDriveState(steerRight = true).toKartControl().steering)+ // Both thumbs down at once is a panic, not a direction.+ assertEquals(0f, TouchDriveState(steerLeft = true, steerRight = true).toKartControl().steering)+ }++ @Test fun encodesOntoControllerInputTheRaceLoopReads() {+ // The race loop only ever sees ControllerInput, so the touch state must+ // survive the encode -> GameInputLoop.normalize round trip unchanged.+ val state = TouchDriveState(steerLeft = true, gas = true, drift = true, item = true)+ val input = state.toControllerInput("p1", seq = 7L)+ assertEquals("p1", input.playerId)+ assertEquals(7L, input.seq)+ assertTrue(input.isPressed(ControllerButton.A))+ assertTrue(input.isPressed(ControllerButton.RIGHT_SHOULDER))+ val control = GameInputLoop.normalize(input)+ assertEquals(1f, control.throttle)+ assertEquals(-1f, control.steering)+ assertEquals(0f, control.brake)+ assertTrue(control.drift)+ assertTrue(control.itemUse)+ }++ @Test fun brakeEncodesOnTheBrakeAxis() {+ val control = GameInputLoop.normalize(+ TouchDriveState(brake = true).toControllerInput("p1"),+ )+ assertEquals(1f, control.brake)+ assertEquals(0f, control.throttle)+ }++ @Test fun touchKartActuallyMovesInPlaceholderRace() {+ // End-to-end at the domain layer: held gas through the encode the+ // ViewModel uses, fed the way the tick loop feeds it, moves the kart.+ val race = PlaceholderRace(playerIds = listOf("p1"), aiCount = 0)+ val input = TouchDriveState(gas = true).toControllerInput("p1")+ race.setControl("p1", GameInputLoop.normalize(input))+ race.tick(1f)+ assertTrue(race.lapProgress("p1") > 0f)+ }+}
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 81a672b78f..a99cf8c7cb 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@@ -134,6 +134,31 @@ class KartViewModelTest { } } + @Test fun touchDriveMovesLocalKartInPlaceholderRace() {+ val wasAvailable = KartNative.isAvailable+ KartNative.isAvailable = false+ try {+ val vm = KartViewModel(app)+ await("cup loads") { vm.uiState.value.cup != null }+ // Touch input before a race is dropped quietly.+ vm.onTouchDrive(com.vayunmathur.games.kart.domain.TouchDriveState(gas = true))+ vm.startRace()+ pump(4_000)+ await("placeholder racing") { vm.racePhase.value is RacePhase.Racing }+ val seat = requireNotNull(vm.localPlayerId)+ vm.onTouchDrive(com.vayunmathur.games.kart.domain.TouchDriveState(gas = true))+ pump(5_000)+ val racing = vm.racePhase.value+ assertTrue(racing is RacePhase.Racing, "phase=$racing")+ val progress = (racing as RacePhase.Racing).lapProgress[seat] ?: 0f+ assertTrue(progress > 0f, "local kart did not move under touch gas: $racing")+ // Releasing everything coasts: no crash, race still running or done.+ vm.onTouchDrive(com.vayunmathur.games.kart.domain.TouchDriveState.RELEASED)+ } finally {+ KartNative.isAvailable = wasAvailable+ }+ }+ @Test fun secondViewModelSeesPersistedCupState() { val vm = KartViewModel(app) await("cup loads") { vm.uiState.value.cup != null }
games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartGameScreenTest.kt
diff --git a/games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartGameScreenTest.kt b/games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartGameScreenTest.ktindex 98de4ef567..05ccedc679 100644--- a/games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartGameScreenTest.kt+++ b/games/kart/src/test/java/com/vayunmathur/games/kart/ui/KartGameScreenTest.kt@@ -30,8 +30,10 @@ class KartGameScreenTest { private class RecordingActions : KartGameActions { var starts = 0 var backs = 0+ var touch: com.vayunmathur.games.kart.domain.TouchDriveState? = null override fun startRace() { starts++ } override fun backToLobby() { backs++ }+ override fun onTouchDrive(state: com.vayunmathur.games.kart.domain.TouchDriveState) { touch = state } } @Test fun lobbyLoadingWhenCupMissing() {@@ -129,8 +131,25 @@ class KartGameScreenTest { assertEquals(0, actions.starts) } + @Test fun racingShowsTouchControls() {+ val phase = RacePhase.Racing(+ order = listOf("p1"),+ lapProgress = emptyMap(),+ playerLap = 0,+ totalLaps = 3,+ )+ rule.setContent { KartGameScreen(KartUiState(cup = CUPS[0]), phase, KartGameActions.Noop) }+ rule.onNodeWithText(str(R.string.touch_left)).assertIsDisplayed()+ rule.onNodeWithText(str(R.string.touch_right)).assertIsDisplayed()+ rule.onNodeWithText(str(R.string.touch_gas)).assertIsDisplayed()+ rule.onNodeWithText(str(R.string.touch_brake)).assertIsDisplayed()+ rule.onNodeWithText(str(R.string.touch_drift)).assertIsDisplayed()+ rule.onNodeWithText(str(R.string.touch_item)).assertIsDisplayed()+ }+ @Test fun noopActionsAreHarmless() { KartGameActions.Noop.startRace() KartGameActions.Noop.backToLobby()+ KartGameActions.Noop.onTouchDrive(com.vayunmathur.games.kart.domain.TouchDriveState(gas = true)) } }