This blog assumes basic knowledge of HTML, CSS, and JavaScript. It is targeted towards individuals who are learning to create web applications.
When learning to code, practicing by creating applications is extremely important. Early-stage learners often get discouraged by the complexity of it all. Creating games is a great way to practice coding for a variety of reasons. First, we're familiar with the game rules, so that removes some of the complexity from the process. Second, games are fun, so we enjoy ourselves coding them.
In this blog, we’ll create a game of rock-paper-scissors in JavaScript. In the process, we’ll learn or reinforce the following:
Setting up radio buttons and a button in HTML
Manipulating the DOM in JavaScript
Attaching and defining event listeners to the HTML input elements
You almost certainly know the rules of the game, but let's have a look at them again:
Both players choose either rock, paper, or scissors.
If both players choose the same item, it is a tie.
If player 1 chooses rock and player 2 chooses paper, player 2 wins because paper wraps the rock.
If player 1 chooses rock and player 2 chooses scissors, player 1 wins because rock breaks scissors.
If player 1 chooses scissors and player 2 chooses paper, player 1 wins because scissors cut paper.
A fundamental skill to learn in coding is to be able to break down a problem into smaller, manageable subproblems. So, spend some time trying to find smaller subproblems that, when solved, will complete the implementation of this game. You should arrive at a list resembling the following:
Create a web page on which the game will be played.
Allow the player to select from rock, paper, and scissors. Update the web page with the player’s choice.
Implement a computer player that randomly picks from rock, paper, and scissors. Update the web page with the computer’s choice.
Decide who wins and display the result on the screen.
In this course, you will get hands-on game development experience with JavaScript. Using the classic game of Tetris, you are going to cover concepts like graphics, game loops, and collision detection. By the end of this course, we will have a fully functioning game with points and levels. Try it out with your friends and put it in your portfolio for employers to see.
We’ll start with some basic HTML and simple styling given in the following coding playground:
Let’s make sure we understand the purpose of the code given in the HTML tab and the CSS tab, bit by bit.
We first create h2
elements to show the computer (line 10) and the end user (line 11) choices. Inside the h2
elements, we place span
elements to display the values picked by both players. In the HTML code, these are empty. We’ll populate the text inside these span
elements using JavaScript.
For the player to choose an item, we use radio buttons created using the input
and the label
tags (lines 13–19). The input
tag creates the radio button, when the type
attribute is set to radio
. The name
attribute for all radio
buttons is set to the same value choice
, so the browser knows that they belong to the same group, and only one can be selected at a time.
The id
attributes for all radio buttons and span
elements are set appropriately because we’ll want to access these in JavaScript. For the radio button labels, you’ll notice that the label
tags have the for
attribute set equal to the id
attribute of the corresponding radio button. This helps with toggling a radio button when its label is clicked.
Note that we’ve disabled the “Play” button (line 19). The thought process is that until the player makes a choice with the radio button, there’s no point clicking the “Play” button and invoking its click event handler.
We don’t need to bother with the styling of the application. However, we set the text-transform
style for the span
elements to capitalize
so that we can use words in lowercase in JavaScript and have the browser worry about rendering “scissors” as “Scissors,” for example.
Let’s start implementing the game in JavaScript one bit at a time.
Let’s start by getting objects representing the necessary HTML elements and declaring an array that holds the three strings that the computer can randomly choose from. To get programmatic access to an HTML element using its unique id
, we can use the document.getElementById
function from the JavaScript DOM API. We’ll pass the unique id
values that we set in the HTML file earlier.
The first thing that we want to do is to enable the “Play” button as soon as a radio button is clicked. To do that, we need to add an event listener to all the radio buttons that sets the disabled
attribute of the “Play” button to false
.
We could pick the radio buttons one by one using their id
attributes and the getElementyById
function, but it is more convenient and less error-prone to access all the radio buttons using a single variable. This is possible because they all have the same name
attribute. We use the getElementsByName
function this time. Note the plural “Elements” in the function name. It returns a collection of all HTML elements with the name
value specified as the argument.
To iterate over the choices
radio buttons collection, we use the functional programming style of forEach
. The forEach
function invokes a function for each value in the collection on which it is called. Since we are saying choices.forEach
, there’ll be one call to a callback function for each value in the choices
collection, which holds all of our radio buttons. The callback function is for us to specify as an argument to the forEach
function. We use an anonymous function here. The variable c
is assigned each radio button, one by one, in each call.
Since we wanted to add an event listener that enables the “Play” button when a radio button is clicked, we call the addEventListener
function on c
, with click
specified as the event that we want to handle. A callback function needs to be passed as the second argument of the addEventListener
function. Again, we use an anonymous function here. Since we already have access to the “Play” button, courtesy of the variable playButton
, all that we need to do is playButton.disabled = false
.
We’ll add an anonymous function as the click event listener on the “Play” button. The first thing that we’d like to know when the “Play” button is clicked, is the player’s choice.
We wanted to obtain the particular radio button that was checked
in the choices
collection. We could do if-else
, here. But why not use filter
? Note that choices
is a collection of HTML elements, not a JavaScript array. That means that we can’t call filter
on it. So we first convert the collection of HTML elements into an array with Array.from
. The argument to this function is the choices
collection.
Now, we call filter
on the buttonsArray
using an anonymous function. This function will be called for every element in that array. For each element, b
, we specify a boolean condition b.checked
. The filter
function returns all the elements in the buttonsArray
for which this boolean condition evaluates to true. Since the array is based on radio buttons, we are confident that it’ll return an array with one element—the radio button element that was selected.
How do we extract the string associated with the radio button? Because of the way we defined the radio buttons (<input type=”radio” id=”rock” name=”choice” value=”rock”>
, for example), we can use the id
property. Now, let’s display this string as the player’s choice.
This is for those familiar with the basics of JavaScript and looking to advance their knowledge and really understand how the language works. We'll cover topics that are essential to help you read, understand, and write better code. Before starting, you should be familiar with the basics of variables, functions, and loops in JavaScript. This course will enable you to master JavaScript interview questions that stump most developers. You'll be able to talk intelligently about the fundamentals of the language and about common design patterns. This course has been created by Arnav Aggarwal, a full-stack engineer. Having attended a coding boot camp and having taught at another one, Arnav has extensive experience understanding how new developers learn to code. In under a month, Arnav's published articles on JavaScript concepts have received over 50,000 views and have been featured as staff selections on Medium.com and codementor.io because of their educational value.
Since we’ll have to display the computer’s choice too, we’ll define a function (lines 20–22) that assigns a text to a span
element, given both of these as arguments.
We add the text passed as the text
argument to the textContent
property of the span
element (line 21). Then, we go back to the “Play” button click handler and add a call to addTextToSpan()
(line 17) to display the player’s choice. By now, the player will see the “Play” button initially disabled. Once they click any of the radio buttons, the “Play” button will be enabled. If they click the “Play” button, they’ll see the choice that they made in front of “Your Choice” on the page.
We want the computer to make a random choice. We want it to pick a value at random from the possibleChoices
array. To do that, we need to generate a random index.
JavaScript provides a Math
library with several useful functions. One of these is the Math.random
function, which returns a number randomly picked between
A fractional value can’t be used as an array index. It has to be an integer between possibleChoices
array has three elements). How do we convert a randomly drawn positive fractional value less than
If we multiply this random value by Math.random
will be a positive number in the range
If we take the floor of random numbers in the range
We’ll define a function generateComputerChoice()
(lines 25–30) that makes a random choice, sets the HTML element to show the player what the computer chose, and returns the chosen value so that the calling function can decide who wins. Next, we’ll call this function in the “Play” button click handler (line 18):
We extend the “Play” button handler to decide who wins. We define a function showResult()
(lines 33–61) that takes two arguments: the player’s choice and the computer’s choice, and decides who wins.
We first check if there’s a tie (lines 34–36) because that’s easy to check. We use the ===
JavaScript operator. Note that we don’t use the ==
operator because it isn’t safe—it might do type coercion to deduce equality among different types of data.
Furthermore, we encode the game’s rules into the else if
parts. Each of the player’s choices becomes one else if
. If the player chooses “rock”, at this point, the computer’s choice would be either “paper”, or “scissors.” Why could it not be “rock”, too? Because we are in the else if
part already, and that possibility was exhausted in the if
part at the beginning. That’s why each else if
block has two possibilities.
For example, if the user pick “rock” while the computer picks anything else, the condition on line 37 evaluates to true
. Either the computer picks “paper” and wins (lines 38–40), or it picks “scissors” and loses (lines 41–43).
Notice that we call our addTextToSpan
function to display the result on the page. Next, we add a call to this function in the “Play” button click handler (line 19).
With this addition, our game is nearly complete. There’s only one improvement we’d like to make to it. Once the result of a game is decided, we’d like the radio buttons to be reset again and the “Play” button disabled so that the learner can start another round of the game. Here’s the code with the modified event handler.
Since this is the click handler for the “Play” button, and the event source is specified in the anonymous callback function argument (the e
parameter), the “Play” button itself is available through the e.target
property. So we disable it using e.target
.disabled = true
(line 20). Also, we iterate over the choices
collection to reset all the radio buttons (lines 21–23) using the forEach
function.
That's it for this blog. Do keep practicing. Try to add features to the game or styling with CSS. Stay tuned for more blogs on games like this rock, paper, scissors in JavaScript.
Free Resources