In this article, we will create Rock, Paper, Scissors game using ReactJS. This project basically implements class components and manages the state accordingly. The player uses a particular option from Rock, Paper, or Scissors and then Computer chooses an option randomly. The logic of scoring and winning is implemented using JSX.
Let's have a look at what our final project will look like:
👁 Screenshot-(199)
Technologies Used/Pre-requisites: ReactJS CSS JSX Class Components in React Approach: Initialize your React project using Create React App. Create a Game component to handle the game logic and UI. Use the component’s state to keep track of player and computer choices, scores, and game results. Define the possible choices (Rock, Paper, Scissors) and their winning conditions. Implement a function to compare the player's choice with the computer’s choice and determine the winner. Update scores based on the game outcome. Create buttons for each choice (Rock, Paper, Scissors). Handle button clicks to set the player’s choice and initiate the game logic. Use React's state to manage player and computer choices, and scores. Update the state based on the results of the game. Project Structure: 👁 Image Steps to create Rock Paper Scissor Game using ReactJS 1. Set up React project using the command
npm create vite@latest <<name_of_project>> --template react 2. Navigate to the project folder using
cd <<Name_of_project>> 3. Create a folder "components" and add two new files in it namely Game.js and Game.css.
4. Import the icon pack using the following command in the index.html file of the public folder.
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css" /> Example: Write the following code in different files(The name of the files is mentioned in the first line of each code block)
index.html: This is an automatically created file in the public folder we just have to import the icon pack in its <head> tag. App.js: This file imports the game components and exports it. Game.js: This file contains the logic for the game, scoring techniques, and random function with which the computer chooses a value Game.css: This file contains the design of the game elements. Steps to run the application:
1. Type the following command in terminal.
npm run dev 2. Open web-browser and type the following URL
http://localhost:5173/ Output:
👁 a1-(2)