Ready to level up your web development skills? Follow this tutorial on creating an animated rock paper scissors game with HTML, CSS, and JavaScript.
Table of Contents
The game of Rock Paper Scissors is a timeless classic that has been enjoyed by people of all ages for generations. Despite its simplicity, the game can be incredibly challenging and entertaining, making it a perfect starting point for those who are interested in game development.
In this tutorial, we will be using HTML, CSS, and JavaScript to create an animated version of Rock Paper Scissors. By following along with our step-by-step instructions and code snippets, you will gain a basic understanding of these three essential web development tools.
Not only will you learn how to create an engaging game, but you will also gain valuable experience with HTML game development, CSS animation techniques, and JavaScript game programming. By the end of this tutorial, you'll have a basic understanding of HTML, CSS, and JavaScript, and you'll have built an engaging project to show off your new skills.
Join My Telegram Channel to Download the Project: Click Here
Prerequisites:
Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.
Source Code
Step 1 (HTML Code):
To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our rock paper scissors game.
Here's a breakdown of what each section of the code does:
The <!DOCTYPE html> declaration specifies that the document is an HTML5 document.
The <html> element is the root element of the document and wraps all the other elements.
The <head> element contains meta data and resources used by the web page. Here, it includes a title for the web page, a reference to an external font-awesome stylesheet, a reference to an external CSS stylesheet, and specifies the character encoding used for the document.
The <body> element contains the content of the web page that will be visible to the user.
The <a> element creates a hyperlink to an external website, in this case the website of the creator of the code. The class attribute specifies a CSS class to apply to the link, and the target attribute specifies that the link should open in a new tab.
The <h1> element creates a heading for the web page.
The <div> element with class="scoreboard" contains two child <div> elements, each displaying the score of the player and computer.
The <div> element with class="choices" contains three child <div> elements, each representing a possible move in the game.
The <div> element with class="result" displays the result of the game.
The <div> element with id="computer-choice" displays the computer's choice in the game.
The <div> element with class="timer" displays a countdown timer for the game.
The <button> element with id="play-again" allows the user to play the game again.
The <script> element contains JavaScript code that controls the logic and behavior of the game. The src attribute specifies the location of the JavaScript file.
After creating the files just paste the following below codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.
This is the basic structure of our rock paper scissors game using HTML, and now we can move on to styling it using CSS.
Step 2 (CSS Code):
Once the basic HTML structure of the rock paper scissors game is in place, the next step is to add styling to the rock paper scissors game using CSS. CSS allows us to control the visual appearance of the website, including things like layout, color, and typography.
Next, we will create our CSS file. In this file, we will use some basic CSS rules to style our rock paper scissors game.
The code starts by importing the Google Fonts library, specifically the 'Roboto' font in weights 400 and 700.
Then, the code sets some global styles, such as applying the box-sizing property to all elements, setting margins and paddings to 0, and setting the background color of the body to a pale purple.
The code then proceeds to style the scoreboard, which is displayed as a horizontal row of boxes with a border, and the choices section which contains the options for the game, also styled as boxes with borders and a transition effect when hovered over.
Next, the code styles the result section, which displays the outcome of the game, and the timer section, which shows the countdown of the game.
Finally, the code styles the play-again button, which allows the user to restart the game, and a logo which is positioned at the top right corner of the page.
To ensure a responsive design, the code includes media queries for devices with a maximum screen width of 600px. In this case, the choices section is wrapped when there is not enough space, and the margin of the choice box is reduced.
This will give our rock paper scissors game an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.
/* Import Google Fonts */
@import url('https://fonts.googleapis.com/css?family=Roboto:400,700&display=swap');
/* Apply global styles */
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
body {
font-family: 'Roboto', sans-serif;
background-color: #E6E6FA;
}
h1 {
text-align: center;
font-size: 3rem;
margin-top: 2rem;
color: #660033;
}
/* Style scoreboard */
.scoreboard {
display: flex;
justify-content: center;
margin-top: 2rem;
}
.scoreboard > div {
font-size: 2rem;
margin: 0 1rem;
padding: 0.5rem;
border: 2px solid #660033;
border-radius: 10px;
color: #660033;
}
/* Style choices */
.choices {
display: flex;
justify-content: center;
margin-top: 3rem;
}
.choice {
border: 2px solid #660033;
border-radius: 10px;
margin: 0 2rem;
padding: 2rem;
background-color: #FFFFFF;
transition: transform 0.2s ease-in-out;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
}
.choice:hover {
transform: scale(1.1);
}
.choice:active {
transform: scale(0.9);
}
.choice i {
color: #660033;
font-size: 50px;
}
/* Style result */
.result {
text-align: center;
font-size: 2rem;
margin-top: 2rem;
color: #660033;
}
#computer-choice {
text-align: center;
font-size: 2rem;
color: #660033;
}
/* Style timer */
.timer {
text-align: center;
font-size: 2rem;
margin-top: 1rem;
color: #660033;
}
/* Style play again button */
.play-again {
display: block;
margin: 3rem auto 1rem auto;
padding: 1rem 2rem;
border: none;
border-radius: 10px;
background-color: #660033;
color: #FFFFFF;
font-size: 1.5rem;
cursor: pointer;
transition: background-color 0.2s ease-in-out;
}
.play-again:hover {
background-color: #993366;
}
.logo {
position: absolute;
top: 30px;
right: 30px;
display: block;
z-index: 100;
transition: all 250ms linear;
}
.logo img {
height: 30px;
width: auto;
display: block;
}
.play-again:active {
transform: scale(0.9);
}
/* Add responsive design */
@media only screen and (max-width: 600px) {
.choices {
flex-wrap: wrap;
}
.choice {
margin: 2rem 1rem;
}
.timer {
margin-top: 1rem;
}
}
Step 3 (JavaScript Code):
Finally, we need to create a JavaScript code that implements a simple game of Rock-Paper-Scissors between a player and a computer.
The code initializes various variables and constants and defines several functions.
The const declarations define a set of DOM elements that will be manipulated to display the game's status and enable the player to interact with the game.
The let declarations define mutable variables that will be used to track the game's state, such as the player and computer's scores and the current countdown timer value.
The weapons array contains the possible choices of weapons the computer can choose from.
The computerPlay function generates a random weapon choice for the computer.
The updateScore function takes two arguments, the player's and computer's weapons. It compares the weapons, determines the winner, updates the scores, and displays the result on the web page. The function also handles the cases where the player has not made a choice or one player reaches a score of 5.
The selectWeapon function is called when the player clicks on one of the weapon choices. It retrieves the player's choice and calls the updateScore function with the player's and computer's weapons as arguments.
The startTimer function is called after the player makes a choice. It starts a countdown timer and updates the remaining time on the web page. If the timer reaches zero, the function calls the updateScore function with null for the player's weapon to indicate that the player did not make a choice in time.
The stopTimer function is called when the game is over. It clears the countdown timer and resets the countdown value.
The resetGame function is called when the player clicks on the "Play Again" button. It resets the game state, updates the web page, and starts a new countdown timer.
The disableOptions and enableOptions functions are called to disable and enable the weapon choices respectively.
The choices and playAgainBtn DOM elements have event listeners attached to them. When the player clicks on a weapon choice, the selectWeapon function is called. When the player clicks on the "Play Again" button, the resetGame function is called.
Finally, the code sets the initial value of the countdown on the web page and starts the countdown timer when the page loads.
Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.
const choices = document.querySelectorAll('.choice');
const playerScoreElem = document.querySelector('.player-score');
const computerScoreElem = document.querySelector('.computer-score');
const resultElem = document.querySelector('#result');
const playAgainBtn = document.querySelector('#play-again');
const countdownElem = document.querySelector('#countdown');
const computerChoiceElem = document.querySelector('#computer-choice');
const weapons = ['rock', 'paper', 'scissors'];
let playerScore = 0;
let computerScore = 0;
let countdown = 10;
let timeout;
// Function to generate random weapon for computer
function computerPlay() {
const weaponIndex = Math.floor(Math.random() * weapons.length);
return weapons[weaponIndex];
}
// Function to update score and display result
function updateScore(playerWeapon, computerWeapon) {
clearTimeout(timeout);
if (playerWeapon) {
computerChoiceElem.innerHTML = `Computer choose: ${computerWeapon}.`;
if (playerWeapon === computerWeapon) {
resultElem.innerHTML = "It's a tie!";
} else if (
(playerWeapon === 'rock' && computerWeapon === 'scissors') ||
(playerWeapon === 'paper' && computerWeapon === 'rock') ||
(playerWeapon === 'scissors' && computerWeapon === 'paper')
) {
resultElem.innerHTML = 'You win!';
playerScore++;
playerScoreElem.innerHTML = `Player: ${playerScore}`;
} else {
resultElem.innerHTML = 'Computer wins!';
computerScore++;
computerScoreElem.innerHTML = `Computer: ${computerScore}`;
}
startTimer();
} else {
computerChoiceElem.innerHTML = `Game Over`;
resultElem.innerHTML = 'You did not make a choice! | You lose the game!';
resultElem.style.color = 'red';
disableOptions();
}
if (playerScore === 5) {
resultElem.textContent = 'You win the game!';
resultElem.style.color = 'green';
computerChoiceElem.innerHTML = 'Game Over';
disableOptions();
stopTimer();
}
if (computerScore === 5) {
resultElem.textContent = 'You lose the game!';
resultElem.style.color = 'red';
computerChoiceElem.innerHTML = 'Game Over';
disableOptions();
stopTimer();
}
}
// Function to handle player choice
function selectWeapon() {
clearTimeout(timeout);
countdownElem.innerHTML = '10';
countdown = 10;
const playerWeapon = this.id;
const computerWeapon = computerPlay();
updateScore(playerWeapon, computerWeapon);
}
// Function to start countdown timer
function startTimer() {
countdown--;
countdownElem.innerHTML = countdown;
if (countdown === 0) {
const computerWeapon = computerPlay();
updateScore(null, computerWeapon);
} else {
timeout = setTimeout(startTimer, 1000);
}
}
function stopTimer() {
clearInterval(timeout);
countdown = 10;
countdownElem.textContent = countdown;
}
// Function to reset the game
function resetGame() {
playerScore = 0;
computerScore = 0;
countdown = 10;
playerScoreElem.innerHTML = 'Player: 0';
computerScoreElem.innerHTML = 'Computer: 0';
resultElem.innerHTML = 'Choose your weapon!';
countdownElem.innerHTML = '10';
resultElem.style.color = '#660033';
computerChoiceElem.innerHTML = '';
enableOptions();
startTimer();
}
function disableOptions() {
choices.forEach((choice) => {
choice.style.pointerEvents = 'none';
});
}
function enableOptions() {
choices.forEach((choice) => {
choice.style.pointerEvents = 'auto';
});
}
// Event listeners
choices.forEach((choice) => choice.addEventListener('click', selectWeapon));
playAgainBtn.addEventListener('click', resetGame);
// Start countdown timer when page loads
countdownElem.innerHTML = countdown; // Set initial value of countdown in HTML
timeout = setTimeout(startTimer, 1000);
Final Output:
See the Pen JS Rock, Paper, Scissors with Timer by Faraz (@codewithfaraz) on CodePen.
Conclusion:
In conclusion, we hope that this tutorial has provided you with a fun and engaging introduction to HTML game development, CSS animation techniques, and JavaScript game programming. By creating an animated version of Rock Paper Scissors, you have learned the fundamentals of game development and have gained valuable experience with three essential web development tools.
We encourage you to continue exploring and experimenting with HTML, CSS, and JavaScript, as there are countless possibilities for creating exciting and innovative games and web applications. With dedication and practice, you can become a skilled game developer and web programmer, and the possibilities are endless.
Thank you for following along with our tutorial, and we hope you enjoyed creating your own animated Rock Paper Scissors game. Happy coding!
That’s a wrap!
I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.
Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee
And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!
Thanks!
Faraz 😊