Chuyển đến nội dung

Bài 99 · Projects

Project: Mini Games (Tic-Tac-Toe, Guess the Number, Reflex, Spin the Bottle, Magic 8 Ball)

Build five small Android games with Compose: tic-tac-toe with a computer opponent, guess the number, a reflex tester, spin the bottle and a magic 8 ball, with the game logic tested in runnable Kotlin.

Small games are an excellent way to practice Android: they have a clear state, clear rules and instant feedback. Five classic ones also cover most of the skills of a first real app: a grid of buttons, input and validation, timing, animation and randomness. This project builds all five the same way.

Rule one: separate the game from the screen. Each game's rules live in a plain Kotlin class that knows nothing about Android. A ViewModel owns that class and exposes state, and a composable draws the state (UI state and events). That separation is what lets you test the rules without a device, and it is why this lesson's TryIts can run the real game logic on this site. The Compose screens are shown read-only because they need the Android toolchain. If you prefer XML screens, the logic is identical and only the view code changes (XML layouts).

flowchart LR
    U["Tap / input"] --> V["Composable<br/>draws state"]
    V -->|"event"| VM["ViewModel<br/>holds UiState"]
    VM --> G["Game class<br/>(pure Kotlin rules)"]
    G --> VM
    VM -->|"StateFlow"| V

Screens send events, the ViewModel asks the game class, and the new state flows back.

Game 1: Tic-tac-toe with a computer opponent

The rules

The board is nine cells. Players alternate X and O. A player wins with three in a row, column or diagonal. If the board is full with no winner, it is a draw. The winning lines are data, not code:

Kotlin Tic-tac-toe: rules and an unbeatable computer

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Notice the choices: the board is immutable (play returns a new board), which makes states easy to compare and the ViewModel trivially correct, and minimax tries every continuation, which is cheap on a 3x3 board. A harder game would need pruning or a heuristic.

The screen

Kotlin
// read-only example: the Compose board
@Composable
fun BoardScreen(vm: TicTacToeViewModel = viewModel()) {
    val state by vm.state.collectAsStateWithLifecycle()
    Column(horizontalAlignment = Alignment.CenterHorizontally, modifier = Modifier.padding(24.dp)) {
        Text(state.message, style = MaterialTheme.typography.headlineSmall)
        LazyVerticalGrid(columns = GridCells.Fixed(3), modifier = Modifier.size(300.dp)) {
            itemsIndexed(state.cells) { index, mark ->
                OutlinedButton(
                    onClick = { vm.onCellClick(index) },
                    enabled = mark == null && !state.over,
                    modifier = Modifier.aspectRatio(1f).padding(4.dp)
                ) { Text(mark?.name ?: "", fontSize = 32.sp) }
            }
        }
        Button(onClick = vm::reset) { Text("New game") }
    }
}

The ViewModel keeps state as a StateFlow, calls the game class on every tap and, after the human moves, asks bestMove for the computer (optionally after a short delay so it feels natural).

Game 2: Guess the number

The computer picks a secret number; the player guesses; the app answers "higher", "lower" or "correct" and counts attempts. Good practice for input validation: the text field gives a String, which may be empty, not a number or out of range.

Kotlin Guess the number: validation and hints

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In the app, kotlin.random.Random.nextInt(1, 101) creates the secret once and the ViewModel keeps it, so a screen rotation does not start a new game. Show the hint in a Text, validate with isError on the OutlinedTextField, and use KeyboardOptions(keyboardType = KeyboardType.Number).

Game 3: Reflex tester

The screen is red; after a random delay it turns green; the player taps as fast as possible; the app shows the reaction time. Tapping while it is still red is a false start. The interesting part is that it is a state machine driven by time:

Kotlin Reflex game state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

In the app, the screen's background color comes from the phase (Waiting red, Go green) and a coroutine does the real waiting: delay(Random.nextLong(1500, 4000)), then sets the phase to Go and records SystemClock.elapsedRealtime(). Use a monotonic clock for the reaction time, as in Timers and sensors.

Game 4: Spin the bottle

The bottle is an image that rotates by a random angle and slows down. The logic is one formula: pick a target angle, animate to it with a DecelerateInterpolator, and read which direction the bottle points (the angle modulo 360).

Kotlin
// read-only example: Compose animation of a random spin
@Composable
fun BottleScreen() {
    var target by remember { mutableFloatStateOf(0f) }
    val angle by animateFloatAsState(
        targetValue = target,
        animationSpec = tween(durationMillis = 2500, easing = FastOutSlowInEasing),
        label = "bottle"
    )
    Column(horizontalAlignment = Alignment.CenterHorizontally) {
        Image(
            painter = painterResource(R.drawable.bottle),
            contentDescription = "Bottle",
            modifier = Modifier.size(240.dp).rotate(angle)
        )
        Button(onClick = { target += 720f + Random.nextInt(360) }) { Text("Spin") }
    }
}

The same effect in a View-based app uses ObjectAnimator.ofFloat(bottle, "rotation", from, to) with a DecelerateInterpolator (Lottie, shimmer and motion). One detail: always start from the current rotation, otherwise the bottle jumps back to 0 on every spin. That is why target accumulates.

Game 5: Magic 8 ball

The player asks a yes/no question, shakes the phone (or taps a button) and gets a random answer. The logic is a list of answers and a random pick; the fun parts are shake detection (Timers, clocks, sensors and speech) and avoiding the same answer twice in a row, which feels broken.

Kotlin Magic 8 ball and spin angle logic

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The seed in Random(7) makes the test repeatable; in the app you use the default Random. Seeding is also how you write a unit test for any random feature.

Wiring it together

A simple launcher screen with a list of games uses Navigation Compose: one destination per game, one ViewModel per destination. Share the pattern, not the code: each game class is plain Kotlin, each ViewModel exposes one StateFlow<UiState>, and each screen is a function of that state. Add a best-score store with DataStore and sounds from res/raw (Resources).

Common mistakes

  • Putting game rules inside the Activity or composable, where they cannot be tested.
  • Creating the secret number inside the composable: it changes on every recomposition. Keep it in the ViewModel.
  • Counting reaction time with System.currentTimeMillis(), which can jump when the user's clock changes.
  • Letting the computer move while the human's tap handler is still running, or accepting taps during the computer's turn.
  • Forgetting a "New game" reset path.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. Why keep the game rules in a plain Kotlin class?

    Rules with no Android dependency are fast to test and independent of the UI toolkit.
  2. 2. How many winning lines does tic-tac-toe have on a 3x3 board?

    Three rows, three columns and two diagonals make eight.
  3. 3. Why is the secret number kept in the ViewModel?

    State in a composable without remember is recreated every recomposition, and an Activity's fields are lost on rotation. The ViewModel survives both.
  4. 4. What does a false start in the reflex game mean in the state machine?

    Tapping before the screen turns green moves the machine to FalseStart instead of measuring a reaction time.

Summary

  • Keep rules in pure Kotlin, state in a ViewModel and drawing in composables.
  • Tic-tac-toe: eight winning lines as data, immutable boards and minimax for the computer.
  • Guess the number: validate text input, keep the secret in the ViewModel, count only valid guesses.
  • Reflex: a time-driven state machine with a monotonic clock.
  • Spin the bottle and the magic 8 ball: random targets with decelerating animation, and a no-repeat random pick.

Next: Project: utility apps.

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.