Rana Maninder Singh
Lesson 5 of 8Android App Development

Build a Number Guessing Game — Capstone

Lesson opener

In one line: Every file for a complete game - copy-paste runnable with Expo.

Why it matters: This shows up at work when you need to every file for a complete game - copy-paste runnable with Expo.

Before this lesson: android1 / android4

Before you start

ResourceLink
PreviousState & persistence
NextStyling for mobile
Prerequisitesandroid1–android4
Time~90 minutes
What you needExpo project from earlier lessons

Same codebase runs on iOS after ios1 — one React Native project, two stores.


What you will learn

  • Every file for a complete game — copy-paste runnable with Expo
  • Line-by-line comments on non-obvious logic
  • Expected UI for Home, Game, and Result screens
  • Stretch goals you can add after the core game works

Section 1 — Game spec

FeatureImplementation
Random target 1–100useState(randomTarget) once per round
Too high / low / correctConditional hint state
Attempt counterIncrement on each valid guess
Best score (fewest attempts)AsyncStorage via utils/storage.js
NavigationHome → Game → Result → Play again

Section 2 — Project structure

MyFirstApp/
  App.js                 ← navigation root
  utils/
    storage.js           ← read/write best score
  screens/
    HomeScreen.js        ← title + start + best score
    GameScreen.js        ← input + hints + submit
    ResultScreen.js      ← win message + save best + replay

Install dependencies (if not already):

npx expo install @react-navigation/native @react-navigation/native-stack
npx expo install react-native-screens react-native-safe-area-context
npx expo install @react-native-async-storage/async-storage

Section 3 — utils/storage.js (complete)

import AsyncStorage from '@react-native-async-storage/async-storage';

// Stable key — changing this loses saved data for existing users
const BEST_KEY = 'guess_game_best_attempts';

/**
 * Load best (lowest) attempt count, or null if never saved.
 * async/await required — AsyncStorage is never synchronous.
 */
export async function getBestAttempts() {
  const raw = await AsyncStorage.getItem(BEST_KEY);
  // raw is string | null — JSON.parse only when we have data
  return raw ? JSON.parse(raw) : null;
}

/**
 * Save if new score beats previous best (lower attempts = better).
 * Returns the best value after this save attempt.
 */
export async function saveBestAttempts(attempts) {
  const current = await getBestAttempts();
  // null current means first win ever — always save
  if (current === null || attempts < current) {
    await AsyncStorage.setItem(BEST_KEY, JSON.stringify(attempts));
    return attempts;
  }
  return current;
}

Section 4 — App.js (complete)

import { NavigationContainer } from '@react-navigation/native';
import { createNativeStackNavigator } from '@react-navigation/native-stack';
import HomeScreen from './screens/HomeScreen';
import GameScreen from './screens/GameScreen';
import ResultScreen from './screens/ResultScreen';

const Stack = createNativeStackNavigator();

export default function App() {
  return (
    // NavigationContainer required once at root — provides navigation context
    <NavigationContainer>
      <Stack.Navigator initialRouteName="Home">
        <Stack.Screen
          name="Home"
          component={HomeScreen}
          options={{ title: 'Guess Game' }}
        />
        <Stack.Screen
          name="Game"
          component={GameScreen}
          options={{ title: 'Playing' }}
        />
        <Stack.Screen
          name="Result"
          component={ResultScreen}
          options={{ title: 'You won!' }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

Section 5 — screens/HomeScreen.js (complete)

import { useState, useCallback } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
// useFocusEffect reloads best score whenever user returns to Home
import { useFocusEffect } from '@react-navigation/native';
import { getBestAttempts } from '../utils/storage';

export default function HomeScreen({ navigation }) {
  const [best, setBest] = useState(null);

  useFocusEffect(
    useCallback(() => {
      // Re-fetch after winning a round — Result screen may have updated storage
      getBestAttempts().then(setBest);
    }, [])
  );

  return (
    <View style={styles.container}>
      <Text style={styles.title}>Number Guessing Game</Text>
      <Text style={styles.sub}>
        I'm thinking of a number from 1 to 100.
      </Text>
      {best !== null && (
        <Text style={styles.best}>
          Best score: {best} attempt{best === 1 ? '' : 's'}
        </Text>
      )}
      <Button
        title="Start game"
        onPress={() => navigation.navigate('Game')}
      />
    </View>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    padding: 24,
  },
  title: { fontSize: 22, fontWeight: 'bold', marginBottom: 8 },
  sub: { fontSize: 16, color: '#64748b', marginBottom: 16 },
  best: { fontSize: 16, marginBottom: 24, color: '#1e3a5f' },
});

Expected UI — Home


Section 6 — screens/GameScreen.js (complete)

import { useState } from 'react';
import {
  View,
  Text,
  TextInput,
  Button,
  StyleSheet,
  Alert,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';

/** Returns random integer 1–100 inclusive */
function randomTarget() {
  return Math.floor(Math.random() * 100) + 1;
}

export default function GameScreen({ navigation }) {
  // Pass function ref to useState — runs once per mount, not every render
  const [target] = useState(randomTarget);
  const [guess, setGuess] = useState('');
  const [attempts, setAttempts] = useState(0);
  const [hint, setHint] = useState('Enter your guess');

  function checkGuess() {
    const n = parseInt(guess, 10);
    // Reject empty, decimal, or out-of-range before counting as attempt
    if (Number.isNaN(n) || n < 1 || n > 100) {
      Alert.alert('Invalid', 'Enter a whole number from 1 to 100');
      return;
    }

    const nextAttempts = attempts + 1;
    setAttempts(nextAttempts);

    if (n < target) {
      setHint('Too low — try higher');
    } else if (n > target) {
      setHint('Too high — try lower');
    } else {
      // replace (not navigate) so back button does not return to finished round
      navigation.replace('Result', { attempts: nextAttempts });
    }
  }

  return (
    <KeyboardAvoidingView
      style={styles.flex}
      behavior={Platform.OS === 'ios' ? 'padding' : undefined}
    >
      <View style={styles.container}>
        <Text style={styles.hint}>{hint}</Text>
        <Text style={styles.attempts}>Attempts: {attempts}</Text>
        <TextInput
          style={styles.input}
          keyboardType="number-pad"
          value={guess}
          onChangeText={setGuess}
          placeholder="1–100"
          maxLength={3}
        />
        <Button title="Submit guess" onPress={checkGuess} />
      </View>
    </KeyboardAvoidingView>
  );
}

const styles = StyleSheet.create({
  flex: { flex: 1 },
  container: { flex: 1, padding: 24, justifyContent: 'center' },
  hint: { fontSize: 20, fontWeight: '600', marginBottom: 8 },
  attempts: { fontSize: 16, color: '#64748b', marginBottom: 16 },
  input: {
    borderWidth: 1,
    borderColor: '#cbd5e1',
    borderRadius: 8,
    padding: 12,
    fontSize: 18,
    marginBottom: 16,
  },
});

Expected UI — Game


Section 7 — screens/ResultScreen.js (complete)

import { useEffect, useState } from 'react';
import { View, Text, Button, StyleSheet } from 'react-native';
import { saveBestAttempts } from '../utils/storage';

export default function ResultScreen({ route, navigation }) {
  const { attempts } = route.params;
  const [best, setBest] = useState(attempts);

  useEffect(() => {
    // Persist on mount — user may force-quit app; save immediately on win
    saveBestAttempts(attempts).then(setBest);
  }, [attempts]);

  return (
    <View style={styles.container}>
      <Text style={styles.win}>Correct!</Text>
      <Text style={styles.line}>
        You guessed it in {attempts} attempt{attempts === 1 ? '' : 's'}.
      </Text>
      <Text style={styles.line}>
        Best score: {best} attempt{best === 1 ? '' : 's'}
      </Text>
      <View style={styles.gap} />
      <Button
        title="Play again"
        onPress={() => navigation.replace('Game')}
      />
      <Button title="Home" onPress={() => navigation.navigate('Home')} />
    </View>
  );
}

const styles = StyleSheet.create({
  container: { flex: 1, justifyContent: 'center', padding: 24 },
  win: {
    fontSize: 28,
    fontWeight: 'bold',
    color: '#16a34a',
    marginBottom: 12,
  },
  line: { fontSize: 16, marginBottom: 8 },
  gap: { height: 16 },
});

Expected UI — Result


Section 8 — Run and verify

npx expo start
  1. Start game → enter guesses → win
  2. Force-close Expo Go → reopen → Best score still on Home
  3. Press Android back from Game → returns to Home (stack pop)

Section 9 — Stretch goals (optional)

Try these after the core game works:

1. Timer (bonus for speed)

2. Difficulty levels

3. Leaderboard (top 3 scores)


Checklist

  • [ ] All five files match your project
  • [ ] Game runs on device via Expo Go
  • [ ] Best score survives app restart
  • [ ] Invalid input shows Alert, not a counted attempt
  • [ ] Back button behaviour feels correct

What's next

Styling for mobile — safe areas, dark mode, and platform-specific polish.