Create a Rock Paper Scissors Game using React-Native
Last Updated :
23 May, 2025
Rock, Paper, Scissors is a timeless game that has entertained people of all ages for generations. In this article, we will walk you through the process of creating a Rock Paper Scissors mobile game using React Native. You'll learn how to build a simple yet engaging game that can be played on both Android and iOS devices.
To give you a better idea of what we’re going to create, let’s watch a demo video.
Demo Video
Playground
Note: This Section is to interact with the app which you are going to build.
Step-by-Step Implementation
Step 1: Create a React Native Project
Now, create a project with the following command.
npx create-expo-app app-name --template
Note: Replace the app-name with your app name for example : react-native-demo-app
Next, you might be asked to choose a template. Select one based on your preference as shown in the image below. I am selecting the blank template because it will generate a minimal app that is as clean as an empty canvas in JavaScript.
It completes the project creation and displays a message: "Your Project is ready!" as shown in the image below.
Now go into your project folder, i.e., react-native-demo
cd app-name
Project Structure:
Step 2: Run Application
Start the server by using the following command.
npx expo start
Then, the application will display a QR code.
- For the Android users,
- For the Android Emulator, press " a" as mentioned in the image below.
- For the Physical Device, download the " Expo Go " app from the Play Store. Open the app, and you will see a button labeled " Scan QR Code. " Click that button and scan the QR code; it will automatically build the Android app on your device.
- For iOS users, simply scan the QR code using the Camera app .
- If you're using a web browser, it will provide a local host link that you can use as mentioned in the image below.
Step 3: Start Coding
Approach / Functionalities:
- Create a UI with buttons for Rock, Paper, and Scissors.
- Create state variables to store playerValue, computerValue, playerScore, and computerScore.
- Attach event handlers to the button Rock, Paper, Scissors to manipulate states.
- Implement a decision function to generate computerValue.
- Implement game logic to determine the winner (player or computer).
- Display the user's choice and the computer's choice.
- Keep track of the user's score and the computer's score.
Let's dive into the code in detail.
- Import libraries: Import required libraries at the top of the file.
JavaScript
// Import useState hook from React for state management
import { useState } from "react";
// Import necessary components from react-native
// Import core components from react-native for building UI
import {
View, // Container component for layout
Text, // Component for displaying text
TouchableOpacity, // Button component for touch interactions
StyleSheet // Utility for creating styles
} from "react-native";
- StyleSheet: Create a StyleSheet to style components like container, title, buttonContainer, etc.
JavaScript
// Styles for the components
const styles = StyleSheet.create({
container: {
flex: 1, // Take full height
justifyContent: "center", // Center vertically
alignItems: "center", // Center horizontally
backgroundColor: "#333", // Dark background
color: "#fff", // Text color
},
title: {
fontSize: 28, // Large font size
marginBottom: 20, // Space below title
color: "#4caf50", // Green color
fontWeight: "bold", // Bold text
textTransform: "uppercase", // Uppercase letters
},
buttonContainer: {
flexDirection: "row", // Arrange buttons in a row
justifyContent: "space-between", // Space between buttons
marginVertical: 20, // Vertical margin
},
button: {
backgroundColor: "#4caf50", // Green background
paddingVertical: 12, // Vertical padding
paddingHorizontal: 20, // Horizontal padding
borderRadius: 8, // Rounded corners
marginHorizontal: 10, // Space between buttons
},
buttonText: {
color: "#fff", // White text
fontSize: 18, // Medium font size
fontWeight: "bold", // Bold text
},
scoreContainer: {
marginTop: 20, // Space above scores
alignItems: "center", // Center align
},
scoreText: {
color: "#fff", // White text
fontSize: 16, // Font size
marginBottom: 10, // Space below each score
textAlign: "center", // Centered text
},
});
- Title Text:
This title explains what the app does. We use the text "Rock, Paper, Scissors Game" to show that the app is to play the Rock, Paper, Scissors Game.
JavaScript
{/* Game title */}
<Text style={styles.title}>
Rock, Paper, Scissors Game
</Text>
After the title, we have three buttons: Rock, Paper, and Scissors. Each button is created by wrapping a Text component with the words "Rock," "Paper," and "Scissors" with respect to buttons. These are then placed inside a TouchableOpacity component so that the user can click on them. All three buttons are held together in a View component. When the user taps on any button, we call a function called "decision," which contains the game logic.
JavaScript
{/* Buttons for player to choose */}
<View style={styles.buttonContainer}>
// Rock Button
<TouchableOpacity
style={styles.button}
onPress={() => decision("ROCK")} // Player chooses ROCK
>
<Text style={styles.buttonText}>
Rock
</Text>
</TouchableOpacity>
// Paper Button
<TouchableOpacity
style={styles.button}
onPress={() => decision("PAPER")} // Player chooses PAPER
>
<Text style={styles.buttonText}>
Paper
</Text>
</TouchableOpacity>
// Scissors Button
<TouchableOpacity
style={styles.button}
onPress={() => decision("SCISSORS")} // Player chooses SCISSORS
>
<Text style={styles.buttonText}>
Scissors
</Text>
</TouchableOpacity>
</View>
- decision function: This function starts by randomly picking a choice from a list of options for the computer using Math.random and Math.floor. It then sends the player's choice and the computer's choice to logic function.
-The logic function: checks who won by looking at certain conditions in the code. It returns 0 if there's a tie, 1 if the player wins, and -1 if the computer wins.
After that, the state variable is updated based on what the logic function returns.
JavaScript
// State to store player's current choice
const [playerVal, setPlayerVal] = useState(null);
// State to store computer's current choice
const [computerVal, setComputerVal] = useState(null);
// State to store player's score
const [playerScore, setPlayerScore] = useState(0);
// State to store computer's score
const [compScore, setCompScore] = useState(0);
// Function to determine the winner
const logic = (playerVal, computerVal) => {
// If both choices are the same, it's a draw
if (playerVal === computerVal) {
return 0;
// Player wins conditions
} else if (
(playerVal === "ROCK" && computerVal === "SCISSORS") ||
(playerVal === "SCISSORS" && computerVal === "PAPER") ||
(playerVal === "PAPER" && computerVal === "ROCK")
) {
return 1; // Player wins
} else {
return -1; // Computer wins
}
};
// Function to handle player's choice and update state
const decision = (playerChoice) => {
// Array of possible choices
const choices = ["ROCK", "PAPER", "SCISSORS"];
// Randomly select computer's choice
const compChoice =
choices[Math.floor(Math.random() * choices.length)];
// Determine the result using logic function
const val = logic(playerChoice, compChoice);
// If player wins
if (val === 1) {
setPlayerVal(playerChoice); // Update player's choice
setComputerVal(compChoice); // Update computer's choice
setPlayerScore(playerScore + 1); // Increment player's score
// If computer wins
} else if (val === -1) {
setPlayerVal(playerChoice); // Update player's choice
setComputerVal(compChoice); // Update computer's choice
setCompScore(compScore + 1); // Increment computer's score
// If it's a draw
} else {
setComputerVal(compChoice); // Update computer's choice
setPlayerVal(playerChoice); // Update player's choice
}
};
- Display choices and scores:
After that, display choices and scores of player and computer using below code.
JavaScript
{/* Display choices and scores */}
<View style={styles.scoreContainer}>
<Text style={styles.scoreText}>
Your choice: {playerVal}
</Text>
<Text style={styles.scoreText}>
Computer's choice: {computerVal}
</Text>
<Text style={styles.scoreText}>
Your Score: {playerScore}
</Text>
<Text style={styles.scoreText}>
Computer Score: {compScore}
</Text>
</View>
Now, wrap all design code with a View component, return it from the App component, and place all methods and useStates within the App component. Ensure to export the App.
Complete Source Code
App.js:
App.js
// Import useState hook from React for state management
import { useState } from "react";
// Import necessary components from react-native
// Import core components from react-native for building UI
import {
View, // Container component for layout
Text, // Component for displaying text
TouchableOpacity, // Button component for touch interactions
StyleSheet // Utility for creating styles
} from "react-native";
// Main App component
const App = () => {
// State to store player's current choice
const [playerVal, setPlayerVal] = useState(null);
// State to store computer's current choice
const [computerVal, setComputerVal] = useState(null);
// State to store player's score
const [playerScore, setPlayerScore] = useState(0);
// State to store computer's score
const [compScore, setCompScore] = useState(0);
// Function to determine the winner
const logic = (playerVal, computerVal) => {
// If both choices are the same, it's a draw
if (playerVal === computerVal) {
return 0;
// Player wins conditions
} else if (
(playerVal === "ROCK" && computerVal === "SCISSORS") ||
(playerVal === "SCISSORS" && computerVal === "PAPER") ||
(playerVal === "PAPER" && computerVal === "ROCK")
) {
return 1; // Player wins
} else {
return -1; // Computer wins
}
};
// Function to handle player's choice and update state
const decision = (playerChoice) => {
// Array of possible choices
const choices = ["ROCK", "PAPER", "SCISSORS"];
// Randomly select computer's choice
const compChoice =
choices[Math.floor(Math.random() * choices.length)];
// Determine the result using logic function
const val = logic(playerChoice, compChoice);
// If player wins
if (val === 1) {
setPlayerVal(playerChoice); // Update player's choice
setComputerVal(compChoice); // Update computer's choice
setPlayerScore(playerScore + 1); // Increment player's score
// If computer wins
} else if (val === -1) {
setPlayerVal(playerChoice); // Update player's choice
setComputerVal(compChoice); // Update computer's choice
setCompScore(compScore + 1); // Increment computer's score
// If it's a draw
} else {
setComputerVal(compChoice); // Update computer's choice
setPlayerVal(playerChoice); // Update player's choice
}
};
// Render UI
return (
<View style={styles.container}>
{/* Game title */}
<Text style={styles.title}>
Rock, Paper, Scissors Game
</Text>
{/* Buttons for player to choose */}
<View style={styles.buttonContainer}>
<TouchableOpacity
style={styles.button}
onPress={() => decision("ROCK")} // Player chooses ROCK
>
<Text style={styles.buttonText}>
Rock
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => decision("PAPER")} // Player chooses PAPER
>
<Text style={styles.buttonText}>
Paper
</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
onPress={() => decision("SCISSORS")} // Player chooses SCISSORS
>
<Text style={styles.buttonText}>
Scissors
</Text>
</TouchableOpacity>
</View>
{/* Display choices and scores */}
<View style={styles.scoreContainer}>
<Text style={styles.scoreText}>
Your choice: {playerVal}
</Text>
<Text style={styles.scoreText}>
Computer's choice: {computerVal}
</Text>
<Text style={styles.scoreText}>
Your Score: {playerScore}
</Text>
<Text style={styles.scoreText}>
Computer Score: {compScore}
</Text>
</View>
</View>
);
};
// Styles for the components
const styles = StyleSheet.create({
container: {
flex: 1, // Take full height
justifyContent: "center", // Center vertically
alignItems: "center", // Center horizontally
backgroundColor: "#333", // Dark background
color: "#fff", // Text color
},
title: {
fontSize: 28, // Large font size
marginBottom: 20, // Space below title
color: "#4caf50", // Green color
fontWeight: "bold", // Bold text
textTransform: "uppercase", // Uppercase letters
},
buttonContainer: {
flexDirection: "row", // Arrange buttons in a row
justifyContent: "space-between", // Space between buttons
marginVertical: 20, // Vertical margin
},
button: {
backgroundColor: "#4caf50", // Green background
paddingVertical: 12, // Vertical padding
paddingHorizontal: 20, // Horizontal padding
borderRadius: 8, // Rounded corners
marginHorizontal: 10, // Space between buttons
},
buttonText: {
color: "#fff", // White text
fontSize: 18, // Medium font size
fontWeight: "bold", // Bold text
},
scoreContainer: {
marginTop: 20, // Space above scores
alignItems: "center", // Center align
},
scoreText: {
color: "#fff", // White text
fontSize: 16, // Font size
marginBottom: 10, // Space below each score
textAlign: "center", // Centered text
},
});
// Export the App component as default
export default App;
Output:
Similar Reads
React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version
7 min read
React Fundamentals
React IntroductionReactJS is a component-based JavaScript library used to build dynamic and interactive user interfaces. It simplifies the creation of single-page applications (SPAs) with a focus on performance and maintainability.React.jsWhy Use React?Before React, web development faced issues like slow DOM updates
7 min read
React Environment SetupTo run any React application, we need to first setup a ReactJS Development Environment. In this article, we will show you a step-by-step guide to installing and configuring a working React development environment.Pre-requisite:We must have Nodejs installed on our PC. So, the very first step will be
3 min read
React JS ReactDOMReactDom is a core react package that provides methods to interact with the Document Object Model or DOM. This package allows developers to access and modify the DOM. Let's see in brief what is the need to have the package. Table of ContentWhat is ReactDOM ?How to use ReactDOM ?Why ReactDOM is used
3 min read
React JSXJSX stands for JavaScript XML, and it is a special syntax used in React to simplify building user interfaces. JSX allows you to write HTML-like code directly inside JavaScript, enabling you to create UI components more efficiently. Although JSX looks like regular HTML, itâs actually a syntax extensi
5 min read
ReactJS Rendering ElementsIn this article we will learn about rendering elements in ReactJS, updating the rendered elements and will also discuss about how efficiently the elements are rendered.What are React Elements?React elements are the smallest building blocks of a React application. They are different from DOM elements
3 min read
React ListsReact Lists are used to display a collection of similar data items like an array of objects and menu items. It allows us to dynamically render the array elements and display repetitive data.Rendering List in ReactTo render a list in React, we will use the JavaScript array map() function. We will ite
5 min read
React FormsForms are an essential part of any application used for collecting user data, processing payments, or handling authentication. React Forms are the components used to collect and manage the user inputs. These components include the input elements like text field, check box, date input, dropdowns etc.
5 min read
ReactJS KeysA key serves as a unique identifier in React, helping to track which items in a list have changed, been updated, or removed. It is particularly useful when dynamically creating components or when users modify the list. In this article, we'll explore ReactJS keys, understand their importance, how the
5 min read
Components in React
React ComponentsIn React, React components are independent, reusable building blocks in a React application that define what gets displayed on the UI. They accept inputs called props and return React elements describing the UI.In this article, we will explore the basics of React components, props, state, and render
4 min read
ReactJS Functional ComponentsIn ReactJS, functional components are a core part of building user interfaces. They are simple, lightweight, and powerful tools for rendering UI and handling logic. Functional components can accept props as input and return JSX that describes what the component should render.What are Reactjs Functio
5 min read
React Class ComponentsClass components are ES6 classes that extend React.Component. They allow state management and lifecycle methods for complex UI logic.Used for stateful components before Hooks.Support lifecycle methods for mounting, updating, and unmounting.The render() method in React class components returns JSX el
4 min read
ReactJS Pure ComponentsReactJS Pure Components are similar to regular class components but with a key optimization. They skip re-renders when the props and state remain the same. While class components are still supported in React, it's generally recommended to use functional components with hooks in new code for better p
4 min read
ReactJS Container and Presentational Pattern in ComponentsIn this article we will categorise the react components in two types depending on the pattern in which they are written in application and will learn briefly about these two categories. We will also discuss about alternatives to this pattern. Presentational and Container ComponentsThe type of compon
2 min read
ReactJS PropTypesIn ReactJS PropTypes are the property that is mainly shared between the parent components to the child components. It is used to solve the type validation problem. Since in the latest version of the React 19, PropeTypes has been removed. What is ReactJS PropTypes?PropTypes is a tool in React that he
5 min read
React Lifecycle In React, the lifecycle refers to the various stages a component goes through. These stages allow developers to run specific code at key moments, such as when the component is created, updated, or removed. By understanding the React lifecycle, you can better manage resources, side effects, and perfo
7 min read
React Hooks
Routing in React
Advanced React Concepts
React Projects