Checkout my Getting Started with React video course on Skillshare. It is 100% free.

Build a game with React part 3 – simple animations by using setInterval and clearInterval in React JS

We will see in this final part of the series how to use React with setInterval to generate a basic animation and also how to end the running of a setInterval.

This screencast is part of a three part course. You can visit the main page of the Building a complete Rock Paper Scissors game with ReactJs course or can go directly to specific chapter:

These examples are created by using create-react-app. You can check here a short guide on how to setup your machine to run the code samples.

Audio transcript

We achieved a lot with our application. Our game has now a basic layout, knows how to draw some random symbols and also how to show the corresponding icons for these symbols.

One thing that we could do next is to show these shuffling animations when the button is pressed. There are multiple techniques that we can use to accomplish this, but for the sake of the the example let’s pick the pure Javascript one.

In Javascript we have the two main timer functions. First we have setInterval and also we have setTimeout. For both of them the main idea is that they will execute a specific function after some time. We give them a function to execute and the delay.

The main difference between them is that setTimeout will execute the given function just once, meanwhile setInterval will execute it until canceled. Given the fact that in our example this shuffling effect is made from multiple random picks, we will use the setInterval function.      

This being said, what we should do now is go back into our code first I will take all the part that generates the random symbols and wrap it in a function, and use this function with the setInterval function. I will give a interval of 100 milliseconds, meaning that this function will be run every 100 ms until canceled. And after the save , if we press the run game button, we will see the animation in action.

Still things are not yet complete. One issue that we face now is that the animation is not stopping. For now I will just stop it manually, by refreshing the page.

We need to find a way to stop the execution of this function in a programatic way. If we go back into the documentation we will discover this clear interval function that we can use combined with a reference to a specific set interval.

Knowing this the plan will be like : we will let the function run for 40 times and after use this clear interval to cancel the execution of our function. First I will go back into the source and in here I will create a new variable called counter. This counter start with the value of 0 in a new game. Every time this function runs, the counter gets incremented.

Next we will need a reference to our interval, and I will defined here a new variable called my interval and as you can see it will point to the setInterval.

After this I will use a if statement to check if the counter had reach a level above 40 and if so I will say clearInterval of my interval.

After the save, when the page refreshes when we will run again the game we will see that our animation will stop after 40 runs.

And the final step:  we should teach the game on how to decide the winner. For this , we will introduce a new value on the state, called winner, and set it to an empty string. The decision will be taken in a new function called decideWinner and this function will be called after we clear the interval.

Given the fact that we will have to deal with state variables we will use setState and say that the winner should be this do decideWinner and out of this function will return the result of our game.

We will start by using a destructor statement to extract the value of player blue and player red out of this state.

We will start by checking player red is equal with player blue, case in which we will return a draw result.

Next we will check if the payer Red is not the winner. Begin a longer statement I will just paste this code,  but basically we just check here for every on the three cases that could make playerRed the winner and in this case we will return that player red is the winner.

And finally if we don’t have a draw and if playerRed is not the winner it’s safe to assume that playerBlue won the game.

Now all that is left to do is go inside the render method and in here in a paragraph I will display the state variable for the winner and close the paragraph.

So our game should be ready to go for a testdrive. If we run the game it will select for the red player paper, for the blue payer rock and it will tell us that the red player wins.

And this concluded our application. With this we have seen in action things like basic react components, eventHandlers or how to use Javascript timing functions with react. Thank you for watching and I hope you’ve enjoyed it. If you have questions don’t hesitate to leave a comment below and share this set of tutorials. Happy coding and see you the next time.

Build a game with React part 2 – using setState

In the second part of this tutorial we will see in action things like how to change the state of a component, will add images to our game and "teach" it how to draw some random symbols.

This screencast is part of a three part course. You can visit the main page of the Building a complete Rock Paper Scissors game with ReactJs course or can go directly to specific chapter:

These examples are created by using create-react-app. You can check here a short guide on how to setup your machine to run the code samples.

Audio transcript

Hello and welcome back ! In the first part we added the basic parts for our game. Let’s now make our game to select some random symbol.

In order to achieve this we will need to tell the game what are all available options. I will do in the main app and add a default constructor, that just makes a super call with the default properties.

The next step will be to add a symbols filed of the this reference.It will point to an array will all of the available symbols: “rock”, “paper” and “scissors”.

We will also need a button to start the game. I will go in the main render and here add this button with the text run game.

Will will also add a run game method that initially will just have a simple console log with the text start the game.

This method will be assigned to the onClick event of the button. After the save, if I open the console you will see that every time we press the button we have this message appearing in the console.

Having this set in place , the next logical step will be to teach the game how draw a random element at the button click. Basically we will need to generate a random index and get the corresponding element out of this array.

First I will create the random index, and give it a name of index. To generate a random number I will use Math.random and will multiply this by the maximum number of symbols, in our case 3.

We will also use Math.floor to be sure that we will not get numbers like 2.5 or 1.3 or anything that is not a whole number.

And with this random index constructed we can now just console log of this dot symbols and of index.

Now if we refresh the page , when we press the button we will get a random element after that another one , another one and so on.

Let’s get these random symbols into the view now. We have to replace this static value and also this one with something like the random element generated in here.

This a perfect example to use the state of the components. First I will replace this with this dot state playerRed and also for this one I will write this dot state dot player blue.

These two state values will be set in the run game method. Given the fact that we to deal with state properties we will have to use this setState and pass it a object. Inside this object I will sat that player red equals this dot and as and index I will get this whole formula.

Will reuse exactly the same formula but this time for player blue.

Will delete the not needed code , and after we save we will see that we get an error.

This is because in here we are trying to access something from the sate and we have not yet created that state.

This is very easy to fix. I go inside the constructor and write that the state equals an empty object.

And with this set in place, if we go back in the game window can see now that every time we press the Run button we get a random symbol displayed on our screen.

Let’s go and take another look at the the final version of the game. In here we have these nice icons for the symbols and not a static text. Coming back to the code you can see that in the public folder we have this img folder, that contains the three symbol icons. All of them have a png extension.

To build this into our project we can use the background image property for the  inline style . Here I will set the URL to be the image folder plus the corresponding symbol and plus the file extension of PNG.

We will also remove the former code .. and now if we save and run the game you will see that new now also have the icons on screen.

You may wonder why this second image is rotated 180 deg. Well this is because of this css property I’ve added here and that defines that the second item that this type should have a css scale and css flip as a filter.