Building a ‘Fire Water Tree’ game in React

In this article, we will be learning to build a game using only some basic hooks and concepts in React helping us to strengthen our grips.

But before hitting the keyboard, let’s first understand how the game is to be played.
There are 3 items with which you play the game. Fire, water, tree.

  1. If fire is put against tree, fire gets a point as fire burns the tree down.
  2. If water is put against fire, water gets a point as water extinguishes fire.
  3. If tree is put against water, tree gets a point as tree absorbs water.
  4. The option picked by the computer would be auto-generated using random function and for user, there would be an option to pick.

Alright, so as you’ve got the basic idea, lets understand how are we actually going to implement it.

Let’s get started by running the command npx create-react-app in our desired directory

npx create-react-app 'YOUR_APP_NAME'

Now you can see the boilerplate React files and folders inside the folder created in your directory by the name ‘YOUR_APP_NAME’, open this in a code editor of your choice(I would prefer VS Code).

Clean all the already-existing code in App.js to get going, we will mainly write our logic in this file only as it is not that layered and heavy.

Firstly, let’s break the logic into parts and align them to React scheme-of-things.

We need to display the buttons for user to select any of the options and play again, along with an Image component to display the images of options selected by both user as well as the computer.

Let’s code the button component to start with.

As the title of the button (obviously) varies, we pass that as a dynamic prop to the component and return the button JSX from it.

Coming to the image component, it goes as follows:

Again as we pass the images dynamically, I have used a little trick over here.
I have named the png images same as what variable I will be passing as a prop to update the image.

Alright so that was about getting some building blocks for the game done, now let’s understand the logic part(the following code goes in App.js).

Whenever a user selects an option, we have to make computer select one option randomly and then we will decide who the winner is and display it on the screen accordingly.

For this, we will create an array of options for computer to pick from it at random.

const choices = ["fire", "tree", "water"];

Now, let’s write the logic for what we’ve discussed earlier.

Firstly let’s maintain states for handling userElement and computerElement, we will be using useState hook for achieving this.

const [userElement, setUserElement] = useState("null");  
const [computerElement, setComputerElement] = useState("null");
const handleSelect = (selected) => {
setUserElement(selected);
};

handleSelect will be passed to a function prop in Button component as follows:

<OptionButton title=”Fire” onClick={() => handleSelect(“fire”)}/>

OptionButton.js:

I am passing the element linked to that button as a parameter to handleSelect, the function which sets userElement to the element passed and sets computerElement to randomly picked option from the array as shown in the code below:

So that was about setting the user’s and computer’s choice, now let’s code the conditional logic to decide who the winner is according to the rules mentioned above.

But before jumping on that, let’s maintain a state to handle the winner

const [result, setResult] = useState("-");

Having that done,

Logic

At this point, we are done writing the state handling and logic part of the game, but we have to make sure the state is updated every time the option is selected by the user and computer both and the winner is to be displayed.

That is, we have to connect the state management dots of every discrete part.

Here is the code for the same followed by the explanation.

We put the entire winner-deciding logic that we’ve already discussed into useEffect for it to run every time the parameters passed to it change, just like how useEffect works.

What this does is, whenever any of the useElement or the computerElement changes, the entire useEffect function is run as a side effect on re-rendering thus updating all the states for us.

Coming to the JSX part, we will display the variables discussed above on the screen by adding some styles thus completing our app.

Code:

Lastly, I have also handled play again feature which just re-sets all the states and is implemented in the full code which you find linked here or at the end of this article.

And we have covered coding an entire app!, it’s been a bit long journey till here so let’s have some fun as a reward to ourselves :)

We will add a confetti celebration feature when we win, for that we need

@reonomy/react-confetti-explosion’ package in our app which we will get from npm and import in App.js.

import ConfettiExplosion from '@reonomy/react-confetti-explosion'; 

Let’s maintain a state to decide when to explode confetti, and whenever user is won, we will set the state to true, else it will be set to false by default.

const [isExploding, setIsExploding] = useState(false);

We will update this state to true right after when we set the winner to user to get it exploded only at the time of user’s victory!

App.js:

Alright, so that was it. Thanks for being around till the end of this fun mini project in React!

Github: https://github.com/jaymalave/FireWaterTree

--

--

--

Computer Science Undergrad Sophomore, Avid Writer, Computer Programmer, Economy and Equity Markets Enthusiast.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

React With CORS: The How and the Why

Metal Gears Connecting and Achiving more

How to ace your JavaScript coding assignment round — Part 3

6 Essential NPM Packages For Every Web Developer

TutorialspointTutorialspoint

Create Connections Between Objects with Konva and React

ES13 (ES2022) | Prominent Features

Prerender Angular application — be SEO

Electron: Getting Custom Error Messages from IPC Main

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jay Malave

Jay Malave

Computer Science Undergrad Sophomore, Avid Writer, Computer Programmer, Economy and Equity Markets Enthusiast.

More from Medium

Leetcode 238: Product of Array Except Self Javascript solution

React, Libraries and Frameworks: an Introduction

What is Redux Toolkit?

A light intro to instrumentation on the web frontend