circuit

Building a Rock Paper Scissors Game with JavaScript

Let's Build a Rock Paper Scissors Game Using Vanilla JavaScript




Image By Mehdi Aoussiad.

Image By Mehdi Aoussiad.

Introduction

The Rock-Paper-Scissors game is one of the exciting projects that you have to try in order to improve your JavaScript skills. Last month, I built this simple game, It was one of the projects that I have tried in my 100 days of code challenge. So before trying this project, you will need to have basic knowledge of HTML, CSS, and JavaScript. As you can see, the project is so simple, it's just a Rock-Paper-Scissors game where you can play against the computer and compare your score to the computer's score. Let's see how our game looks.

The Project Demo

As you can see in the example above, you have the ability to choose between the rock, the paper, and the scissors. After that, it will generate a random icon for you and for the computer. If you win, your score will increase, and the same thing for the computer.

Let's Start with HTML

First, we will create a container that will take in two sections. One for the computer, and the other for the player. Each section will contain the score and the icon. Under that container, we will put the rock, the paper, and the scissor buttons. Let's have a look at the example below:

Let's Style Our Elements

So now, we will style our elements using CSS. You can read the code below to see our stylesheet.

The JavaScript Part

Now, this is the exciting part that will make our game functional. In our JavaScript logic, we have created a variable for the computer score and the player score, then we selected our HTML elements. After that, we created an array that contains the rock, the paper, and the scissors icons in order to get them randomly from the array. Then we created the game function that contains all the logic, such as getting random icons from the array, putting them on the DOM, and the if statements for each situation(rock against paper, and etc). That function will run for each button clicked. Read the code below carefully to understand our logic.

Now Congratulations, you have easily created a simple Rock-Paper-Scissors game with Vanilla JavaScript.

Conclusion

The best way to become a good developer is by practicing what you have learned. Practice makes perfect. Building a JavaScript game will help you practice and improve your coding skills in general. So that's it for this article, I hope you learned something new today.




Continue Learning