Rock Paper Scissors Game (JavaScript)

Thu Sep 07 2023

This is a game of Rock, paper, scissors.


What is your choice?


You:
Computer:

Result:

In .html file:

<div class="game">

<h1>What is your choice?</h1>
<button class="option">🪨</button>
<button class="option">📃</button>
<button class="option">✂</button>

<div class="game__heading" id="player">You: </div>
<div class="game__heading" id="computer">Computer: </div>
<div class="game__heading" id="result">Result: </div>

</div>

In .js file:

const playerHeading = document.getElementById('player');
const computerHeading = document.getElementById('computer');
const resultHeading = document.getElementById('result')
const options = document.querySelectorAll('.option')

let playerChoice;
let computerChoice;
let gameResult;

options.forEach(option => option.addEventListener('click', () => {
playerChoice = option.innerHTML;
computer();
playerHeading.innerHTML = `You picked ${playerChoice}`;
computerHeading.innerHTML = `Computer picked ${computerChoice}`;
resultHeading.innerHTML = checkWinner();
}))

function computer() {
const randomNumber = Math.floor(Math.random() * 3) + 1;

switch (randomNumber) {
case 1:
computerChoice = "🪨";
break;
case 2:
computerChoice = "📃";
break;
case 3:
computerChoice = "✂";
break;
}
}

function checkWinner() {
if (playerChoice == computerChoice) {
return "No winners this time. It's a tie!";
}
else if (computerChoice == "🪨") {
return (playerChoice == "📃") ? "Congratulations! You win!" : "Sorry! You lose!";
}
else if (computerChoice == "📃") {
return (playerChoice == "✂") ? "Congratulations! You win!" : "Sorry! You lose!"
}
else if (computerChoice == "✂") {
return (playerChoice == "🪨") ? "Congratulations! You win!" : "Sorry! You lose!"
}
}

Illustration for the Rock Paper Scissors Game (JavaScript)
People illustrations by Storyset

Comments (0)


Be the first to leave a comment