0% found this document useful (0 votes)
12 views2 pages

Script Rock, Paper, Scissor

This document contains JavaScript code for a rock-paper-scissors game. It tracks user and computer scores, generates random computer choices, and determines the winner based on user input. The game displays messages and updates scores accordingly after each round.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views2 pages

Script Rock, Paper, Scissor

This document contains JavaScript code for a rock-paper-scissors game. It tracks user and computer scores, generates random computer choices, and determines the winner based on user input. The game displays messages and updates scores accordingly after each round.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

let userScore = 0;

let compScore = 0;

const choices = document.querySelectorAll(".choice");


const msg = document.querySelector("#msg");

const userScorePara = document.querySelector("#user-score");


const compScorePara = document.querySelector("#comp-score");

const genCompChoice = () => {


const options = ["rock", "paper", "scissors"];
const randIdx = Math.floor(Math.random() * 3);
return options[randIdx];
};

const drawGame = () => {


msg.innerText = "Game was Draw. Play again.";
msg.style.backgroundColor = "#081b31";
};

const showWinner = (userWin, userChoice, compChoice) => {


if (userWin) {
userScore++;
userScorePara.innerText = userScore;
msg.innerText = `You win! Your ${userChoice} beats ${compChoice}`;
msg.style.backgroundColor = "green";
} else {
compScore++;
compScorePara.innerText = compScore;
msg.innerText = `You lost. ${compChoice} beats your ${userChoice}`;
msg.style.backgroundColor = "red";
}
};

const playGame = (userChoice) => {


//Generate computer choice
const compChoice = genCompChoice();

if (userChoice === compChoice) {


//Draw Game
drawGame();
} else {
let userWin = true;
if (userChoice === "rock") {
//scissors, paper
userWin = compChoice === "paper" ? false : true;
} else if (userChoice === "paper") {
//rock, scissors
userWin = compChoice === "scissors" ? false : true;
} else {
//rock, paper
userWin = compChoice === "rock" ? false : true;
}
showWinner(userWin, userChoice, compChoice);
}
};

choices.forEach((choice) => {
choice.addEventListener("click", () => {
const userChoice = choice.getAttribute("id");
playGame(userChoice);
});
});

You might also like