Building a rock 🧱, paper 📰 ,scissor ✂️, lizard 🦎 and spock 🖖 game in react
Tags: javascript, webdev, beginners, react
Published: 2021-11-06 12:09:07

In this blog tutorial, we are going to set up and build a rock, paper, scissor, lizard and spock game using react.js from absolutely scratch. If you want to learn more about react, there is a specific article for you.

[https://dev.to/aviyel/building-a-react-application-from-absolute-scratch](https://dev.to/aviyel/building-a-react-application-from-absolute-scratch-1684)

We will be creating the UI and its functionalities from the ground up. However, before we begin, the final version of the app should resemble this.

![demo](https://aviyel.com/assets/uploads/files/1634784785676-image-resized.png)

You can also view the application's final live version.

[rock-paper-scissor-spock-game.netlify.app](https://rock-paper-scissor-spock-game.netlify.app)

## Installing react application
Let us begin with our first react application. So, if Node.js isn't already installed on your system, the first thing you should do is install it. So, go to the official Node.js website and install the correct and appropriate version. We need node js so that we can use the node package manager, also known as NPM.

![Make a directory](https://aviyel.com/assets/uploads/files/1634789103911-image.png)

Now, create a blank folder and open it inside the code editor of your choice. For this tutorial, I will be using VScode. Next step, let’s open the integrated terminal and type ***npx create-react-app music-payer-react-app*** this command will create the app inside the current directory and that application will be named as ***rock-paper-scissor***

![npx script](https://aviyel.com/assets/uploads/files/1634753880195-image-resized.png)

![create react app](https://aviyel.com/assets/uploads/files/1634789172809-image-resized.png)

It usually takes only a few minutes to install. Normally, we would use npm to download packages into the project, but in this case, we are using npx, the package runner, which will download and configure everything for us so that we can start with an amazing template. It's now time to start our development server, so simply type ***npm start***, and the browser will automatically open react-app.

![react application](https://aviyel.com/assets/uploads/files/1634549140771-image.png)

So, the boilerplate template appears right away. It's now time to look into the file and folder structure provided by create-react-app. All of our node dependencies are stored in a folder called node module. Then there's the public folder, where the index.html file is the only thing that matters. So far, it appears that this is a standard HTML file, complete with head, body, and meta tags. Inside our body tag, you'll notice a div with the id root, followed by the fallback noscript tag, which will be visible only if the user's browser has javascript disabled.

![index html](https://aviyel.com/assets/uploads/files/1634791488934-image.png)

![root](https://aviyel.com/assets/uploads/files/1634789293126-image.png)

So you're probably wondering where the content comes from. Remember that, All of our source code is contained within our source or src folder, and react will inject it into the root div element. Let's take a look at our src folder, which contains some stylesheets, javascript files, and SVG files.

![Folder structure](https://aviyel.com/assets/uploads/files/1634792038962-image.png)

Now, head over to our ***App.js*** file

![App js boilerplate](https://aviyel.com/assets/uploads/files/1634789643775-image.png)

In this case, we're simply using standard javascript to import react from react and logo from our logo. Following that, we have a normal javascript function called APP, and this function in react is known as a functional component, and this function is returning a react-element that looks like HTML but is actually an jsx as you can see there is a div tag with a className of APP, and we can't say class by itself because the class is a reserved word in javascript, so we have to use className in jsx. Following that, we have the header and then the image, and notice on the image source that we have our logo, which is actually a javascript variable that we imported at the top, so in order to use the javascript within JSX, we must surround it with curly brackets, and then we have a paragraph, an anchor tag, and that is all for this component.

> **NOTE**: Because of the export, we are able to extract the component and place it on the webpage. Export appears at the bottom of the app.js file, indicating that we are exporting the App function.

So, Now let's look at the ***index.js*** file.

![index js boilerplate](https://aviyel.com/assets/uploads/files/1634789693371-image.png)

So, in this case, we're importing react from react again, and this time we're also importing react-dom, and then we're importing the CSS stylesheet file, and finally, we're importing App from App.js, which is the file we just talked about, and there's service worker, which is used to make your application work completely offline. Then we call ReactDom.render, which takes two arguments. The first parameter is the jsx object, and within jsx we can include our user-defined components, so react strict mode is a react defined component, whereas App is a user-defined component. The second parameter is  ****documented.getElementById('root')****, which targets the root div in our index.html file and is how we access the content in our webpage.

> Note: ReactDom renders our content into our root div located at our index.html file.

---

## Creating a rock 🧱, paper 📰 ,scissor ✂️, lizard 🦎 and spock🖖 game. 

Let's build a simple rock, paper, scissor, lizard and Spock app in react from the ground up, but first let's make a prototype or mindmap of our final application. So, our final app will look something like this.

![Prototype](https://aviyel.com/assets/uploads/files/1634756044459-image-resized.png)

Before we begin building our projects, we must first clean them up by removing some of the files provided by create-react-app. Your src files should look like this after you've cleaned them up.

![Folder structure](https://aviyel.com/assets/uploads/files/1634792178499-image1.png)

Now, within the ***src*** folder, make another folder called ***components***, and within that components folder, add the file name called ***Game.js***

![Folder structure](https://aviyel.com/assets/uploads/files/1634792300702-image-1.png)

Now, go to your Game.js file and create a ***useState()*** because this hook will enable us to integrate the state into our functional component. ***useState()***, unlike state in class components, does not work with object values. If necessary, we can use primitives directly and create multiple react hooks for multiple variables. ***const [state, setState] = useState(initialState);*** . Hooks in React must always be declared at the top of a function. This also aids in the preservation of state between all rendering for the component.


### React Hook: useState()

![useState hook](https://aviyel.com/assets/uploads/files/1634792562185-image.png)

Now create three state ***computerSelection*** , ***userSelection*** and ***finalOutput*** and initialize all with null value.

![states](https://aviyel.com/assets/uploads/files/1634761975812-image.png)

Copy and paste the code below into your ***Game.js*** file.

```javascript
// Game.js

import {useState,useEffect} from "react";

const Game = () => {
  const [computerSelection, setComputerSelection] = useState(null);
  const [userSelection, setUserSelection] = useState(null);
  const [finalOutput, setFinalOutput] = useState(null);

  return (
    <>
      <div>Rock, paper, scissor, lizard and Spock</div>
    </>
  );
};

export default Game;

```

Now, let's create a function called ***clickHandler*** so that whenever a button is clicked, this function is called and a value is passed to it, which is then stored in our ***computerSelection*** state.

```javascript
const clickHandler = (value) => {
    setUserSelection(value);
  };

```

After that, we'll update the jsx within the return statement.

```javascript
// Game.js

import React from "react";

const Game = () => {
  const [computerSelection, setComputerSelection] = useState(null);
  const [userSelection, setUserSelection] = useState(null);
  const [finalOutput, setFinalOutput] = useState(null);

  const clickHandler = (value) => {
    setUserSelection(value);
  };

  return (
    <>
      <h1>Rock Paper Scissors lizard Spock</h1>
      <div>
        <div className="container">
          <div className="section">
            <div className="info">
              <h3>You</h3>
            </div>
            <div className="show">{userSelection}</div>
          </div>

          <div className="section">
            <div className="info">
              <h3>Computer</h3>
            </div>
            <div className="show computer">{computerSelection}</div>
          </div>
        </div>
        <h2>Final Output</h2>
        <button onClick={() => clickHandler("🧱")}>🧱</button>
        <button onClick={() => clickHandler("📰")}>📰</button>
        <button onClick={() => clickHandler("✂️")}>✂️</button>
        <button onClick={() => clickHandler("🦎")}>🦎</button>
        <button onClick={() => clickHandler("🖖")}>🖖</button>
      </div>
    </>
  );
};

export default Game;

```

So now, every time that button is clicked, the ***clickHanlder*** function will be called, and the value will be modified. That value will then be transferred to the ***setUserSelection*** state, where it will be updated and lastly it will get passed down to ***userSelection***.

It's time to make some ***selection***, and we'll do so with emoji.

```javascript
  const selection = ["🧱", "📰", "✂️", "🦎", "🖖"];
```

Now take the ***selection*** and map it over each ***selection***, adding a button inside it. After that, your Game component file should look like this.

```javascript
// Game.js

import React from "react";

const Game = () => {
  const [computerSelection, setComputerSelection] = useState(null);
  const [userSelection, setUserSelection] = useState(null);
  const [finalOutput, setFinalOutput] = useState(null);
  const selection = ["🧱", "📰", "✂️", "🦎", "🖖"];

  const clickHandler = (value) => {
    setUserSelection(value);
  };

  return (
    <>
      <h1>Rock Paper Scissors lizard Spock</h1>
      <div>
        <div className="container">
          <div className="section">
            <div className="info">
              <h3>You</h3>
            </div>
            <div className="show">{userSelection}</div>
          </div>

          <div className="section">
            <div className="info">
              <h3>Computer</h3>
            </div>
            <div className="show computer">{computerSelection}</div>
          </div>
        </div>
        <h2>Final Output</h2>

        <div className="attack-btn">
          {selection.map((select) => (
            <button onClick={() => clickHandler(select)}>{select}</button>
          ))}
        </div>
      </div>
    </>
  );
};

export default Game;
```

Let's import our Game component into our ***App.js*** component, so go to App.js and type  ***import Game from "./components/Game"***  and then simply use/pass that component inside the return statement. 
Your ***App.js*** file should resemble something like this.

```javascript
// App.js

import "./App.css";
import Game from "./components/Game";

function App() {
  return (
    <>
      <Game />
    </>
  );
}

export default App;
```

It’s time to start our development server, so for that simply type ***npm start*** and that’s going to automatically open react-app in the browser.

If you followed all of the steps up to this point, your react app should look something like this.

![react app](https://aviyel.com/assets/uploads/files/1634764979702-image.png)

Now, there may be a warning in your console about the unique key prop, so let's remove that first.

![warning](https://aviyel.com/assets/uploads/files/1634765177231-image-resized.png)

To remove that warning, simply provide a key to your mapped ***selection*** inside the Game component.

```javascript
{
  selection.map((select, index) => (
    <button key={index} onClick={() => clickHandler(select)}>
      {select}
    </button>
  ));
}
```

Now that we've handled the user choice, let's randomly generate the computer choice. To do this, create a function called ***randomChoiceGenerator*** with a variable called ***randomSelection*** inside it, and then take the selection array and use the ***Math.random*** function to generate the random choices, and finally set that generated value and pass it to the ***computerSelection*** state.

```javascript
const randomChoiceGenerator = () => {
  const randomSelection =
    selection[Math.floor(Math.random() * selection.length)];
  setComputerSelection(randomSelection);
};
```

To use this function, simply call it from within the previously created ***clickHandler*** function.

```javascript
const clickHandler = (value) => {
  setUserSelection(value);
  randomChoiceGenerator();
};
```

### React Hook: useEffect()

![react useEffect](https://aviyel.com/assets/uploads/files/1634792629571-image.png)

Let's use the ***useEffect()*** hooks in our project. By using this Hook, you tell React that your component needs to do something after render. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after performing the DOM updates. To this effect, we set the document title, but we could also perform data fetching or call some other imperative API. Placing  ***useEffect()*** inside the component lets us access the count state variable (or any props) right from the effect. We don’t need a special API to read it — it’s already in the function scope. Hooks embrace JavaScript closures and avoid introducing React-specific APIs where JavaScript already provides a ***solution.useEffect()*** hook is somewhat similar to the life-cycle methods that we are aware of for class components. It runs after every render of the component including the initial render. Hence it can be thought of as a combination of ***componentDidMount***, ***componentDidUpdate***, and ***componentWillUnmount*** .If we want to control the behavior of when the effect should run (only on initial render, or only when a particular state variable changes), we can pass in dependencies to the effect to do so. This hook also provides a clean-up option to allow cleaning up of resources before the component is destroyed. basic syntax of the ***effect:useEffect(didUpdate);*** Here, ***didUpdate*** is a function that performs mutations, subscriptions, timers, logging, etc. It will get triggered after the component is rendered to the screen as well as on every subsequently completed render. Now, getting back to our application, let us put this in use to set all the logic behind our application. Add the following code in the Game component:

```javascript
useEffect(() => {
    {
      switch (userSelection + computerSelection) {
        case "✂️📰":
        case "🧱✂️":
        case "📰🧱":
        case "🦎📰":
        case "🖖✂️":
        case "🧱🦎":
        case "📰🖖":
        case "🖖🧱":
        case "✂️🦎":
        case "🦎🖖":
          setFinalOutput("YOU WON! 🎉");
          break;
        case "📰✂️":
        case "✂️🧱":
        case "🧱📰":
        case "📰🦎":
        case "✂️🖖":
        case "🦎🧱":
        case "🖖📰":
        case "🧱🖖":
        case "🦎✂️":
        case "🖖🦎":
          setFinalOutput("YOU LOSE! 👎 ");
          break;
        case "🧱🧱":
        case "📰📰":
        case "✂️✂️":
        case "🦎🦎":
        case "🖖🖖":
          setFinalOutput("ITS A DRAW! 💥 ");
          break;
      }
    }
  }, [computerSelection, userSelection]);
```

The logic underlying our application is represented in this illustration.

![game logic](https://aviyel.com/assets/uploads/files/1634760430628-image-resized.png)

Finally, the ***Game*** component is locked and ready. The final code inside the Game component should look something like this.

```javascript
// Game.js

import React, { useEffect, useState } from "react";
import "./Game.css";

const Game = () => {
  const [computerSelection, setComputerSelection] = useState(null);
  const [userSelection, setUserSelection] = useState(null);
  const [finalOutput, setFinalOutput] = useState(null);
  const selection = ["🧱", "📰", "✂️", "🦎", "🖖"];

  const clickHandler = (value) => {
    setUserSelection(value);
    randomChoiceGenerator();
  };

  const randomChoiceGenerator = () => {
    const randomSelection =
      selection[Math.floor(Math.random() * selection.length)];
    setComputerSelection(randomSelection);
  };

  useEffect(() => {
    {
      switch (userSelection + computerSelection) {
        case "✂️📰":
        case "🧱✂️":
        case "📰🧱":
        case "🦎📰":
        case "🖖✂️":
        case "🧱🦎":
        case "📰🖖":
        case "🖖🧱":
        case "✂️🦎":
        case "🦎🖖":
          setFinalOutput("YOU WON! 🎉");
          break;
        case "📰✂️":
        case "✂️🧱":
        case "🧱📰":
        case "📰🦎":
        case "✂️🖖":
        case "🦎🧱":
        case "🖖📰":
        case "🧱🖖":
        case "🦎✂️":
        case "🖖🦎":
          setFinalOutput("YOU LOSE! 👎 ");
          break;
        case "🧱🧱":
        case "📰📰":
        case "✂️✂️":
        case "🦎🦎":
        case "🖖🖖":
          setFinalOutput("ITS A DRAW! 💥 ");
          break;
      }
    }
  }, [computerSelection, userSelection]);

  return (
    <>
      <h1>Rock Paper Scissors lizard Spock</h1>
      <div>
        <div className="container">
          <div className="section">
            <div className="info">
              <h3>You</h3>
            </div>
            <div className="show">{userSelection}</div>
          </div>

          <div className="section">
            <div className="info">
              <h3>Computer</h3>
            </div>
            <div className="show computer">{computerSelection}</div>
          </div>
        </div>
        <h2>{finalOutput} </h2>

        <div className="attack-btn">
          {selection.map((select, index) => (
            <button key={index} onClick={() => clickHandler(select)}>
              {select}
            </button>
          ))}
        </div>
      </div>
    </>
  );
};

export default Game;
```

Full project CSS and article available here => https://aviyel.com/post/1203

Happy Coding!! 

Follow [@aviyelHQ](https://twitter.com/AviyelHq) or [sign-up](https://aviyel.com/discussions) on Aviyel for early access if you are a project maintainer, contributor, or just an Open Source enthusiast.

Join Aviyel's Discord => [Aviyel's world](https://discord.gg/TbfZmbvnN5)

Twitter =>[https://twitter.com/AviyelHq]