games: a second simultaneous drag no longer reverts the first block's move
- Commit
5a2b176e981fce8d3fe84933c30b1209f0887011- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 13:36 UTC (5 days ago)
- Parents
3162507
settleAfterDrag builds the result board from the level snapshot frozen when the finger went down, and onBlockMoved installed the whole snapshot as the current board โ so any move committed while a drag was in flight (a second finger's drag) was wiped by the finishing drag's stale board: A dragged right and released came back at its start cell when B's drag committed, with a phantom history entry that Undo then 'restored'. onBlockMoved now reconciles the report against the current board: only the named block takes its reported position, all others keep their committed positions; if another committed move has taken the target cell meanwhile, the stale report is refused and the board is untouched. Tests: a real two-finger Robolectric drag (both moves kept, undo walks through both) and a refused stale report. All 850 bundled levels and the daily generator were independently verified solvable with matching par. Verified: :games:unblockjam:testDevUnitTest 100 tests and lint pass.
Diff
games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.kt
diff --git a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.kt b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.ktindex 807b6cc6ce..2e335331c9 100644--- a/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.kt+++ b/games/unblockjam/src/main/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModel.kt@@ -222,8 +222,14 @@ class UnblockJamViewModel(application: Application) : AndroidViewModel(applicati override fun onBlockMoved(newLevelData: LevelData) { val s = _uiState.value val current = s.currentLevelData ?: return+ // A drag builds its result board when the finger goes down, so the board it reports can+ // predate another move committed while it was in flight (a second finger's drag, a+ // step). Installing it wholesale would silently revert that move: rebuild the reported+ // move on the board as it stands instead. A stale result whose cell another committed+ // move has since taken is refused, leaving the block where it is.+ val incoming = reconcile(newLevelData, current) ?: return // Block moved back to its previous position โ collapse with last history entry.- if (s.history.isNotEmpty() && s.history.last().blocks == newLevelData.blocks) {+ if (s.history.isNotEmpty() && s.history.last().blocks == incoming.blocks) { _uiState.update { it.copy( currentLevelData = it.history.last(),@@ -235,10 +241,10 @@ class UnblockJamViewModel(application: Application) : AndroidViewModel(applicati } if (s.isLevelWon) return - if (newLevelData.lastMovedBlockIndex != current.lastMovedBlockIndex) {+ if (incoming.lastMovedBlockIndex != current.lastMovedBlockIndex) { _uiState.update { it.copy(- currentLevelData = newLevelData,+ currentLevelData = incoming, history = it.history + current, ) }@@ -249,11 +255,32 @@ class UnblockJamViewModel(application: Application) : AndroidViewModel(applicati ) } } else {- _uiState.update { it.copy(currentLevelData = newLevelData) }+ _uiState.update { it.copy(currentLevelData = incoming) } } saveProgress() } + /**+ * [reported] as a move on [current]: only the block it says moved changes, taken from+ * [reported]'s position for it, so a move committed in the meantime (its block sits wherever+ * that move left it) survives the report. Null when that block's reported cell has been+ * taken by a block moved in the meantime โ the dragged block stays where it is. A report+ * that does not name a moved block of this board is installed as reported.+ */+ private fun reconcile(reported: LevelData, current: LevelData): LevelData? {+ val index = reported.lastMovedBlockIndex ?: return reported+ if (reported.blocks.size != current.blocks.size) return reported+ val reportedBlock = reported.blocks.getOrNull(index) ?: return reported+ val currentBlock = current.blocks[index]+ if (reportedBlock.position == currentBlock.position) {+ return current.copy(lastMovedBlockIndex = index)+ }+ val merged = current.blocks.toMutableList()+ merged[index] = currentBlock.copy(position = reportedBlock.position)+ val legal = isMoveValid(merged[index], merged - merged[index], current.dimension)+ return if (legal) current.copy(blocks = merged, lastMovedBlockIndex = index) else null+ }+ override fun onLevelWon() { val s = _uiState.value if (s.isLevelWon || s.packIndex == NO_PACK_INDEX) return
games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/BoardDragOverlapTest.kt
diff --git a/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/BoardDragOverlapTest.kt b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/BoardDragOverlapTest.ktnew file mode 100644index 0000000000..20a5fb99cb--- /dev/null+++ b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/BoardDragOverlapTest.kt@@ -0,0 +1,87 @@+package com.vayunmathur.games.unblockjam++import android.app.Application+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.collectAsState+import androidx.compose.runtime.getValue+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.test.junit4.createComposeRule+import androidx.compose.ui.test.onNodeWithTag+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.unit.dp+import androidx.compose.ui.unit.height+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.unblockjam.data.Coord+import com.vayunmathur.games.unblockjam.data.LevelPack+import com.vayunmathur.games.unblockjam.platform.UnblockJamViewModel+import com.vayunmathur.games.unblockjam.ui.components.GameBoard+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.Rule+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals++/**+ * Two fingers dragging two blocks at once: the board each drag reports is the one from when+ * its finger went down, so the drag that ends second must not put back the block the first+ * drag already moved. The board is fed by the ViewModel exactly as the game screen feeds it.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class BoardDragOverlapTest {+ @get:Rule val rule = createComposeRule()+ private val app get() = ApplicationProvider.getApplicationContext<Application>()++ @BeforeTest+ fun setUp() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ if (LevelPack.PACKS.isEmpty()) LevelPack.init(app)+ }++ @AfterTest fun tearDown() { Dispatchers.resetMain() }++ @Test+ fun twoFingerDragKeepsBothMoves() {+ val vm = UnblockJamViewModel(app)+ // Original Pack level 16 (index 15): block 4 is 3x1 at (2,4) and can slide right;+ // block 2 is 1x3 at (3,1) and can slide up.+ vm.loadLevel(0, 15)+ rule.setContent {+ val state by vm.uiState.collectAsState()+ Box(Modifier.size(360.dp)) {+ GameBoard(+ levelData = state.currentLevelData!!,+ onLevelChanged = vm::onBlockMoved,+ onLevelWon = vm::onLevelWon,+ isLevelWon = state.isLevelWon,+ modifier = Modifier.testTag("board"),+ )+ }+ }+ rule.onNodeWithTag("board").performTouchInput {+ // Finger 0 on block 4's centre (3.5, 4.5) cells; finger 1 on block 2's (3.5, 2.5).+ down(0, Offset(height * 3.5f / 6f, height * 4.5f / 6f))+ down(1, Offset(height * 3.5f / 6f, height * 2.5f / 6f))+ moveBy(0, Offset(height * 1f / 6f, 0f))+ moveBy(1, Offset(0f, -height * 1f / 6f))+ moveBy(0, Offset(height * 0.2f / 6f, 0f))+ moveBy(1, Offset(0f, -height * 0.2f / 6f))+ up(0)+ up(1)+ }+ rule.waitForIdle()+ val blocks = vm.uiState.value.currentLevelData!!.blocks+ assertEquals(Coord(3, 4), blocks[4].position, "block 4 dragged right one cell")+ assertEquals(Coord(3, 0), blocks[2].position, "block 2 dragged up one cell")+ assertEquals(2, vm.getCurrentMoves())+ }+}
games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModelOverlapTest.kt
diff --git a/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModelOverlapTest.kt b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModelOverlapTest.ktnew file mode 100644index 0000000000..914a6d4505--- /dev/null+++ b/games/unblockjam/src/test/java/com/vayunmathur/games/unblockjam/platform/UnblockJamViewModelOverlapTest.kt@@ -0,0 +1,134 @@+package com.vayunmathur.games.unblockjam.platform++import android.app.Application+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.games.unblockjam.data.Block+import com.vayunmathur.games.unblockjam.data.LevelData+import com.vayunmathur.games.unblockjam.data.LevelPack+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.test.resetMain+import kotlinx.coroutines.test.setMain+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNotNull+import kotlin.test.assertTrue++/**+ * Two games can be in flight at once on the board: a second finger's drag (or a step) commits+ * while an earlier drag is still being dragged, and that earlier drag then reports a board it+ * built when it started. The reports must be rebuilt on the board as it stands: the older+ * report used to replace the whole board and silently take the intervening move back out.+ */+@OptIn(ExperimentalCoroutinesApi::class)+@RunWith(RobolectricTestRunner::class)+class UnblockJamViewModelOverlapTest {+ private val app get() = ApplicationProvider.getApplicationContext<Application>()++ @BeforeTest+ fun setUp() {+ Dispatchers.setMain(Dispatchers.Unconfined)+ if (LevelPack.PACKS.isEmpty()) LevelPack.init(app)+ }++ @AfterTest fun tearDown() { Dispatchers.resetMain() }++ private fun overlaps(a: Block, b: Block): Boolean =+ a.position.x < b.position.x + b.dimension.width &&+ a.position.x + a.dimension.width > b.position.x &&+ a.position.y < b.position.y + b.dimension.height &&+ a.position.y + a.dimension.height > b.position.y++ private fun step(+ level: LevelData,+ index: Int,+ dx: Int,+ dy: Int,+ ): StepResult.Moved? = stepBlock(level, index, dx, dy) as? StepResult.Moved++ private val directions = listOf(1 to 0, -1 to 0, 0 to 1, 0 to -1)++ /** One legal one-cell step of block [index] of [level], if it has one. */+ private fun legalStep(level: LevelData, index: Int): StepResult.Moved? =+ directions.firstNotNullOfOrNull { (dx, dy) -> step(level, index, dx, dy) }++ @Test+ fun overlappingReportsKeepBothMoves() {+ val vm = UnblockJamViewModel(app)+ vm.loadLevel(0, 15)+ val start = assertNotNull(vm.uiState.value.currentLevelData)++ val byIndex = start.blocks.indices.mapNotNull { i -> legalStep(start, i)?.let { i to it } }+ assertTrue(byIndex.size >= 2, "level 15 should open with two movable blocks: $byIndex")+ val (firstIndex, first) = byIndex[0]+ val second = byIndex.drop(1).firstNotNullOfOrNull { (j, stepped) ->+ // The intervening move as the second drag reports it: built on the start board,+ // and still legal once the first move is on the board.+ val reported = stepped.level.blocks[j]+ val clashes = first.level.blocks.indices.any { k ->+ k != j && reported.position != first.level.blocks[j].position &&+ overlaps(reported, first.level.blocks[k])+ }+ if (clashes) null else stepped+ }+ assertNotNull(second, "need a second move that still fits after the first")++ vm.onBlockMoved(first.level)+ vm.onBlockMoved(second.level)++ val secondIndex = second.level.lastMovedBlockIndex!!+ val expected = first.level.blocks.toMutableList().also {+ it[secondIndex] = it[secondIndex].copy(position = second.level.blocks[secondIndex].position)+ }+ assertEquals(expected, vm.uiState.value.currentLevelData!!.blocks)+ assertEquals(2, vm.uiState.value.history.size)+ assertEquals(2, vm.getCurrentMoves())++ vm.onUndo()+ assertEquals(first.level.blocks, vm.uiState.value.currentLevelData!!.blocks)+ vm.onUndo()+ assertEquals(start.blocks, vm.uiState.value.currentLevelData!!.blocks)+ }++ @Test+ fun staleReportIntoACellTakenInTheMeantimeIsRefused() {+ // Find a shipped level where two blocks can each step from the start, but the second+ // step's destination is a cell the first step has meanwhile moved into.+ var found: Triple<Int, StepResult.Moved, StepResult.Moved>? = null+ for ((levelIndex, level) in LevelPack.PACKS[0].levels.withIndex()) {+ for (i in level.blocks.indices) {+ for (j in level.blocks.indices) {+ if (i == j) continue+ val firstStep = legalStep(level, i) ?: continue+ val secondStep = legalStep(level, j) ?: continue+ val reported = secondStep.level.blocks[j]+ val taken = reported.position != firstStep.level.blocks[j].position &&+ firstStep.level.blocks.indices.any { k ->+ k != j && overlaps(reported, firstStep.level.blocks[k])+ }+ if (taken) {+ found = Triple(levelIndex, firstStep, secondStep)+ break+ }+ }+ if (found != null) break+ }+ if (found != null) break+ }+ val (levelIndex, first, second) = assertNotNull(found, "no shipped level stages the clash")++ val vm = UnblockJamViewModel(app)+ vm.loadLevel(0, levelIndex)+ vm.onBlockMoved(first.level)+ val before = vm.uiState.value+ assertEquals(1, vm.getCurrentMoves())++ vm.onBlockMoved(second.level)+ assertEquals(before, vm.uiState.value, "the stale move must not disturb the board")+ assertEquals(1, vm.getCurrentMoves())+ }+}