Modern Apps git

← Modern-Apps.git

games-arrows: animate arrows as a snake, head leading

Commit
f1ae2398094b6ed7cf32a21ef291f39bc089a8e6
Author
Vayun Mathur <[email protected]>
When
2026-11-07 20:20 UTC (29 days ago)
Parents
7135e83
A travelling arrow used one advance for every segment, so the
whole shape translated rigidly along its route.

The board still drives a single Animatable, but each segment now
converts the global advance with laggedAdvance(): the head tracks
it exactly and every trailing segment is held back by another
SEGMENT_LAG_CELLS (0.22 cells), easing the arrow out like a snake
instead of sliding it as one block. The animation target runs
past each segment's destination by the accumulated lag
(globalAdvanceTarget), so the tail still lands exactly where the
move ends, and durations are sized from that same global
distance. Retreats run the same function backwards, so the head
also leads the way back.

The lag lives in pure functions next to the drawing code and is
pinned by ArrowsMotionTest: head starts first, segments start in
head-to-tail order, everything is bounded by the destination,
and all segments land on it at the global target. The per-leg
specs now come from library.ui Motion (open/close/over) instead
of raw tween/easing call sites; the Animatable sequencing itself
stays under the file's existing raw-animation exception.

Diff

games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoard.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoard.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoard.ktindex d9466580bb..aca147330d 100644--- a/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoard.kt+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoard.kt@@ -4,10 +4,6 @@ package com.vayunmathur.games.arrows.ui.components  import androidx.compose.animation.core.Animatable-import androidx.compose.animation.core.FastOutSlowInEasing-import androidx.compose.animation.core.LinearEasing-import androidx.compose.animation.core.LinearOutSlowInEasing-import androidx.compose.animation.core.tween import androidx.compose.foundation.clickable import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.interaction.MutableInteractionSource@@ -43,6 +39,7 @@ import com.vayunmathur.games.arrows.data.Mirror import com.vayunmathur.games.arrows.domain.ArrowsRules import com.vayunmathur.games.arrows.platform.ArrowMove import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Motion import kotlinx.coroutines.delay  /**@@ -80,21 +77,27 @@ fun ArrowsBoard(      LaunchedEffect(move) {         if (move == null) return@LaunchedEffect+        // Segments do not share this advance: each converts it with laggedAdvance(), so the head+        // sets off first and the tail follows. The global value therefore has to run past each+        // segment's own destination by one lag per trailing segment (globalAdvanceTarget()).+        val segmentCount = game.remaining.firstOrNull { it.id == move.pieceId }?.cells?.size ?: 1         if (move.clears) {             // One past the end of the route, so the tail clears the edge too rather than winking             // out on it. The route already ends with the head's escape path, so its size alone is             // the distance that takes the tail out; adding `move.advance` counted that path twice             // and kept the (by then invisible) arrow animating - and taps locked - for up to a             // whole extra board crossing after it had left.-            val target = move.route.size.toFloat()-            advance.animateTo(target, tween(cellMillis(move.route.size), easing = LinearEasing))+            val maxAdvance = move.route.size.toFloat()+            val target = globalAdvanceTarget(maxAdvance, segmentCount)+            advance.animateTo(target, Motion.over(cellMillis(target)))         } else {             // Wedged arrows still get a nudge, or a tap on one reads as the game ignoring the input.-            val target = if (move.advance == 0) NUDGE_CELLS else move.advance.toFloat()-            advance.animateTo(target, tween(cellMillis(move.advance), easing = LinearOutSlowInEasing))+            val maxAdvance = if (move.advance == 0) NUDGE_CELLS else move.advance.toFloat()+            val target = globalAdvanceTarget(maxAdvance, segmentCount)+            advance.animateTo(target, Motion.open(cellMillis(target)))             showBlocked = true             delay(BLOCKED_HOLD_MILLIS)-            advance.animateTo(0f, tween(cellMillis(move.advance), easing = FastOutSlowInEasing))+            advance.animateTo(0f, Motion.close(cellMillis(target)))         }         onMoveFinished()     }@@ -142,7 +145,14 @@ fun ArrowsBoard(                             else -> arrowColor                         }                         if (moving && move != null) {-                            drawTravellingArrow(piece, move, advance.value, cols, cellPx, color)+                            val maxAdvance = if (move.clears) {+                                move.route.size.toFloat()+                            } else if (move.advance == 0) {+                                NUDGE_CELLS+                            } else {+                                move.advance.toFloat()+                            }+                            drawTravellingArrow(piece, move, advance.value, maxAdvance, cols, cellPx, color)                         } else {                             drawArrow(piece, cols, cellPx, color)                         }@@ -202,8 +212,8 @@ private const val MILLIS_PER_CELL = 45 /** Floor on the animation, so a one-cell move is still long enough to register. */ private const val MIN_MOVE_MILLIS = 120 -private fun cellMillis(cells: Int): Int =-    (cells * MILLIS_PER_CELL).coerceAtLeast(MIN_MOVE_MILLIS)+private fun cellMillis(cells: Float): Int =+    (cells * MILLIS_PER_CELL).toInt().coerceAtLeast(MIN_MOVE_MILLIS)  /** How far a wedged arrow lurches before coming back, in cells. */ private const val NUDGE_CELLS = 0.3f
games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoardDrawing.kt
diff --git a/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoardDrawing.kt b/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoardDrawing.ktindex 5cae3ca8d6..9b333f716a 100644--- a/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoardDrawing.kt+++ b/games/arrows/src/main/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoardDrawing.kt@@ -54,6 +54,47 @@ internal fun DrawScope.drawMirror(cell: Int, mirror: Mirror, cols: Int, size: Fl     drawLine(color, start, end, strokeWidth = size * 0.09f, cap = StrokeCap.Round) } +/**+ * How far each trailing segment waits for the one ahead of it, in cells of travel.+ *+ * This is the whole of the snake feel: the head sets off immediately and every segment behind it+ * starts [SEGMENT_LAG_CELLS] of travel later, so the arrow eases out instead of translating as+ * one rigid shape. A fifth of a cell per segment is enough to read as a follow-through on a+ * five-cell arrow without the tail feeling disconnected on a two-cell one.+ */+internal const val SEGMENT_LAG_CELLS = 0.22f++/**+ * Segment [segmentIndex]'s own advance when the move's global advance is [globalAdvance].+ *+ * Pure arithmetic on purpose, so the timing can be pinned by plain unit tests: the head+ * (the last segment) tracks the global advance exactly, each segment behind it is held back+ * by one more [lagPerSegment], and no segment ever passes [maxAdvance] or goes negative.+ * Animating the global value from 0 to [globalAdvanceTarget] therefore starts the head first+ * and still lands every segment exactly on [maxAdvance].+ */+internal fun laggedAdvance(+    globalAdvance: Float,+    segmentIndex: Int,+    segmentCount: Int,+    maxAdvance: Float,+    lagPerSegment: Float = SEGMENT_LAG_CELLS,+): Float {+    val behindHead = (segmentCount - 1 - segmentIndex).coerceAtLeast(0)+    return (globalAdvance - behindHead * lagPerSegment).coerceIn(0f, maxAdvance)+}++/**+ * The global advance at which even the tail has completed [maxAdvance] of travel: the far end+ * has to run one lag per segment past it. Durations should be sized from this value so the+ * arrow's speed per cell is the same whatever its length.+ */+internal fun globalAdvanceTarget(+    maxAdvance: Float,+    segmentCount: Int,+    lagPerSegment: Float = SEGMENT_LAG_CELLS,+): Float = maxAdvance + (segmentCount - 1).coerceAtLeast(0) * lagPerSegment+ /**  * One arrow part-way along its route.  *@@ -61,6 +102,10 @@ internal fun DrawScope.drawMirror(cell: Int, mirror: Mirror, cols: Int, size: Fl  * and turns corners with it. Fractional advance interpolates between the two positions either side, which  * is what makes the motion continuous rather than a hop per cell.  *+ * [advance] is the move's *global* advance (see [laggedAdvance]): each segment converts it to+ * its own, so the head leads and the tail follows a beat later rather than the whole shape+ * translating rigidly. [maxAdvance] is how far each segment ultimately travels.+ *  * Once the route runs out the piece is leaving the board, so positions past the end are extrapolated from  * the final step's direction — it slides off the edge instead of stopping dead on it.  */@@ -68,15 +113,19 @@ internal fun DrawScope.drawTravellingArrow(     piece: ArrowPiece,     move: ArrowMove,     advance: Float,+    maxAdvance: Float,     cols: Int,     cell: Float,     color: Color, ) {-    val centres = piece.cells.indices.map { routePoint(move.route, it + advance, cols, cell) }+    val segmentAdvance = { index: Int ->+        laggedAdvance(advance, index, piece.cells.size, maxAdvance)+    }+    val centres = piece.cells.indices.map { routePoint(move.route, it + segmentAdvance(it), cols, cell) }     // Sampled half a cell further along the route rather than taken from the last two body cells: a     // one-cell arrow has no "last two", and sampling also keeps the head turning smoothly through a     // mirror instead of snapping once the body reaches it.-    val headAt = piece.cells.lastIndex + advance+    val headAt = piece.cells.lastIndex + segmentAdvance(piece.cells.lastIndex)     val ahead = routePoint(move.route, headAt + 0.5f, cols, cell)     val head = centres.last()     val sampled = Offset(ahead.x - head.x, ahead.y - head.y)
games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoardDrawingTest.kt
diff --git a/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoardDrawingTest.kt b/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoardDrawingTest.ktindex 33ad1877e7..fd5bcd7482 100644--- a/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoardDrawingTest.kt+++ b/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/components/ArrowsBoardDrawingTest.kt@@ -89,7 +89,7 @@ class ArrowsBoardDrawingTest {         for (advance in listOf(0f, 0.5f, 1.5f, 3f)) {             val bitmap = drawOnBitmap {                 val cell = size.width / 5-                drawTravellingArrow(piece, ArrowMove(piece.id, route, 3, true), advance, 5, cell, Color.Black)+                drawTravellingArrow(piece, ArrowMove(piece.id, route, 3, true), advance, route.size.toFloat(), 5, cell, Color.Black)             }             assertTrue(nonTransparentPixels(bitmap) > 5, "travelling arrow at $advance should paint")         }@@ -102,7 +102,7 @@ class ArrowsBoardDrawingTest {         val bitmap = drawOnBitmap {             val cell = size.width / 5             // Route is only the piece's own cells, so the sampled heading collapses at the head-            drawTravellingArrow(piece, ArrowMove(piece.id, piece.cells, 0, false), 0f, 5, cell, Color.Black)+            drawTravellingArrow(piece, ArrowMove(piece.id, piece.cells, 0, false), 0f, 0f, 5, cell, Color.Black)         }         assertTrue(nonTransparentPixels(bitmap) > 5)     }
games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/components/ArrowsMotionTest.kt
diff --git a/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/components/ArrowsMotionTest.kt b/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/components/ArrowsMotionTest.ktnew file mode 100644index 0000000000..a6c63018fc--- /dev/null+++ b/games/arrows/src/test/java/com/vayunmathur/games/arrows/ui/components/ArrowsMotionTest.kt@@ -0,0 +1,72 @@+package com.vayunmathur.games.arrows.ui.components++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/**+ * The snake timing, as pure arithmetic: the head sets off first and the tail follows a beat+ * later, without any segment ever passing the move's destination.+ */+class ArrowsMotionTest {++    @Test+    fun headMovesImmediatelyWhileTheTailStillWaits() {+        // Four segments: at a tenth of a cell of global travel only the head has started.+        assertEquals(0.1f, laggedAdvance(0.1f, segmentIndex = 3, segmentCount = 4, maxAdvance = 5f))+        assertEquals(0f, laggedAdvance(0.1f, segmentIndex = 0, segmentCount = 4, maxAdvance = 5f))+    }++    @Test+    fun segmentsStartInOrderFromHeadToTail() {+        val count = 5+        var global = 0f+        val started = mutableListOf<Int>()+        while (global <= 1f) {+            for (index in 0 until count) {+                if (index !in started && laggedAdvance(global, index, count, maxAdvance = 5f) > 0f) {+                    started += index+                }+            }+            global += 0.05f+        }+        assertEquals(listOf(4, 3, 2, 1, 0), started, "head first, tail last")+    }++    @Test+    fun everySegmentLandsExactlyOnMaxAdvanceAtTheGlobalTarget() {+        val max = 7f+        for (count in 1..6) {+            val target = globalAdvanceTarget(max, count)+            for (index in 0 until count) {+                assertEquals(+                    max, laggedAdvance(target, index, count, max),+                    "segment $index of $count should finish at max",+                )+            }+        }+    }++    @Test+    fun advanceIsOrderedAndBoundedThroughoutTheMove() {+        val count = 4+        val max = 3f+        var global = 0f+        val target = globalAdvanceTarget(max, count)+        while (global <= target) {+            val advances = (0 until count).map { laggedAdvance(global, it, count, max) }+            assertTrue(advances.all { it in 0f..max }, "bounded at global $global: $advances")+            assertTrue(+                advances.zipWithNext().all { (behind, ahead) -> behind <= ahead },+                "tail never ahead of head at global $global: $advances",+            )+            global += 0.1f+        }+    }++    @Test+    fun singleSegmentHasNoLagAndMatchesGlobal() {+        assertEquals(2f, globalAdvanceTarget(2f, segmentCount = 1))+        assertEquals(1.5f, laggedAdvance(1.5f, segmentIndex = 0, segmentCount = 1, maxAdvance = 2f))+    }+}