Discover how to easily make an engaging rock paper scissors game using js or JavaScript codewars.
In this article, we will guide you through the process of building the game logic and user interface and provide you with all the code you need to get started.
So bear with us as we will show you how to code rock paper scissors in JavaScript. Let’s get started!
What is Rock Paper Scissors?
Rock Paper Scissors is a beloved game that captivates people of all generations.
Whether as a childhood pastime with friends or a means to settle disputes in the workplace, this timeless game always brings a sense of excitement and friendly rivalry.
Rock paper scissors in JavaScript
Get ready for a simple and fun game of rock-paper-scissors JavaScript codewars! With just three options – rock, paper, or scissors – two players face off to see who wins.
In this JavaScript-based game, you’ll be playing against the computer. You’ll make your choice while the computer randomly selects its own.
The final result will be displayed on the screen, along with a handy restart button. Plus, this game is designed to be responsive, so you can enjoy it on any device.
How to code a rock paper scissors game in JavaScript?
Here, we will show you how to make a rock paper scissors game in js or JavaScript.
Here’s the code for HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="src/style.css">
<title>Rock Paper Scissor</title>
</head>
<body>
<section class="game">
<!--Title -->
<div class="title">Rock Paper Scissor</div>
<!--Display Score of player and computer -->
<div class="score">
<div class="playerScore">
<h2>Player 1</h2>
<p class="p-count count">0</p>
</div>
<div class="computerScore">
<h2>Player 2</h2>
<p class="c-count count">0</p>
</div>
</div>
<div class="move">Choose your move</div>
<!--Number of moves left before game ends -->
<div class="movesleft">Moves Left: 5</div>
<!--Options available to player to play the game -->
<div class="options">
<button class="rock">Rock</button>
<button class="paper">Paper</button>
<button class="scissor">Scissors</button>
</div>
<!--Final result of the game -->
<div class="result"></div>
<!--Reload the game -->
<button class="reload"></button>
</section>
<script src="src/script.js"></script>
</body>
</html>
Here’s the code for the CSS
/* style.css */
/* universal selector - Applies to whole document */
*{
padding: 0;
margin: 0;
box-sizing: border-box;
background: #f5f4f5;
color: hwb(0 3% 97%);
}
/* To center everything in game */
.game{
display: flex;
flex-direction: column;
height: 100vh;
width: 100vw;
justify-content: center;
align-items: center;
}
/* Title of the game */
.title{
position: absolute;
top: 0;
font-size: 4rem;
z-index: 2;
}
/* Score Board */
.score{
display: flex;
width: 30vw;
justify-content: space-evenly;
position: absolute;
top: 70px;
z-index: 1;
}
/* Score */
.p-count,.c-count{
text-align: center;
font-size: 1.5rem;
margin-top: 1rem;
}
/* displaying three buttons in one line */
.options{
display: flex;
width: 50vw;
justify-content: space-evenly;
margin-top: 2rem;
}
/* Styling on all three buttons */
.rock, .paper, .scissor{
padding: 0.8rem;
width: 100px;
border-radius: 10px;
background: rgb(216, 128, 172);
outline: none;
border-color: rgb(248, 86, 113);
border: none;
cursor: pointer;
}
.move{
font-size: 2rem;
font-weight: bold;
}
/* Reload button style */
.reload {
display: none;
margin-top: 2rem;
padding: 1rem;
background: rgb(216, 128, 172);
outline: none;
border: none;
border-radius: 10px;
cursor: pointer;
}
.result{
margin-top: 20px;
font-size: 1.2rem;
}
/* Responsive Design */
@media screen and (max-width: 612px)
{
.title{
text-align: center;
}
.score{
position: absolute;
top: 200px;
width: 100vw;
}
.options{
width: 100vw;
}
Here’s the code for script.js
// Complete logic of game inside this function
const game = () => {
let playerScore = 0;
let computerScore = 0;
let moves = 0;
// Function to
const playGame = () => {
const rockBtn = document.querySelector('.rock');
const paperBtn = document.querySelector('.paper');
const scissorBtn = document.querySelector('.scissor');
const playerOptions = [rockBtn,paperBtn,scissorBtn];
const computerOptions = ['rock','paper','scissors']
// Function to start playing game
playerOptions.forEach(option => {
option.addEventListener('click',function(){
const movesLeft = document.querySelector('.movesleft');
moves++;
movesLeft.innerText = `Moves Left: ${5-moves}`;
const choiceNumber = Math.floor(Math.random()*3);
const computerChoice = computerOptions[choiceNumber];
// Function to check who wins
winner(this.innerText,computerChoice)
// Calling gameOver function after 10 moves
if(moves == 5){
gameOver(playerOptions,movesLeft);
}
})
})
}
// Function to decide winner
const winner = (player,computer) => {
const result = document.querySelector('.result');
const playerScoreBoard = document.querySelector('.p-count');
const computerScoreBoard = document.querySelector('.c-count');
player = player.toLowerCase();
computer = computer.toLowerCase();
if(player === computer){
result.textContent = 'Tie'
}
else if(player == 'rock'){
if(computer == 'paper'){
result.textContent = 'Player 2 Won';
computerScore++;
computerScoreBoard.textContent = computerScore;
}else{
result.textContent = 'Player 1 Won'
playerScore++;
playerScoreBoard.textContent = playerScore;
}
}
else if(player == 'scissors'){
if(computer == 'rock'){
result.textContent = 'Player 2 Won';
computerScore++;
computerScoreBoard.textContent = computerScore;
}else{
result.textContent = 'Player 1 Won';
playerScore++;
playerScoreBoard.textContent = playerScore;
}
}
else if(player == 'paper'){
if(computer == 'scissors'){
result.textContent = 'Player 2 Won';
computerScore++;
computerScoreBoard.textContent = computerScore;
}else{
result.textContent = 'Player 1 Won';
playerScore++;
playerScoreBoard.textContent = playerScore;
}
}
}
// Function to run when game is over
const gameOver = (playerOptions,movesLeft) => {
const chooseMove = document.querySelector('.move');
const result = document.querySelector('.result');
const reloadBtn = document.querySelector('.reload');
playerOptions.forEach(option => {
option.style.display = 'none';
})
chooseMove.innerText = 'Game Over!!'
movesLeft.style.display = 'none';
if(playerScore > computerScore){
result.style.fontSize = '2rem';
result.innerText = 'You Won The Game'
result.style.color = '#308D46';
}
else if(playerScore < computerScore){
result.style.fontSize = '2rem';
result.innerText = 'You Lost The Game';
result.style.color = 'red';
}
else{
result.style.fontSize = '2rem';
result.innerText = 'Tie';
result.style.color = 'grey'
}
reloadBtn.innerText = 'Restart';
reloadBtn.style.display = 'flex'
reloadBtn.addEventListener('click',() => {
window.location.reload();
})
}
// Calling playGame function inside game
playGame();
}
// Calling the game function
game();
Different way on how to make a rock paper scissors game in javascript
Rock paper scissors is a game played by two people using their hands.
Each player makes one of three shapes: rock (a closed fist), paper (an open hand), or scissors (a fist with the index and middle fingers extended).
The outcome depends on these rules:
📌Rock beats scissors.
📌Scissors beat paper.
📌Paper beats rock.
To create a Rock Paper Scissors game in JavaScript, we need to know how to get user input, generate random choices for the computer, and compare the choices to determine the winner. Let’s go through the process step by step.
1. Set up the project
First, you’ll need to have Node.js installed on your computer. Create a new directory for your project and navigate to it in the command line.
Then, create a new file for your code for instance (game.js).
2. Get user input
In order to begin our JavaScript implementation, we must obtain the user’s selection.
We can accomplish this by utilizing the prompt function, you can use the readline module that comes with Node.js. At the top of your game.js file, add the following code to create a readline interface:
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
3. Define the game logic
You’ll need to define the logic for the game. This includes defining the possible choices (rock, paper, and scissors), a function to randomly choose the computer’s move, and a function to determine the winner of the game based on the rules of rock-paper-scissors.
const choices = ['rock', 'paper', 'scissors'];
const getComputerChoice = () => {
const index = Math.floor(Math.random() * 3);
return choices[index];
}
const determineWinner = (playerChoice, computerChoice) => {
if (playerChoice === computerChoice) {
return 'It\'s a tie!';
} else if (
(playerChoice === 'rock' && computerChoice === 'scissors') ||
(playerChoice === 'paper' && computerChoice === 'rock') ||
(playerChoice === 'scissors' && computerChoice === 'paper')
) {
return 'You win!';
} else {
return 'The computer wins!';
}
}
4. Use the readline interface to get the player’s choice
After that you have defined the game logic, you can use the readline interface to get the player’s choice and play the game. Here’s an example of how you could do this:
const playGame = () => {
readline.question('Choose rock, paper, or scissors: ', playerChoice => {
playerChoice = playerChoice.toLowerCase();
if (!choices.includes(playerChoice)) {
console.log('Invalid choice');
readline.close();
return;
}
const computerChoice = getComputerChoice();
console.log(`You chose ${playerChoice}`);
console.log(`The computer chose ${computerChoice}`);
console.log(determineWinner(playerChoice, computerChoice));
readline.close();
});
}
playGame();
In this code, we ask the user for their choice using the question method from the readline interface.
Then, we use the getComputerChoice and determineWinner functions to play the game and show the result.
5. Play the game
To run and play your game, save your code to the game.js file and run it from the command line using the node command for example (node game.js).
You should see a prompt asking you to choose rock, paper, or scissors. After making your choice, you’ll see the result of the game.
Here’s the complete code:
const readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
const choices = ['rock', 'paper', 'scissors'];
const getComputerChoice = () => {
const index = Math.floor(Math.random() * 3);
return choices[index];
}
const determineWinner = (playerChoice, computerChoice) => {
if (playerChoice === computerChoice) {
return 'It\'s a tie!';
} else if (
(playerChoice === 'rock' && computerChoice === 'scissors') ||
(playerChoice === 'paper' && computerChoice === 'rock') ||
(playerChoice === 'scissors' && computerChoice === 'paper')
) {
return 'You win!';
} else {
return 'The computer wins!';
}
}
const playGame = () => {
readline.question('Choose rock, paper, or scissors: ', playerChoice => {
playerChoice = playerChoice.toLowerCase();
if (!choices.includes(playerChoice)) {
console.log('Invalid choice');
readline.close();
return;
}
const computerChoice = getComputerChoice();
console.log(`You chose ${playerChoice}`);
console.log(`The computer chose ${computerChoice}`);
console.log(determineWinner(playerChoice, computerChoice));
readline.close();
});
}
playGame();
Output:
Choose rock, paper, or scissors: You chose rock
The computer chose scissors
You win!
Conclusion
In conclusion, this article provides a step-by-step guide on how to code a rock paper scissors game using JavaScript.
It covers the game logic, and user interface, and provides the necessary code to get started.
The game allows players to choose between rock, paper, and scissors while playing against the computer.
The result of each round is displayed on the screen, and there is an option to restart the game.
By executing the provided instructions and using the code above, readers can easily create their own rock paper scissors game in JavaScript.
We are hoping that this article provides you with enough information that helps you understand how to make a rock paper scissors game in js or JavaScript.
You can also check out the following article:
- Understanding the -1 Index in JavaScript Arrays
- How to check if a function exists in JavaScript?
- Variable might not have been initialized JavaScript
Thank you for reading itsourcecoders 😊.