Create a Number Guessing App using React-Native
The Number Guessing App is a simple mobile game where the user tries to guess a random number generated by the app. The app provides feedback to the user, indicating whether their guess is too high or too low, and keeps track of the number of attempts it takes to guess the correct number. In this article, we will learn how to create a Number Guessing Game using React Native.
Preview Image:
Prerequisites
- Node.js and npm (Node Package Manager)
- React Native
- Expo CLI (for development)
- JavaScript/ES6
- Android or iOS emulator or a physical device for testing
Steps to install & configure React Native:
Step 1: Create a react native application by using this command:
npx create-expo-app basicNotes-app
Step 2: After creating your project folder, i.e. basicNotes-app, use the following command to navigate to it:
cd basicNotes-app
Step 3: Create the game logic
Implement the game logic in App.js.
Project structure:
Your project structure might look like this:
Approach
- Generate a random number between a specified range (e.g., 1 to 20).
- Allow the user to input their guess.
- Provide feedback on whether the guess is too high, too low, or correct.
- Display a congratulatory message when the user guesses the correct number along with total attempts made.
Example: This example shows the above-explained approach.
Javascript
// App.js import React, { useState, useEffect } from "react" ; import { View, Text, TextInput, TouchableOpacity, StyleSheet, } from "react-native" ; const App = () => { const [term, setTerm] = useState( "" ); const [result, setResult] = useState( "" ); const [secretNum] = useState(generateRandomNumber()); const [stepCount, setStepCount] = useState(0); useEffect(() => { // Reset step count when the secret // number changes. setStepCount(0); }, [secretNum]); function generateRandomNumber() { return Math.floor(Math.random() * 20) + 1; } function handleChange(text) { setTerm(text); } function checkGuess() { let newResult = "" ; if (term === "" ) { newResult = "Enter Valid Input" ; } else if ( isNaN(term) || parseInt(term) < 1 || parseInt(term) > 20 ) { newResult = "Enter a valid number between 1 and 20" ; } else { setStepCount(stepCount + 1); if (parseInt(term) < secretNum) { newResult = "Lower" ; } else if (parseInt(term) > secretNum) { newResult = "Higher" ; } else { newResult = `Yippee, correct! It took you ${ stepCount + 1 } ${stepCount === 1 ? "step" : "steps" }.`; } } setResult(newResult); } return ( <View style={styles.container}> <Text style={styles.head}> Guess Number between 1 to 20 </Text> <TextInput style={styles.input} placeholder= "Enter your guess" onChangeText={handleChange} value={term} keyboardType= "numeric" /> <TouchableOpacity style={styles.button} onPress={checkGuess} > <Text style={styles.buttonText}>Check</Text> </TouchableOpacity> <Text style={styles.result}> You Guessed: {result} </Text> </View> ); }; // ... Rest of your code remains unchanged const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center" , justifyContent: "center" , backgroundColor: "#f2f2f2" , padding: 16, }, head: { fontWeight: "bold" , fontSize: 24, marginBottom: 20, color: "#333" , }, input: { padding: 10, borderWidth: 1, borderColor: "#ccc" , borderRadius: 10, width: "80%" , marginBottom: 20, backgroundColor: "#fff" , fontSize: 18, }, button: { backgroundColor: "#007BFF" , borderRadius: 10, paddingVertical: 12, paddingHorizontal: 24, }, buttonText: { color: "#fff" , fontSize: 18, fontWeight: "bold" , }, result: { marginTop: 20, fontSize: 18, color: "#333" , fontWeight: "bold" , }, }); export default App; |
Steps to run the application:
Run your React Native app using Expo CLI:
npx expo start
This will open a Metro Bundler page in your web browser. You can then choose to run the app on an Android/iOS emulator or scan the QR code with the Expo Go app on your physical device.
To run on Android:
npx react-native run-android
To run on iOS:
npx react-native run-ios
Output:
Your Number Guessing App is now ready for users to enjoy! You can expand on this basic example by adding more features and enhancing the user interface.