nonogram: drag to fill, cross or clear a whole run of cells (#ux-audit)
- Commit
a02fb801aa6d0ee2f723c4bedbe51bb6fd301686- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-13 01:22 UTC (23 days ago)
- Parents
3e6ec0c
Symptom: every cell had to be tapped individually - a 15-cell run was
15 separate taps - because each cell carried its own tap detector and
nothing tracked a finger moving across the grid.
Root cause: NonogramCell had a per-cell pointerInput/detectTapGestures;
there was no grid-level gesture and no notion of a stroke.
Fix:
- New pure domain/NonogramStrokes: a stroke begins on a cell and is
extended as the finger moves.
- The first cell that takes input decides the action: fill in fill
mode; in cross mode, clear if that cell has an X, else cross. A
stroke that starts on a settled cell waits for the first live one.
- On reaching a second cell the stroke locks to the first cell's row
or column (whichever the finger moved further along), so a wobbly
horizontal drag stays in its row.
- Every cell between two pointer positions is walked, so fast swipes
don't skip cells; each cell is applied at most once per stroke
(back-and-forth never un-crosses).
- Fill strokes stop at the first wrong cell: it is revealed, costs
one heart and ends the stroke, so a stroke can never cost more than
one heart. Fill sweeps step over the player's Xs (an X protects its
cell); starting a stroke on an X still attempts it, as a tap did.
- ViewModel gains beginStroke/extendStroke/endStroke on the UI
contract; tapCell/crossCell are now one-cell strokes, so taps,
drags and TalkBack actions share one code path.
- ui/components/BoardGestures: one pointer handler on the whole grid.
Tap -> one-cell stroke. Leaving touch slop -> stroke in the current
mode. Long press -> haptic, then a stroke in the *other* mode that
keeps following the finger. Long press keeps exactly its old meaning
("the other mark") and simply extends to runs, so the Fill/Cross
toggle remains the one answer to "what does a plain touch do".
Hit-testing is a pure BoardGeometry.cellAt() that clamps to the grid
edge and mirrors columns under RTL (the grid Row mirrors there).
- NonogramBoard now takes NonogramGameActions instead of two lambdas.
Board code is split into BoardCell.kt / BoardClues.kt (moved
unchanged) to stay under the 350-line ui file limit.
User-visible effect: drag along a row or column to fill, cross out or
clear many cells at once; a wrong cell stops the drag and costs a
single heart; long-press-and-drag paints the other mark.
Verification: NonogramStrokesTest (first-cell decision, line lock,
skipped-cell walking, once-per-cell, stop at first wrong + one heart,
X protection, settled start, game over, win mid-stroke),
BoardGeometryTest (LTR, RTL mirroring, clamping), Compose tests for
tap / drag / long-press strokes and RTL hit-testing, and Robolectric VM
tests for a drag across a row with a mistake and a long-press stroke.Diff
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramStrokes.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramStrokes.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramStrokes.ktnew file mode 100644index 0000000000..90a868e185--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/domain/NonogramStrokes.kt@@ -0,0 +1,123 @@+package com.vayunmathur.games.nonogram.domain++import com.vayunmathur.games.nonogram.data.CellMark+import com.vayunmathur.games.nonogram.data.MarkMode+import com.vayunmathur.games.nonogram.data.NonogramGameState+import kotlin.math.abs+import kotlin.math.sign++/** What every cell of one stroke gets. Decided by the first cell that takes input. */+enum class StrokeAction {+ /** Fill attempt: picture cells fill, the first wrong one is revealed, costs a heart, and ends it. */+ FILL,++ /** Puts the player's X on blank cells. */+ CROSS,++ /** Takes the player's X off. */+ CLEAR,+}++/** The line a stroke is locked to once it leaves its first cell. */+enum class StrokeAxis { ROW, COLUMN }++/**+ * One finger-down-to-finger-up gesture over the grid. A tap is a stroke of one cell.+ *+ * @property mode the mark mode this stroke paints with: the toggle's mode, or the other one for a+ * stroke that began with a long press.+ * @property anchor the cell the finger went down on.+ * @property action set by the first cell that takes input, then fixed for the stroke.+ * @property axis set once the finger reaches a second cell, then fixed for the stroke.+ * @property visited every cell the stroke has passed, applied or skipped; each is handled once.+ * @property head the cell the stroke last walked to along its line.+ * @property stopped set by a wrong fill or the end of the game; the rest of the stroke does nothing.+ */+data class Stroke(+ val mode: MarkMode,+ val anchor: Int,+ val action: StrokeAction? = null,+ val axis: StrokeAxis? = null,+ val visited: Set<Int> = emptySet(),+ val head: Int = anchor,+ val stopped: Boolean = false,+)++/** A board and the stroke that produced it. */+data class StrokeStep(val game: NonogramGameState, val stroke: Stroke)++/**+ * Drag-to-fill, as pure functions over a [NonogramGameState].+ *+ * Rules:+ * - The first cell that takes input decides the [StrokeAction]: fill in fill mode; in cross mode,+ * clear when that cell already carries an X and cross otherwise. A stroke that starts on a settled+ * cell waits for the first unsettled one.+ * - Once the finger reaches another cell the stroke locks to the first cell's row or column, picking+ * whichever the finger has moved further along, so a wobbly horizontal drag stays in its row.+ * - Every cell between the last position and the new one is walked, so a fast swipe that skips+ * cells between two pointer events still marks them, and each cell is handled at most once.+ * - Fill strokes only paint blank cells after the first: an X the player placed protects its cell+ * from a sweep (tapping an X in fill mode still attempts it, as before).+ * - A wrong fill reveals that cell, costs one heart and stops the stroke, so one stroke can never+ * cost more than one heart.+ */+object NonogramStrokes {++ /** The action a stroke would take if it started on [index], or null if that cell takes no input. */+ fun actionFor(game: NonogramGameState, index: Int, mode: MarkMode): StrokeAction? = when {+ game.isLocked(index) -> null+ mode == MarkMode.FILL -> StrokeAction.FILL+ index in game.crossed -> StrokeAction.CLEAR+ else -> StrokeAction.CROSS+ }++ /** Starts a stroke on [index] and applies it to that cell. */+ fun begin(game: NonogramGameState, index: Int, mode: MarkMode): StrokeStep =+ visit(game, Stroke(mode = mode, anchor = index), index)++ /** Moves the stroke on to the cell under the finger, [index], marking every cell on the way. */+ fun extend(game: NonogramGameState, stroke: Stroke, index: Int): StrokeStep {+ if (stroke.stopped || index == stroke.anchor && stroke.axis == null) return StrokeStep(game, stroke)+ val n = game.size+ val axis = stroke.axis ?: axisTowards(stroke.anchor, index, n)+ val target = when (axis) {+ StrokeAxis.ROW -> stroke.anchor / n * n + index % n+ StrokeAxis.COLUMN -> index / n * n + stroke.anchor % n+ }+ val step = (if (axis == StrokeAxis.ROW) 1 else n) * (target - stroke.head).sign+ var current = StrokeStep(game, stroke.copy(axis = axis))+ var cursor = stroke.head+ while (cursor != target && !current.stroke.stopped) {+ cursor += step+ current = visit(current.game, current.stroke, cursor)+ }+ return current.copy(stroke = current.stroke.copy(head = cursor))+ }++ private fun axisTowards(anchor: Int, index: Int, n: Int): StrokeAxis {+ val dRow = abs(index / n - anchor / n)+ val dCol = abs(index % n - anchor % n)+ return if (dCol >= dRow) StrokeAxis.ROW else StrokeAxis.COLUMN+ }++ private fun visit(game: NonogramGameState, stroke: Stroke, index: Int): StrokeStep {+ if (stroke.stopped || index in stroke.visited) return StrokeStep(game, stroke)+ val seen = stroke.copy(visited = stroke.visited + index)+ val decided = seen.action+ val action = decided ?: actionFor(game, index, seen.mode) ?: return StrokeStep(game, seen)+ val next = apply(game, action, index, deciding = decided == null)+ val wrongFill = next.hearts < game.hearts+ return StrokeStep(next, seen.copy(action = action, stopped = wrongFill || next.isOver))+ }++ private fun apply(game: NonogramGameState, action: StrokeAction, index: Int, deciding: Boolean) =+ when (action) {+ StrokeAction.FILL ->+ if (deciding || game.markAt(index) == CellMark.BLANK) NonogramMoves.guess(game, index) else game+ StrokeAction.CROSS ->+ if (game.markAt(index) == CellMark.BLANK) NonogramMoves.setNote(game, index, true) else game+ StrokeAction.CLEAR ->+ if (game.markAt(index) == CellMark.CROSSED) NonogramMoves.setNote(game, index, false) else game+ }+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.ktindex 93268f93c3..1765302b02 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramUiContract.kt@@ -15,12 +15,24 @@ import com.vayunmathur.games.nonogram.data.NonogramGameState * Every member has a no-op default, so `Noop` is the whole implementation a preview needs. */ interface NonogramGameActions {- /** Tap: places whichever mark the current [MarkMode] selects. */+ /** Tap: places whichever mark the current [MarkMode] selects. A one-cell stroke. */ fun tapCell(index: Int) {} - /** Long press: places the other mark, whatever the mode is. */+ /** Long press: places the other mark, whatever the mode is. A one-cell alternate stroke. */ fun crossCell(index: Int) {} + /**+ * A finger went down on [index] and the gesture became a stroke: a tap, a drag, or (with+ * [alternate]) a long press, which paints with the other mark for the rest of the stroke.+ */+ fun beginStroke(index: Int, alternate: Boolean) {}++ /** The stroke's finger is now over [index]. */+ fun extendStroke(index: Int) {}++ /** The stroke's finger lifted (or the gesture was cancelled). */+ fun endStroke() {}+ fun setMarkMode(mode: MarkMode) {} fun nextLevel() {} fun restartLevel() {}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.ktindex 5350158ad6..6bd833fab8 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/platform/NonogramViewModel.kt@@ -14,7 +14,8 @@ import com.vayunmathur.games.nonogram.data.STARTING_HEARTS import com.vayunmathur.games.nonogram.data.StoredBoard import com.vayunmathur.games.nonogram.data.sizeForLevel import com.vayunmathur.games.nonogram.domain.NonogramGenerator-import com.vayunmathur.games.nonogram.domain.NonogramMoves+import com.vayunmathur.games.nonogram.domain.NonogramStrokes+import com.vayunmathur.games.nonogram.domain.Stroke import com.vayunmathur.library.util.AchievementsManager import com.vayunmathur.library.util.DailyChallengeStore import com.vayunmathur.library.util.DailyStreakReporter@@ -243,12 +244,8 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application * point of the mode: crossing off a long run of cells should not be a gamble. */ override fun tapCell(index: Int) {- val state = _uiState.value- val game = state.game ?: return- commit(- if (state.markMode == MarkMode.CROSS) NonogramMoves.toggleNote(game, index)- else NonogramMoves.guess(game, index)- )+ beginStroke(index, alternate = false)+ endStroke() } /**@@ -259,12 +256,36 @@ class NonogramViewModel(application: Application) : AndroidViewModel(application * is the player's own working, and being wrong in a note is not a guess the game should punish. */ override fun crossCell(index: Int) {+ beginStroke(index, alternate = true)+ endStroke()+ }++ /** The stroke in progress, if a finger is down on the grid. See [NonogramStrokes]. */+ private var stroke: Stroke? = null++ override fun beginStroke(index: Int, alternate: Boolean) { val state = _uiState.value val game = state.game ?: return- commit(- if (state.markMode == MarkMode.CROSS) NonogramMoves.guess(game, index)- else NonogramMoves.toggleNote(game, index)- )+ val mode = when {+ !alternate -> state.markMode+ state.markMode == MarkMode.FILL -> MarkMode.CROSS+ else -> MarkMode.FILL+ }+ val step = NonogramStrokes.begin(game, index, mode)+ stroke = step.stroke+ commit(step.game)+ }++ override fun extendStroke(index: Int) {+ val current = stroke ?: return+ val game = _uiState.value.game ?: return+ val step = NonogramStrokes.extend(game, current, index)+ stroke = step.stroke+ commit(step.game)+ }++ override fun endStroke() {+ stroke = null } override fun setMarkMode(mode: MarkMode) {
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.ktindex 93dba66368..05b6b1b082 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/NonogramGameScreen.kt@@ -174,8 +174,7 @@ fun NonogramGameScreen( ) { NonogramBoard( game = game,- onTap = actions::tapCell,- onLongPress = actions::crossCell,+ actions = actions, markMode = state.markMode, modifier = Modifier .widthIn(max = BoardMaxWidth)@@ -207,8 +206,7 @@ fun NonogramGameScreen( NonogramBoard( game = game,- onTap = actions::tapCell,- onLongPress = actions::crossCell,+ actions = actions, markMode = state.markMode, modifier = Modifier .widthIn(max = BoardMaxWidth)
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardCell.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardCell.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardCell.ktnew file mode 100644index 0000000000..1c4157c777--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardCell.kt@@ -0,0 +1,154 @@+package com.vayunmathur.games.nonogram.ui.components++import androidx.compose.foundation.background+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.fillMaxSize+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.Immutable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.draw.drawBehind+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.semantics.clearAndSetSemantics+import androidx.compose.ui.semantics.contentDescription+import androidx.compose.ui.semantics.onClick+import androidx.compose.ui.semantics.onLongClick+import androidx.compose.ui.semantics.stateDescription+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.dp+import com.vayunmathur.games.nonogram.R+import com.vayunmathur.games.nonogram.data.CellMark+import com.vayunmathur.games.nonogram.data.MarkMode+import com.vayunmathur.library.ui.MaterialTheme++// One grid cell of [NonogramBoard], plus the grid-line overlay drawn over all of them.++/** The state words and action names TalkBack reads, looked up once per grid. */+@Immutable+internal data class CellLabels(+ val filled: String,+ val crossed: String,+ val revealed: String,+ val blank: String,+ val fill: String,+ val cross: String,+ val uncross: String,+) {+ fun wordFor(mark: CellMark): String = when (mark) {+ CellMark.FILLED -> filled+ CellMark.CROSSED -> crossed+ CellMark.REVEALED -> revealed+ CellMark.BLANK -> blank+ }++ /** What a tap (TalkBack double tap) does: the mode's own mark. */+ fun tapLabel(mark: CellMark, mode: MarkMode): String =+ if (mode == MarkMode.FILL) fill else noteLabel(mark)++ /** What a long press (TalkBack double tap and hold) does: the other mark. */+ fun longPressLabel(mark: CellMark, mode: MarkMode): String =+ if (mode == MarkMode.FILL) noteLabel(mark) else fill++ private fun noteLabel(mark: CellMark) = if (mark == CellMark.CROSSED) uncross else cross+}++/** Zero-based row and column, kept together so the cell signature stays short. */+@Immutable+internal data class CellPosition(val row: Int, val col: Int)++@Composable+internal fun NonogramCell(+ mark: CellMark,+ index: Int,+ position: CellPosition,+ stateWord: String,+ tapLabel: String?,+ longPressLabel: String?,+ onTap: (Int) -> Unit,+ onLongPress: (Int) -> Unit,+ modifier: Modifier = Modifier,+) {+ val scheme = MaterialTheme.colorScheme++ // A fill only ever lands on a cell that belongs to the picture, because a wrong guess is turned+ // into a revealed blank instead. That revealed blank gets a tinted cell and an error-coloured X so+ // it reads as "the game told you" rather than the player's own grey note: colour plus a filled+ // background, so it does not rely on hue alone.+ val background = when (mark) {+ CellMark.FILLED -> scheme.onSurface+ CellMark.REVEALED -> scheme.errorContainer+ else -> Color.Transparent+ }+ val description = stringResource(R.string.cd_cell_position, position.row + 1, position.col + 1)++ Box(+ modifier+ .background(background)+ // Touch input is handled once for the whole grid (see strokeGestures), so cells only+ // draw and describe themselves.+ // Position as the description, the mark as state, and the same two moves a finger has+ // as named actions โ without them TalkBack could read a cell but never fill or cross it.+ .clearAndSetSemantics {+ contentDescription = description+ stateDescription = stateWord+ if (tapLabel != null) onClick(label = tapLabel) { onTap(index); true }+ if (longPressLabel != null) onLongClick(label = longPressLabel) { onLongPress(index); true }+ },+ contentAlignment = Alignment.Center,+ ) {+ if (mark == CellMark.CROSSED || mark == CellMark.REVEALED) {+ val revealed = mark == CellMark.REVEALED+ Box(+ Modifier+ .fillMaxSize()+ .padding(CrossInset)+ .drawCross(+ color = if (revealed) scheme.onErrorContainer else scheme.onSurfaceVariant,+ width = if (revealed) RevealedCrossWidth else NoteCrossWidth,+ )+ )+ }+ }+}++/** Keeps the X clear of the cell borders so it reads as a mark rather than a filled square. */+private val CrossInset = 3.dp++/** The player's own note: a light grey X. */+private val NoteCrossWidth = 1.5.dp++/** A blank a mistake revealed: heavier, so it differs in weight as well as colour. */+private val RevealedCrossWidth = 2.5.dp++private fun Modifier.drawCross(color: Color, width: Dp) = drawBehind {+ val stroke = width.toPx()+ drawLine(color, Offset(0f, 0f), Offset(size.width, size.height), stroke)+ drawLine(color, Offset(size.width, 0f), Offset(0f, size.height), stroke)+}++/**+ * Every cell edge, with a heavier stroke every five cells and around the outside.+ *+ * The five-cell grouping is the standard nonogram aid: it lets a player count along a long line+ * without losing their place. Drawn in one pass over the whole grid so shared edges are painted once.+ */+internal fun Modifier.drawGridLines(size: Int, thin: Color, thick: Color) = drawBehind {+ val step = this.size.width / size+ val thinPx = 1.dp.toPx()+ val thickPx = 2f * thinPx++ for (i in 0..size) {+ val offset = i * step+ val heavy = i % GROUP == 0 || i == size+ val color = if (heavy) thick else thin+ val width = if (heavy) thickPx else thinPx+ drawLine(color, Offset(offset, 0f), Offset(offset, this.size.height), width)+ drawLine(color, Offset(0f, offset), Offset(this.size.width, offset), width)+ }+}++/** Cells per heavy guide line. */+private const val GROUP = 5
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardClues.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardClues.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardClues.ktnew file mode 100644index 0000000000..7c040a5334--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardClues.kt@@ -0,0 +1,93 @@+package com.vayunmathur.games.nonogram.ui.components++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Box+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.size+import androidx.compose.runtime.Composable+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.style.TextAlign+import androidx.compose.ui.unit.Dp+import androidx.compose.ui.unit.TextUnit+import com.vayunmathur.games.nonogram.data.NonogramGameState+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text++// The clue gutters of [NonogramBoard]: column clues across the top, row clues down the side.++@Composable+internal fun ColumnClues(+ game: NonogramGameState,+ gutterCells: Int,+ cell: Dp,+ clueCell: Dp,+ fontSize: TextUnit,+ lineHeight: TextUnit,+) {+ Row {+ for (col in 0 until game.size) {+ val clues = game.puzzle.colClues[col]+ Column(+ Modifier.size(cell, clueCell * gutterCells),+ // Bottom-aligned so the last clue sits against the grid it describes.+ verticalArrangement = Arrangement.Bottom,+ horizontalAlignment = Alignment.CenterHorizontally,+ ) {+ for (clue in clues.ifEmpty { listOf(0) }) {+ ClueText(clue, fontSize, lineHeight, Modifier.size(cell, clueCell))+ }+ }+ }+ }+}++@Composable+internal fun RowClues(+ game: NonogramGameState,+ gutterCells: Int,+ cell: Dp,+ clueCell: Dp,+ fontSize: TextUnit,+ lineHeight: TextUnit,+) {+ Column {+ for (row in 0 until game.size) {+ val clues = game.puzzle.rowClues[row]+ Row(+ Modifier.size(clueCell * gutterCells, cell),+ // End-aligned for the same reason: the final clue abuts the grid.+ horizontalArrangement = Arrangement.End,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ for (clue in clues.ifEmpty { listOf(0) }) {+ ClueText(clue, fontSize, lineHeight, Modifier.size(clueCell, cell))+ }+ }+ }+ }+}++@Composable+private fun ClueText(+ clue: Int,+ fontSize: TextUnit,+ lineHeight: TextUnit,+ modifier: Modifier = Modifier,+) {+ Box(modifier, contentAlignment = Alignment.Center) {+ Text(+ text = clue.toString(),+ fontSize = fontSize,+ lineHeight = lineHeight,+ maxLines = 1,+ softWrap = false,+ fontWeight = FontWeight.Medium,+ textAlign = TextAlign.Center,+ color = if (clue == 0) MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)+ else MaterialTheme.colorScheme.onSurface,+ )+ }+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGestures.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGestures.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGestures.ktnew file mode 100644index 0000000000..78d9dcb788--- /dev/null+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/BoardGestures.kt@@ -0,0 +1,127 @@+package com.vayunmathur.games.nonogram.ui.components++import androidx.compose.foundation.gestures.awaitEachGesture+import androidx.compose.foundation.gestures.awaitFirstDown+import androidx.compose.ui.Modifier+import androidx.compose.ui.geometry.Offset+import androidx.compose.ui.input.pointer.AwaitPointerEventScope+import androidx.compose.ui.input.pointer.PointerId+import androidx.compose.ui.input.pointer.pointerInput+import androidx.compose.ui.input.pointer.positionChanged+import androidx.compose.ui.unit.IntSize+import com.vayunmathur.games.nonogram.platform.NonogramGameActions+import kotlin.math.floor++/**+ * Pure grid geometry for touch input.+ *+ * Kept free of Compose so the hit-testing can be unit tested directly, including the right-to-left+ * case: the grid's columns are laid out with `Row`, which mirrors under RTL, so physical x = 0 is+ * the *last* column there.+ */+internal object BoardGeometry {++ /**+ * The cell under ([x], [y]), in pixels from the top-left of a [gridPx]-square grid of [n] x [n].+ *+ * Points outside the grid clamp onto its nearest edge cell, so a drag that overshoots the board+ * keeps extending along the edge instead of dropping out.+ */+ fun cellAt(x: Float, y: Float, gridPx: Float, n: Int, rtl: Boolean): Int {+ val cellPx = gridPx / n+ val physicalCol = floor(x / cellPx).toInt().coerceIn(0, n - 1)+ val row = floor(y / cellPx).toInt().coerceIn(0, n - 1)+ val col = if (rtl) n - 1 - physicalCol else physicalCol+ return row * n + col+ }+}++/** How the opening moments of a touch resolved, before it became a stroke. */+private sealed interface Press {+ /** Lifted within the long-press timeout without leaving touch slop. */+ data object Tap : Press++ /** Left touch slop before the long-press timeout: a drag in the mode's own mark. */+ data class Drag(val position: Offset) : Press++ /** The pointer went away without lifting (the gesture was taken from us). */+ data object Cancelled : Press+}++/**+ * One gesture handler for the whole grid, turning touches into strokes on [actions].+ *+ * - Tap: a one-cell stroke in the current mode.+ * - Drag: begins once the finger leaves touch slop; the stroke follows the finger cell by cell.+ * - Long press: [onLongPress] (haptics), then a stroke in the *other* mode, which keeps following+ * the finger โ so long-press-and-drag crosses a run in fill mode, or fills one in cross mode.+ * This keeps long press meaning exactly what it did before ("the other mark") while extending it+ * to runs, so the mode toggle stays the single answer to "what does a plain touch do".+ *+ * [n] and [rtl] are keys: the handler restarts if the grid size or layout direction changes.+ * Every change is consumed so an enclosing scroll or double-tap detector never sees grid touches.+ */+internal fun Modifier.strokeGestures(+ n: Int,+ rtl: Boolean,+ actions: () -> NonogramGameActions,+ onLongPress: () -> Unit,+): Modifier = pointerInput(n, rtl) {+ fun cellAt(position: Offset, size: IntSize) =+ BoardGeometry.cellAt(position.x, position.y, size.width.toFloat(), n, rtl)++ awaitEachGesture {+ val down = awaitFirstDown(requireUnconsumed = false)+ down.consume()+ val start = cellAt(down.position, size)+ val press = withTimeoutOrNull(viewConfiguration.longPressTimeoutMillis) {+ awaitTapOrDrag(down.id, down.position, viewConfiguration.touchSlop)+ }+ when (press) {+ Press.Tap -> {+ actions().beginStroke(start, alternate = false)+ actions().endStroke()+ }+ is Press.Drag -> {+ actions().beginStroke(start, alternate = false)+ actions().extendStroke(cellAt(press.position, size))+ followStroke(down.id, actions) { cellAt(it, size) }+ }+ null -> {+ onLongPress()+ actions().beginStroke(start, alternate = true)+ followStroke(down.id, actions) { cellAt(it, size) }+ }+ Press.Cancelled -> Unit+ }+ }+}++private suspend fun AwaitPointerEventScope.awaitTapOrDrag(id: PointerId, origin: Offset, slop: Float): Press {+ while (true) {+ val change = awaitPointerEvent().changes.firstOrNull { it.id == id } ?: return Press.Cancelled+ change.consume()+ if (!change.pressed) return Press.Tap+ if ((change.position - origin).getDistance() > slop) return Press.Drag(change.position)+ }+}++/** Feeds the finger's cell to the stroke until it lifts; always ends the stroke, even if cancelled. */+private suspend fun AwaitPointerEventScope.followStroke(+ id: PointerId,+ actions: () -> NonogramGameActions,+ cellAt: (Offset) -> Int,+) {+ try {+ while (true) {+ val change = awaitPointerEvent().changes.firstOrNull { it.id == id } ?: break+ // positionChanged() reads as false once consumed, so check before consuming.+ val moved = change.positionChanged()+ change.consume()+ if (!change.pressed) break+ if (moved) actions().extendStroke(cellAt(change.position))+ }+ } finally {+ actions().endStroke()+ }+}
games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt
diff --git a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.ktindex f4b8f75688..d6da1f9ca3 100644--- a/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt+++ b/games/nonogram/src/main/java/com/vayunmathur/games/nonogram/ui/components/NonogramBoard.kt@@ -1,47 +1,27 @@ package com.vayunmathur.games.nonogram.ui.components -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.BoxWithConstraints import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row-import androidx.compose.foundation.layout.fillMaxSize-import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.runtime.Composable-import androidx.compose.runtime.Immutable import androidx.compose.runtime.getValue import androidx.compose.runtime.remember import androidx.compose.runtime.rememberUpdatedState-import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier-import androidx.compose.ui.draw.drawBehind-import androidx.compose.ui.geometry.Offset-import androidx.compose.ui.graphics.Color-import androidx.compose.ui.hapticfeedback.HapticFeedbackType-import androidx.compose.ui.input.pointer.pointerInput import androidx.compose.ui.platform.LocalDensity-import androidx.compose.ui.platform.LocalHapticFeedback+import androidx.compose.ui.platform.LocalLayoutDirection import androidx.compose.ui.res.stringResource-import androidx.compose.ui.semantics.clearAndSetSemantics-import androidx.compose.ui.semantics.contentDescription-import androidx.compose.ui.semantics.onClick-import androidx.compose.ui.semantics.onLongClick-import androidx.compose.ui.semantics.stateDescription-import androidx.compose.ui.text.font.FontWeight-import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.Dp-import androidx.compose.ui.unit.TextUnit+import androidx.compose.ui.unit.LayoutDirection import androidx.compose.ui.unit.dp import com.vayunmathur.games.nonogram.R-import com.vayunmathur.games.nonogram.data.CellMark import com.vayunmathur.games.nonogram.data.MarkMode import com.vayunmathur.games.nonogram.data.NonogramGameState-import com.vayunmathur.library.ui.ColorScheme+import com.vayunmathur.games.nonogram.platform.NonogramGameActions import com.vayunmathur.library.ui.MaterialTheme-import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.rememberHaptics /** * The grid with its clues.@@ -50,12 +30,15 @@ import com.vayunmathur.library.ui.Text * clues down the left, and the grid itself. The clue gutters are sized from the longest clue on that * axis so nothing is ever clipped, and everything scales off the cell size so a 5x5 and a 15x15 both * fill the available width.+ *+ * Touch goes through one handler on the whole grid ([strokeGestures]): taps, drags and long presses+ * all become strokes on [actions]. TalkBack's per-cell actions call [NonogramGameActions.tapCell] and+ * [NonogramGameActions.crossCell]; [markMode] only labels those actions. */ @Composable fun NonogramBoard( game: NonogramGameState,- onTap: (Int) -> Unit,- onLongPress: (Int) -> Unit,+ actions: NonogramGameActions, modifier: Modifier = Modifier, markMode: MarkMode = MarkMode.FILL, ) {@@ -90,93 +73,18 @@ fun NonogramBoard( } Row { RowClues(game, rowGutterCells, cell, clueCell, fontSize, lineHeight)- Grid(game, markMode, cell, onTap, onLongPress)+ Grid(game, markMode, cell, actions) } } } } -@Composable-private fun ColumnClues(- game: NonogramGameState,- gutterCells: Int,- cell: Dp,- clueCell: Dp,- fontSize: TextUnit,- lineHeight: TextUnit,-) {- Row {- for (col in 0 until game.size) {- val clues = game.puzzle.colClues[col]- Column(- Modifier.size(cell, clueCell * gutterCells),- // Bottom-aligned so the last clue sits against the grid it describes.- verticalArrangement = Arrangement.Bottom,- horizontalAlignment = Alignment.CenterHorizontally,- ) {- for (clue in clues.ifEmpty { listOf(0) }) {- ClueText(clue, fontSize, lineHeight, Modifier.size(cell, clueCell))- }- }- }- }-}--@Composable-private fun RowClues(- game: NonogramGameState,- gutterCells: Int,- cell: Dp,- clueCell: Dp,- fontSize: TextUnit,- lineHeight: TextUnit,-) {- Column {- for (row in 0 until game.size) {- val clues = game.puzzle.rowClues[row]- Row(- Modifier.size(clueCell * gutterCells, cell),- // End-aligned for the same reason: the final clue abuts the grid.- horizontalArrangement = Arrangement.End,- verticalAlignment = Alignment.CenterVertically,- ) {- for (clue in clues.ifEmpty { listOf(0) }) {- ClueText(clue, fontSize, lineHeight, Modifier.size(clueCell, cell))- }- }- }- }-}--@Composable-private fun ClueText(- clue: Int,- fontSize: TextUnit,- lineHeight: TextUnit,- modifier: Modifier = Modifier,-) {- Box(modifier, contentAlignment = Alignment.Center) {- Text(- text = clue.toString(),- fontSize = fontSize,- lineHeight = lineHeight,- maxLines = 1,- softWrap = false,- fontWeight = FontWeight.Medium,- textAlign = TextAlign.Center,- color = if (clue == 0) MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)- else MaterialTheme.colorScheme.onSurface,- )- }-}- @Composable private fun Grid( game: NonogramGameState, markMode: MarkMode, cell: Dp,- onTap: (Int) -> Unit,- onLongPress: (Int) -> Unit,+ actions: NonogramGameActions, ) { val scheme = MaterialTheme.colorScheme // Resolved once per grid rather than once per cell per tap.@@ -190,18 +98,24 @@ private fun Grid( uncross = stringResource(R.string.action_uncross), ) val over = game.isOver+ val n = game.size+ val rtl = LocalLayoutDirection.current == LayoutDirection.Rtl+ val haptics = rememberHaptics() // Stable callbacks: the cells get the same lambda instance every recomposition, so a cell whose // mark did not change is skipped outright instead of being recomposed for a new closure.- val currentTap by rememberUpdatedState(onTap)- val currentLongPress by rememberUpdatedState(onLongPress)- val tap = remember { { index: Int -> currentTap(index) } }- val longPress = remember { { index: Int -> currentLongPress(index) } }- Box {+ val currentActions by rememberUpdatedState(actions)+ val tap = remember { { index: Int -> currentActions.tapCell(index) } }+ val longPress = remember { { index: Int -> currentActions.crossCell(index) } }+ Box(+ Modifier+ .size(cell * n)+ .strokeGestures(n, rtl, actions = { currentActions }, onLongPress = { haptics.longPress() })+ ) { Column {- for (row in 0 until game.size) {+ for (row in 0 until n) { Row {- for (col in 0 until game.size) {- val index = row * game.size + col+ for (col in 0 until n) {+ val index = row * n + col // Each cell sees only its own mark, so one tap recomposes one cell, not all // 225 of a 15x15. val mark = game.markAt(index)@@ -225,149 +139,12 @@ private fun Grid( } Box( Modifier- .size(cell * game.size)- .drawGridLines(game.size, scheme.outlineVariant, scheme.onSurface)+ .size(cell * n)+ .drawGridLines(n, scheme.outlineVariant, scheme.onSurface) ) } } -/** The state words and action names TalkBack reads, looked up once per grid. */-@Immutable-private data class CellLabels(- val filled: String,- val crossed: String,- val revealed: String,- val blank: String,- val fill: String,- val cross: String,- val uncross: String,-) {- fun wordFor(mark: CellMark): String = when (mark) {- CellMark.FILLED -> filled- CellMark.CROSSED -> crossed- CellMark.REVEALED -> revealed- CellMark.BLANK -> blank- }-- /** What a tap (TalkBack double tap) does: the mode's own mark. */- fun tapLabel(mark: CellMark, mode: MarkMode): String =- if (mode == MarkMode.FILL) fill else noteLabel(mark)-- /** What a long press (TalkBack double tap and hold) does: the other mark. */- fun longPressLabel(mark: CellMark, mode: MarkMode): String =- if (mode == MarkMode.FILL) noteLabel(mark) else fill-- private fun noteLabel(mark: CellMark) = if (mark == CellMark.CROSSED) uncross else cross-}--/** Zero-based row and column, kept together so the cell signature stays short. */-@Immutable-private data class CellPosition(val row: Int, val col: Int)--@Composable-private fun NonogramCell(- mark: CellMark,- index: Int,- position: CellPosition,- stateWord: String,- tapLabel: String?,- longPressLabel: String?,- onTap: (Int) -> Unit,- onLongPress: (Int) -> Unit,- modifier: Modifier = Modifier,-) {- val scheme = MaterialTheme.colorScheme- val haptics = LocalHapticFeedback.current-- // A fill only ever lands on a cell that belongs to the picture, because a wrong guess is turned- // into a revealed blank instead. That revealed blank gets a tinted cell and an error-coloured X so- // it reads as "the game told you" rather than the player's own grey note: colour plus a filled- // background, so it does not rely on hue alone.- val background = when (mark) {- CellMark.FILLED -> scheme.onSurface- CellMark.REVEALED -> scheme.errorContainer- else -> Color.Transparent- }- val description = stringResource(R.string.cd_cell_position, position.row + 1, position.col + 1)-- Box(- modifier- .background(background)- .pointerInput(index) {- // The ViewModel ignores taps on settled cells and finished boards, so the handler- // does not need to restart whenever those change.- detectTapGestures(- onTap = { onTap(index) },- onLongPress = {- haptics.performHapticFeedback(HapticFeedbackType.LongPress)- onLongPress(index)- },- )- }- // Position as the description, the mark as state, and the same two moves a finger has- // as named actions โ without them TalkBack could read a cell but never fill or cross it.- .clearAndSetSemantics {- contentDescription = description- stateDescription = stateWord- if (tapLabel != null) onClick(label = tapLabel) { onTap(index); true }- if (longPressLabel != null) onLongClick(label = longPressLabel) { onLongPress(index); true }- },- contentAlignment = Alignment.Center,- ) {- if (mark == CellMark.CROSSED || mark == CellMark.REVEALED) {- val revealed = mark == CellMark.REVEALED- Box(- Modifier- .fillMaxSize()- .padding(CrossInset)- .drawCross(- color = if (revealed) scheme.onErrorContainer else scheme.onSurfaceVariant,- width = if (revealed) RevealedCrossWidth else NoteCrossWidth,- )- )- }- }-}--/** Keeps the X clear of the cell borders so it reads as a mark rather than a filled square. */-private val CrossInset = 3.dp--/** The player's own note: a light grey X. */-private val NoteCrossWidth = 1.5.dp--/** A blank a mistake revealed: heavier, so it differs in weight as well as colour. */-private val RevealedCrossWidth = 2.5.dp--private fun Modifier.drawCross(color: Color, width: Dp) = drawBehind {- val stroke = width.toPx()- drawLine(color, Offset(0f, 0f), Offset(size.width, size.height), stroke)- drawLine(color, Offset(size.width, 0f), Offset(0f, size.height), stroke)-}--/**- * Every cell edge, with a heavier stroke every five cells and around the outside.- *- * The five-cell grouping is the standard nonogram aid: it lets a player count along a long line- * without losing their place. Drawn in one pass over the whole grid so shared edges are painted once.- */-private fun Modifier.drawGridLines(size: Int, thin: Color, thick: Color) = drawBehind {- val step = this.size.width / size- val thinPx = 1.dp.toPx()- val thickPx = 2f * thinPx-- for (i in 0..size) {- val offset = i * step- val heavy = i % GROUP == 0 || i == size- val color = if (heavy) thick else thin- val width = if (heavy) thickPx else thinPx- drawLine(color, Offset(offset, 0f), Offset(offset, this.size.height), width)- drawLine(color, Offset(0f, offset), Offset(this.size.width, offset), width)- }-}--/** Cells per heavy guide line. */-private const val GROUP = 5- /** Clue digit height as a fraction of its slot, leaving room for the side bearings of "15". */ private const val CLUE_TEXT_FRACTION = 0.78f
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramStrokesTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramStrokesTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramStrokesTest.ktnew file mode 100644index 0000000000..082cd5c2d4--- /dev/null+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/domain/NonogramStrokesTest.kt@@ -0,0 +1,125 @@+package com.vayunmathur.games.nonogram.domain++import com.vayunmathur.games.nonogram.data.GameMode+import com.vayunmathur.games.nonogram.data.MarkMode+import com.vayunmathur.games.nonogram.data.NonogramGameState+import com.vayunmathur.games.nonogram.data.NonogramPuzzle+import com.vayunmathur.games.nonogram.data.STARTING_HEARTS+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class NonogramStrokesTest {+ // 5x5, row-major. Row 0 = # # . # #, row 1 = # # # # #, others blank except column 0.+ private val rows = listOf(+ "##.##",+ "#####",+ "#....",+ "#....",+ "#....",+ )+ private val puzzle = NonogramPuzzle.from(5, rows.joinToString("").map { it == '#' })+ private fun game(crossed: Set<Int> = emptySet(), filled: Set<Int> = emptySet(), hearts: Int = STARTING_HEARTS) =+ NonogramGameState(puzzle, filled, crossed, emptySet(), hearts, GameMode.CASUAL, 1)+ private fun idx(row: Int, col: Int) = row * 5 + col++ /** Runs a whole stroke: down on [cells].first(), then the finger over each following cell. */+ private fun stroke(start: NonogramGameState, mode: MarkMode, vararg cells: Int): StrokeStep {+ var step = NonogramStrokes.begin(start, cells.first(), mode)+ for (c in cells.drop(1)) step = NonogramStrokes.extend(step.game, step.stroke, c)+ return step+ }++ @Test fun aTapIsAOneCellStroke() {+ val s = stroke(game(), MarkMode.FILL, idx(1, 2))+ assertEquals(setOf(idx(1, 2)), s.game.filled)+ assertEquals(StrokeAction.FILL, s.stroke.action)+ assertNull(s.stroke.axis)+ }++ @Test fun fillDragPaintsARowAndWalksSkippedCells() {+ // Finger jumps straight from column 0 to column 4: columns 1-3 still get filled.+ val s = stroke(game(), MarkMode.FILL, idx(1, 0), idx(1, 4))+ assertEquals((0..4).map { idx(1, it) }.toSet(), s.game.filled)+ assertEquals(StrokeAxis.ROW, s.stroke.axis)+ assertEquals(STARTING_HEARTS, s.game.hearts)+ }++ @Test fun fillStopsAtTheFirstWrongCellAndCostsOneHeart() {+ // Row 0 is "##.##": the stroke fills 0 and 1, reveals 2, and nothing after it.+ val s = stroke(game(), MarkMode.FILL, idx(0, 0), idx(0, 1), idx(0, 2), idx(0, 3), idx(0, 4))+ assertEquals(setOf(idx(0, 0), idx(0, 1)), s.game.filled)+ assertEquals(setOf(idx(0, 2)), s.game.revealedBlanks)+ assertEquals(STARTING_HEARTS - 1, s.game.hearts, "one heart per stroke, never per cell")+ assertTrue(s.stroke.stopped)+ // Coming back over earlier cells after the stop changes nothing either.+ val after = NonogramStrokes.extend(s.game, s.stroke, idx(0, 0))+ assertEquals(s.game, after.game)+ }++ @Test fun aWrongFirstCellStopsTheStrokeImmediately() {+ val s = stroke(game(), MarkMode.FILL, idx(2, 1), idx(2, 2), idx(2, 3))+ assertEquals(setOf(idx(2, 1)), s.game.revealedBlanks)+ assertEquals(STARTING_HEARTS - 1, s.game.hearts)+ }++ @Test fun theStrokeLocksToItsFirstLine() {+ // Mostly horizontal with a wobble into the next row: stays in row 2.+ val s = stroke(game(), MarkMode.CROSS, idx(2, 1), idx(2, 2), idx(3, 3), idx(3, 4))+ assertEquals((1..4).map { idx(2, it) }.toSet(), s.game.crossed)+ // Mostly vertical: locks to the column even when it starts diagonally.+ val v = stroke(game(), MarkMode.CROSS, idx(2, 2), idx(4, 3))+ assertEquals(StrokeAxis.COLUMN, v.stroke.axis)+ assertEquals(setOf(idx(2, 2), idx(3, 2), idx(4, 2)), v.game.crossed)+ }++ @Test fun eachCellIsAppliedOnce() {+ // Cross mode toggles on a tap, but a stroke going back and forth must not un-cross cells.+ val s = stroke(game(), MarkMode.CROSS, idx(3, 1), idx(3, 3), idx(3, 1), idx(3, 4), idx(3, 2))+ assertEquals((1..4).map { idx(3, it) }.toSet(), s.game.crossed)+ // And back past the anchor reaches new cells on the other side (crossing is free anywhere).+ val both = NonogramStrokes.extend(s.game, s.stroke, idx(3, 0))+ assertTrue(idx(3, 0) in both.game.crossed)+ }++ @Test fun crossModeOnAnXClearsTheRun() {+ val start = game(crossed = setOf(idx(3, 1), idx(3, 2), idx(3, 4)))+ val s = stroke(start, MarkMode.CROSS, idx(3, 1), idx(3, 4))+ assertEquals(StrokeAction.CLEAR, s.stroke.action)+ assertEquals(emptySet(), s.game.crossed, "a clear stroke only removes Xs and never adds one at column 3")+ }++ @Test fun fillStrokesStepOverThePlayersXs() {+ val start = game(crossed = setOf(idx(1, 2)))+ val s = stroke(start, MarkMode.FILL, idx(1, 0), idx(1, 4))+ assertEquals(setOf(idx(1, 0), idx(1, 1), idx(1, 3), idx(1, 4)), s.game.filled)+ assertEquals(setOf(idx(1, 2)), s.game.crossed, "the X protects its cell from the sweep")+ // ...but deliberately starting on the X attempts it, like a tap.+ val tap = stroke(start, MarkMode.FILL, idx(1, 2))+ assertTrue(idx(1, 2) in tap.game.filled)+ }++ @Test fun aStrokeStartingOnASettledCellWaitsForTheFirstLiveOne() {+ val start = game(filled = setOf(idx(1, 0)), crossed = setOf(idx(1, 1)))+ // Cross mode starting on a filled cell: the first live cell is the X at column 1, so clear.+ val s = stroke(start, MarkMode.CROSS, idx(1, 0), idx(1, 3))+ assertEquals(StrokeAction.CLEAR, s.stroke.action)+ assertEquals(emptySet(), s.game.crossed)+ assertNull(NonogramStrokes.actionFor(start, idx(1, 0), MarkMode.CROSS))+ }++ @Test fun nothingHappensOnceTheGameIsOver() {+ val over = game(hearts = 0)+ val s = stroke(over, MarkMode.FILL, idx(1, 0), idx(1, 4))+ assertEquals(over, s.game)+ }++ @Test fun theFinalFillEndsTheStroke() {+ // Fill everything but the last picture cell, then sweep row 1 to win mid-stroke.+ val picture = puzzle.solution.indices.filter { puzzle.solution[it] }.toSet()+ val start = game(filled = picture - idx(1, 4))+ val s = stroke(start, MarkMode.FILL, idx(1, 4))+ assertTrue(s.game.isWon); assertTrue(s.stroke.stopped)+ }+}
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.ktindex 78a7a9bb0f..435b537528 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/platform/NonogramViewModelTest.kt@@ -112,6 +112,38 @@ class NonogramViewModelTest { await("reload") { again.uiState.value.game?.filled == target.toSet() } } + @Test fun dragStrokeFillsALineAndChargesOneHeartForAMistake() {+ val vm = loadedVm()+ val g = vm.uiState.value.game!!+ val n = g.size+ // Pick a row with a blank somewhere after a picture cell, and drag across the whole row.+ val row = (0 until n).first { r ->+ val line = (0 until n).map { g.puzzle.solution[r * n + it] }+ line.indexOf(true).let { it >= 0 && line.drop(it).contains(false) }+ }+ val line = (0 until n).map { row * n + it }+ val firstPicture = line.first { g.puzzle.solution[it] }+ vm.beginStroke(firstPicture, alternate = false)+ for (i in line.filter { it > firstPicture }) vm.extendStroke(i)+ vm.endStroke()+ val after = vm.uiState.value.game!!+ val firstWrong = line.first { it > firstPicture && !g.puzzle.solution[it] }+ assertEquals(line.filter { it in firstPicture until firstWrong }.toSet(), after.filled)+ assertEquals(setOf(firstWrong), after.revealedBlanks)+ assertEquals(STARTING_HEARTS - 1, after.hearts, "a stroke costs at most one heart")+ }++ @Test fun longPressStrokeUsesTheOtherMark() {+ val vm = loadedVm()+ val n = vm.uiState.value.game!!.size+ vm.beginStroke(0, alternate = true)+ vm.extendStroke(n - 1)+ vm.endStroke()+ // Fill mode + long press = a cross stroke: the whole first row is crossed, for free.+ assertEquals((0 until n).toSet(), vm.uiState.value.game!!.crossed)+ assertEquals(STARTING_HEARTS, vm.uiState.value.game!!.hearts)+ }+ @Test fun longPressInFillModeNotesAndRestartClears() { val vm = loadedVm() val g = vm.uiState.value.game!!
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.ktindex 93f6624bf0..4d2de6c32d 100644--- a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/NonogramScreensTest.kt@@ -46,8 +46,13 @@ class NonogramScreensTest { val taps = mutableListOf<Int>(); val crosses = mutableListOf<Int>() val modes = mutableListOf<MarkMode>(); val gameModes = mutableListOf<GameMode>() var next = 0; var restarts = 0; var retries = 0+ /** Every stroke as the gesture handler reported it: begin cell, alternate?, then extensions. */+ val strokes = mutableListOf<MutableList<Any>>(); var openStroke = false override fun tapCell(index: Int) { taps += index } override fun crossCell(index: Int) { crosses += index }+ override fun beginStroke(index: Int, alternate: Boolean) { strokes += mutableListOf<Any>(index, alternate); openStroke = true }+ override fun extendStroke(index: Int) { strokes.last() += index }+ override fun endStroke() { openStroke = false } override fun setMarkMode(mode: MarkMode) { modes += mode } override fun nextLevel() { next++ } override fun restartLevel() { restarts++ }@@ -69,9 +74,9 @@ class NonogramScreensTest { .assert(SemanticsMatcher.expectValue(SemanticsProperties.StateDescription, str(state))) @Test fun talkBackCanFillAndCrossThroughNamedActions() {- val taps = mutableListOf<Int>(); val longs = mutableListOf<Int>()+ val a = Recording() rule.setContent {- NonogramBoard(game = game(filled = setOf(1), crossed = setOf(0)), onTap = { taps += it }, onLongPress = { longs += it }, markMode = MarkMode.FILL)+ NonogramBoard(game = game(filled = setOf(1), crossed = setOf(0)), actions = a, markMode = MarkMode.FILL) } // Fill mode: double tap fills, double-tap-and-hold crosses (or removes an existing cross). cell(2, 2, R.string.cd_blank)@@ -83,11 +88,11 @@ class NonogramScreensTest { .assert(SemanticsMatcher("uncross label") { it.config[SemanticsActions.OnLongClick].label == str(R.string.action_uncross) }) // A settled cell offers nothing to do. cell(1, 2, R.string.cd_filled).assert(SemanticsMatcher.keyNotDefined(SemanticsActions.OnClick))- assertEquals(listOf(4), taps); assertEquals(listOf(4), longs)+ assertEquals(listOf(4), a.taps); assertEquals(listOf(4), a.crosses) } @Test fun talkBackActionsFollowCrossMode() {- rule.setContent { NonogramBoard(game = game(crossed = setOf(0)), onTap = {}, onLongPress = {}, markMode = MarkMode.CROSS) }+ rule.setContent { NonogramBoard(game = game(crossed = setOf(0)), actions = NonogramGameActions.Noop, markMode = MarkMode.CROSS) } cell(1, 1, R.string.cd_crossed) .assert(SemanticsMatcher("uncross on tap") { it.config[SemanticsActions.OnClick].label == str(R.string.action_uncross) }) .assert(SemanticsMatcher("fill on hold") { it.config[SemanticsActions.OnLongClick].label == str(R.string.action_fill) })@@ -164,33 +169,66 @@ class NonogramScreensTest { } @Test fun boardCellsReportDescriptionsAndTaps() {- val taps = mutableListOf<Int>()- rule.setContent { NonogramBoard(game = game(filled = setOf(1), crossed = setOf(0)), onTap = { taps += it }, onLongPress = {}) }+ val a = Recording()+ rule.setContent { NonogramBoard(game = game(filled = setOf(1), crossed = setOf(0)), actions = a) } cell(1, 2, R.string.cd_filled).assertExists() cell(1, 1, R.string.cd_crossed).assertExists() cell(1, 3, R.string.cd_blank).performClick()- assertEquals(listOf(2), taps)+ // A tap is a one-cell stroke in the current mode.+ assertEquals(listOf(listOf<Any>(2, false)), a.strokes)+ assertTrue(!a.openStroke)+ }++ @Test fun dragAcrossTheGridIsOneStroke() {+ val a = Recording()+ rule.setContent { NonogramBoard(game = game(), actions = a) }+ // From the middle of row 2, column 1 to column 3, all in one gesture.+ val first = rule.onNodeWithContentDescription(str(R.string.cd_cell_position, 2, 1)).fetchSemanticsNode().boundsInRoot+ val last = rule.onNodeWithContentDescription(str(R.string.cd_cell_position, 2, 3)).fetchSemanticsNode().boundsInRoot+ rule.onNodeWithContentDescription(str(R.string.cd_cell_position, 2, 1)).performTouchInput {+ down(center)+ moveBy(androidx.compose.ui.geometry.Offset(last.center.x - first.center.x, 0f), delayMillis = 50)+ up()+ }+ assertEquals(1, a.strokes.size, "one gesture, one stroke")+ assertEquals(listOf<Any>(3, false), a.strokes[0].take(2))+ assertEquals(5, a.strokes[0].last(), "the stroke reaches the cell under the finger")+ assertTrue(!a.openStroke)+ }++ @Test fun rtlGridMapsTouchesToMirroredColumns() {+ val a = Recording()+ rule.setContent {+ androidx.compose.runtime.CompositionLocalProvider(+ androidx.compose.ui.platform.LocalLayoutDirection provides androidx.compose.ui.unit.LayoutDirection.Rtl,+ ) { NonogramBoard(game = game(), actions = a) }+ }+ // Column 1 sits on the right under RTL; touching it must report column 1 (index 0).+ rule.onNodeWithContentDescription(str(R.string.cd_cell_position, 1, 1)).performClick()+ rule.onNodeWithContentDescription(str(R.string.cd_cell_position, 1, 3)).performClick()+ assertEquals(listOf(listOf<Any>(0, false), listOf<Any>(2, false)), a.strokes) } @Test fun boardTellsARevealedBlankApartFromANote() {- rule.setContent { NonogramBoard(game = game(crossed = setOf(0), revealed = setOf(2)), onTap = {}, onLongPress = {}) }+ rule.setContent { NonogramBoard(game = game(crossed = setOf(0), revealed = setOf(2)), actions = NonogramGameActions.Noop) } cell(1, 1, R.string.cd_crossed).assertExists() cell(1, 3, R.string.cd_revealed).assertExists() } - @Test fun boardLongPressFiresCross() {- val crosses = mutableListOf<Int>()- rule.setContent { NonogramBoard(game = game(), onTap = {}, onLongPress = { crosses += it }) }+ @Test fun boardLongPressStartsAnAlternateStroke() {+ val a = Recording()+ rule.setContent { NonogramBoard(game = game(), actions = a) } cell(2, 2, R.string.cd_blank) .performTouchInput { longClick() }- assertEquals(listOf(4), crosses)+ assertEquals(listOf(listOf<Any>(4, true)), a.strokes)+ assertTrue(!a.openStroke) } @Test fun boardWithEmptyLinesRendersZeroClues() { val p = com.vayunmathur.games.nonogram.data.NonogramPuzzle.from(4, listOf( true,true,false,false, false,false,false,false, false,false,true,false, false,false,false,true)) val g = NonogramGameState(p, emptySet(), emptySet(), emptySet(), STARTING_HEARTS, GameMode.CASUAL, 1)- rule.setContent { NonogramBoard(game = g, onTap = {}, onLongPress = {}) }+ rule.setContent { NonogramBoard(game = g, actions = NonogramGameActions.Noop) } cell(2, 1, R.string.cd_blank).assertExists() rule.onNodeWithText("0").assertExists() }@@ -198,7 +236,7 @@ class NonogramScreensTest { @Test fun boardLargeGeneratedPuzzleRenders() { val p = requireNotNull(com.vayunmathur.games.nonogram.domain.NonogramGenerator.generateSeeded(15, 99L)) val g = NonogramGameState(p, setOf(0), setOf(1), emptySet(), 2, GameMode.CASUAL, 25)- rule.setContent { NonogramBoard(game = g, onTap = {}, onLongPress = {}) }+ rule.setContent { NonogramBoard(game = g, actions = NonogramGameActions.Noop) } cell(15, 15, R.string.cd_blank).assertExists() } @@ -211,7 +249,7 @@ class NonogramScreensTest { androidx.compose.ui.platform.LocalDensity provides androidx.compose.ui.unit.Density(base.density, fontScale = 2f), ) { androidx.compose.foundation.layout.Box(androidx.compose.ui.Modifier.size(360.dp)) {- NonogramBoard(game = g, onTap = {}, onLongPress = {})+ NonogramBoard(game = g, actions = NonogramGameActions.Noop) } } }
games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometryTest.kt
diff --git a/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometryTest.kt b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometryTest.ktnew file mode 100644index 0000000000..735f6a0c81--- /dev/null+++ b/games/nonogram/src/test/java/com/vayunmathur/games/nonogram/ui/components/BoardGeometryTest.kt@@ -0,0 +1,26 @@+package com.vayunmathur.games.nonogram.ui.components++import kotlin.test.Test+import kotlin.test.assertEquals++class BoardGeometryTest {+ // 5x5 grid, 100px square: 20px cells.+ @Test fun ltrMapsPixelsToRowMajorCells() {+ assertEquals(0, BoardGeometry.cellAt(1f, 1f, 100f, 5, rtl = false))+ assertEquals(7, BoardGeometry.cellAt(45f, 30f, 100f, 5, rtl = false))+ assertEquals(24, BoardGeometry.cellAt(99f, 99f, 100f, 5, rtl = false))+ }++ @Test fun rtlMirrorsColumnsButNotRows() {+ // Physical left edge is the last column under RTL.+ assertEquals(4, BoardGeometry.cellAt(1f, 1f, 100f, 5, rtl = true))+ assertEquals(5, BoardGeometry.cellAt(99f, 21f, 100f, 5, rtl = true))+ assertEquals(12, BoardGeometry.cellAt(50f, 50f, 100f, 5, rtl = true))+ }++ @Test fun pointsOffTheGridClampToTheEdge() {+ assertEquals(0, BoardGeometry.cellAt(-30f, -5f, 100f, 5, rtl = false))+ assertEquals(24, BoardGeometry.cellAt(400f, 101f, 100f, 5, rtl = false))+ assertEquals(20, BoardGeometry.cellAt(400f, 101f, 100f, 5, rtl = true))+ }+}