I am learning the basics of JavaScript and am working on a rock paper scissors game but can't seem to get the scores or the main prompt to update. Is there something specific that needs updating or is the JavaScript just written incorrectly? I took a tutorial I found and followed that but changed it to fit my project so I am thinking I possibly just didn't adapt the code properly.
const game = () => {
let pScore = 0;
let cScore = 0;
//play match
const playMatch = () => {
const options = document.querySelectorAll(".controls button");
const playerHand = document.querySelector(".player-hand");
const compHand = document.querySelector(".comp-hand");
const hands = document.querySelectorAll(".hands img");
hands.forEach(hand => {
hand.addEventListener("animationend", function() {
this.style.animation = "";
});
});
//Computer Options
const compOptions = ["rock", "paper", "scissors"];
options.forEach(option => {
option.addEventListener("click", function() {
//Computer choice
const compNumber = Math.floor(Math.random() * 3);
const compChoice = compOptions[compNumber];
setTimeout(() => {
//Here is where we call compare hands
compareHands(this.textContent, compChoice);
//Update images
playerHand.src = `https://via.placeholder.com/50/0000ff`;
compHand.src = `https://via.placeholder.com/50/ff0000`;
}, 1000);
// Animation
playerHand.style.animation = 'shakePlayer 1s ease';
compHand.style.animation = 'shakeComputer 1s ease'
});
});
};
const updateScore = () => {
const playerScore = document.querySelector(".player-score p");
const compScore = document.querySelector(".comp-score p");
playerScore.textContent = pScore;
compScore.textContent = cScore;
};
const compareHands = (playerChoice, compChoice) => {
//Update text
const winner = document.querySelector(".title");
//We are checking for a tie
if (playerChoice === compChoice) {
winner.textContent = 'Tie';
return;
}
//check for ROCK
if (playerChoice === "rock") {
if (compChoice === "scissors") {
winner.textContent = "Player Wins";
pScore++;
updateScore();
return;
} else {
winner.textContent = "Computer Wins";
cScore++;
updateScore();
return;
}
}
//Check for PAPER
if (playerChoice === "paper") {
if (compChoice === "scissors") {
winner.textContent = "Computer Wins";
cScore++;
updateScore();
return;
} else {
winner.textContent = "Player Wins";
pScore++;
updateScore();
return;
}
}
//check for SCISSORS
if (playerChoice === "scissors") {
if (compChoice === "rock") {
winner.textContent = "Computer Wins";
cScore++;
updateScore();
return;
} else {
winner.textContent = "Player Wins";
pScore++;
updateScore();
return;
}
}
};
playMatch();
};
//start the game function
game();
<section class="game grid">
<h2 class="title">A Simple Game of Choice...</h2>
<div class="scores grid">
<div class="player-score">
<h3>Player:</h3>
<p>0</p>
</div>
<div class="comp-score">
<h3>Computer:</h3>
<p>0</p>
</div>
</div>
<div class="hands grid">
<img class="player-hand" src="https://via.placeholder.com/50" alt="image of a hand forming a rock">
<img class="comp-hand" src="https://via.placeholder.com/50" alt="image of a hand forming a rock">
</div>
<div class="controls grid">
<button class="rock">ROCK</button>
<button class="paper">PAPER</button>
<button class="scissors">SCISSORS</button>
</div>
</section>
It's because your text values in the buttons are uppercase, whereas the comp values are all lowercase.
You can either change their case in the buttons, or in javascript convert to lowercase.
const game = () => {
let pScore = 0;
let cScore = 0;
//play match
const playMatch = () => {
const options = document.querySelectorAll(".controls button");
const playerHand = document.querySelector(".player-hand");
const compHand = document.querySelector(".comp-hand");
const hands = document.querySelectorAll(".hands img");
hands.forEach(hand => {
hand.addEventListener("animationend", function(){
this.style.animation = "";
});
});
//Computer Options
const compOptions = ["rock", "paper", "scissors"];
options.forEach(option => {
option.addEventListener("click", function() {
//Computer choice
const compNumber = Math.floor(Math.random() * 3);
const compChoice = compOptions[compNumber];
setTimeout(() => {
//Here is where we call compare hands
compareHands(this.textContent.toLowerCase(), compChoice);
//Update images
console.log("compareHands a", this.textContent);
console.log("compareHands b", compChoice);
playerHand.src = `./img/${this.textContent}.png`;
compHand.src = `./img/${compChoice}.png`;
}, 1000);
// Animation
playerHand.style.animation = 'shakePlayer 1s ease';
compHand.style.animation = 'shakeComputer 1s ease'
});
});
};
const updateScore = () => {
console.log("updateScore");
const playerScore = document.querySelector(".player-score p");
const compScore = document.querySelector(".comp-score p");
playerScore.textContent = pScore;
compScore.textContent = cScore;
console.log("pScore", pScore);
};
const compareHands = (playerChoice, compChoice) => {
//Update text
const winner = document.querySelector(".title");
//We are checking for a tie
if(playerChoice === compChoice) {
winner.textContent = 'Tie';
return;
}
//check for ROCK
if(playerChoice === "rock") {
if(compChoice === "scissors") {
winner.textContent = "Player Wins";
pScore++;
updateScore();
return;
} else {
winner.textContent = "Computer Wins";
cScore++;
updateScore();
return;
}
}
//Check for PAPER
if (playerChoice === "paper") {
if (compChoice === "scissors") {
winner.textContent = "Computer Wins";
cScore++;
updateScore();
return;
} else {
winner.textContent = "Player Wins";
pScore++;
updateScore();
return;
}
}
//check for SCISSORS
if (playerChoice === "scissors") {
if (compChoice === "rock") {
winner.textContent = "Computer Wins";
cScore++;
updateScore();
return;
} else {
winner.textContent = "Player Wins";
pScore++;
updateScore();
return;
}
}
};
playMatch();
};
//start the game function
game();
<body>
<section class="game grid">
<h2 class="title">A Simple Game of Choice...</h2>
<div class="scores grid">
<div class="player-score">
<h3>Player:</h3>
<p>0</p>
</div>
<div class="comp-score">
<h3>Computer:</h3>
<p>0</p>
</div>
</div>
<div class="hands grid">
<img class="player-hand" src="/img/rock.png" alt="image of a hand forming a rock">
<img class="comp-hand" src="/img/rock.png" alt="image of a hand forming a rock">
</div>
<div class="controls grid">
<button class="rock">ROCK</button>
<button class="paper">PAPER</button>
<button class="scissors">SCISSORS</button>
</div>
</section>
</body>
Related
So here is my javascript code for rock-paper-scissors game for TOP(I know the code
is not very tidy, I am new to coding). I have a problem with the score. I have a player score and a computer score. It should go up 1 point according to the winner, but sometimes it goes up 2 points and sometimes it goes up both for the player and the computer.
function getComputerChoice() {
let items = ["rock", "paper", "scissors"];
const randomitem = items[Math.floor(Math.random() * items.length)];
return randomitem;
}
playerScore = 0;
compScore = 0;
function playRound() {
const computerSelection = getComputerChoice();
if (playerSelection === computerSelection) {
return ("it is a tie!");
} else if (playerSelection == "rock" && computerSelection == "scissors") {
playerScore += 1;
return "rock beats scissors you win!";
} else if (playerSelection == "rock" && computerSelection == "paper") {
compScore += 1;
return "paper beats rock you lose!";
} else if (playerSelection == "paper" && computerSelection == "scissors") {
compScore += 1;
return "scissors beats paper you lose!";
} else if (playerSelection == "paper" && computerSelection == "rock") {
playerScore += 1;
return "paper beats rock you win!";
} else if (playerSelection == "scissors" && computerSelection == "paper") {
playerScore += 1;
return "scissors beats paper you win!";
} else if (playerSelection == "scissors" && computerSelection == "rock") {
compScore += 1;
return "rock beats scissors you lose!";
} else {
return "you should choose from rock,paper,scissors";
}
}
let rock = document.querySelector("#rock");
let paper = document.querySelector("#paper");
let scissors = document.querySelector("#scissors");
rock.addEventListener("click", event => {
playerSelection = "rock";
playRound();
let winner = playRound();
document.getElementById("winner").innerHTML = winner;
document.getElementById("player-score").innerHTML = `Player Score: ${playerScore}`;
document.getElementById("comp-score").innerHTML = `Computer Score: ${compScore}`;
});
paper.addEventListener("click", event => {
playerSelection = "paper";
playRound();
let winner = playRound();
document.getElementById("winner").innerHTML = winner;
document.getElementById("player-score").innerHTML = `Player Score: ${playerScore}`;
document.getElementById("comp-score").innerHTML = `Computer Score: ${compScore}`;
});
scissors.addEventListener("click", event => {
playerSelection = "scissors";
playRound();
let winner = playRound();
document.getElementById("winner").innerHTML = winner;
document.getElementById("player-score").innerHTML = `Player Score: ${playerScore}`;
document.getElementById("comp-score").innerHTML = `Computer Score: ${compScore}`;
});
<div class="header">
<div style="font-size:100px">choose your fighter!</div>
<div style="font-size:50px">first to score 5 points wins the game</div>
</div>
<div class="score-container">
<div id="player-score">player-score:0</div>
<div id="comp-score">comp-score:0</div>
</div>
<div class="button-container">
<button class="button" id="rock">rock</button>
<button class="button" id="paper">paper</button>
<button class="button" id="scissors">scissors</button>
</div>
<div class="winner-container">
<div id="winner"></div>
</div>
I tried to find a pattern but it seems random. Could you help me figure out why am I having this issue?
You are calling playRound twice
Call it only one time per click
function getComputerChoice() {
let items = ["rock", "paper", "scissors"];
const randomitem = items[Math.floor(Math.random() * items.length)];
return randomitem;
}
playerScore = 0;
compScore = 0;
function playRound() {
const computerSelection = getComputerChoice();
if (playerSelection === computerSelection) {
return ("it is a tie!");
} else if (playerSelection == "rock" && computerSelection == "scissors") {
playerScore += 1;
return "rock beats scissors you win!";
} else if (playerSelection == "rock" && computerSelection == "paper") {
compScore += 1;
return "paper beats rock you lose!";
} else if (playerSelection == "paper" && computerSelection == "scissors") {
compScore += 1;
return "scissors beats paper you lose!";
} else if (playerSelection == "paper" && computerSelection == "rock") {
playerScore += 1;
return "paper beats rock you win!";
} else if (playerSelection == "scissors" && computerSelection == "paper") {
playerScore += 1;
return "scissors beats paper you win!";
} else if (playerSelection == "scissors" && computerSelection == "rock") {
compScore += 1;
return "rock beats scissors you lose!";
} else {
return "you should choose from rock,paper,scissors";
}
}
let rock = document.querySelector("#rock");
let paper = document.querySelector("#paper");
let scissors = document.querySelector("#scissors");
rock.addEventListener("click", event => {
playerSelection = "rock";
let winner = playRound();
document.getElementById("winner").innerHTML = winner;
document.getElementById("player-score").innerHTML = `Player Score: ${playerScore}`;
document.getElementById("comp-score").innerHTML = `Computer Score: ${compScore}`;
});
paper.addEventListener("click", event => {
playerSelection = "paper";
let winner = playRound();
document.getElementById("winner").innerHTML = winner;
document.getElementById("player-score").innerHTML = `Player Score: ${playerScore}`;
document.getElementById("comp-score").innerHTML = `Computer Score: ${compScore}`;
});
scissors.addEventListener("click", event => {
playerSelection = "scissors";
let winner = playRound();
document.getElementById("winner").innerHTML = winner;
document.getElementById("player-score").innerHTML = `Player Score: ${playerScore}`;
document.getElementById("comp-score").innerHTML = `Computer Score: ${compScore}`;
});
<div class="header">
<div style="font-size:100px">choose your fighter!</div>
<div style="font-size:50px">first to score 5 points wins the game</div>
</div>
<div class="score-container">
<div id="player-score">player-score:0</div>
<div id="comp-score">comp-score:0</div>
</div>
<div class="button-container">
<button class="button" id="rock">rock</button>
<button class="button" id="paper">paper</button>
<button class="button" id="scissors">scissors</button>
</div>
<div class="winner-container">
<div id="winner"></div>
</div>
There seems to be a problem in the addEventListener() callbacks, you are playing the game twice.
playRound();
let winner = playRound();
Remove one function call.
Any time a function is read with Parentheses in your code, it calls the function.
playRound();
let winner = playRound();
So what's happening is the first time you call playRound(), it executes the function, but the returned value never gets stored. Within that function, it is rolling your random number, and adding score to the player, or the computer.
After that, the winner variable is declared, runs the function a second time, the function rolls and adds to the score again, and then your winner variable gets stored.
Hope this helps, this is my first time answering on SO. So if anyone has feedback, let me know.
I am trying to build a rock paper scissors game and I’m having a hard time with loops and events in JS. When I run this script, it counts userChoice as undefined. Why is the loop not waiting till I click any button?
This is part of the oddin project: Revisiting Rock Paper Scissors - Foundations Course
// Setting the game score to 0.
let userScore = 0;
let computerScore = 0;
const rock = document.querySelector('.rock');
const paper = document.querySelector('.paper');
const scissors = document.querySelector('.scissors');
// Main game function.
function game() {
for (let i = 0; i < 5; i++) {
/* Play the game 5 rounds. */
let values = ["rock", "paper", "scissors"]; /* The possibilities the computer can choose. */
let index = Math.floor(Math.random() * values.length); /* I use the random built-in function to randomly pick a value from the array. */
function getComputerChoice() { /* Function for the computer choice. */
return values[index];
}
let computerChoice = getComputerChoice();
let userChoice
rock.addEventListener("click", function() {
userChoice = 'rock';
});
paper.addEventListener("click", function() {
userChoice = 'paper';
});
scissors.addEventListener("click", function() {
userChoice = 'scissors';
});
function roundOfGame(userChoice, computerChoice) {
if (userChoice === computerChoice) {
return ("It is a tie");
} else if ((userChoice === "rock" && computerChoice === "scissor") || (userChoice === "paper" && computerChoice == "rock") || (userChoice === "scissor" && computerChoice === "paper")) {
userScore = userScore += 1;
return (`Player wins! ${userChoice} beats ${computerChoice}. User score = ${userScore} and computer score = ${computerScore}`)
} else {
computerScore = computerScore += 1;
return (`Computer wins! ${computerChoice} beats ${userChoice}. User score = ${userScore} and computer score = ${computerScore}`)
}
}
console.log(roundOfGame(userChoice, computerChoice));
}
}
game()
It's not how you usually handle user events in JavaScript. addEventListener takes a callback instead of returning for a reason. It's a non-blocking operation and by default everything after addEventListener will run immediately
To make it work as you want you can create a function like this:
function waitForClick(options) {
return new Promise(r => {
const listeners = []
options.forEach(option => {
const waitFor = () => {
r(option.value)
listeners.forEach(listener => {
listener.element.removeEventListener('click', listener.fn)
})
}
option.element.addEventListener('click', waitFor)
listeners.push({ element: option.element, fn: waitFor })
})
})
}
and than await for it:
const userChoice = await waitForClick([{
element: rock,
value: 'rock'
},
{
element: paper,
value: 'paper'
},
{
element: scissors,
value: 'scissors'
},
])
let userScore = 0;
let computerScore = 0;
const rock = document.querySelector('.rock');
const paper = document.querySelector('.paper');
const scissors = document.querySelector('.scissors');
async function game() {
for (let i = 0; i < 5; i++) {
let values = ["rock", "paper", "scissors"];
let index = Math.floor(Math.random() * values.length);
function getComputerChoice() {
return values[index];
}
let computerChoice = getComputerChoice();
const userChoice = await waitForClick([{
element: rock,
value: 'rock'
},
{
element: paper,
value: 'paper'
},
{
element: scissors,
value: 'scissors'
},
])
console.log('player', userChoice, 'computer', computerChoice)
function roundOfGame(userChoice, computerChoice) {
if (userChoice === computerChoice) {
return ("It is a tie");
} else if ((userChoice === "rock" && computerChoice === "scissors") || (userChoice === "paper" && computerChoice == "rock") || (userChoice === "scissors" && computerChoice === "paper")) {
userScore = userScore += 1;
return (`Player wins! ${userChoice} beats ${computerChoice}. User score = ${userScore} and computer score = ${computerScore}`)
} else {
computerScore = computerScore += 1;
return (`Computer wins! ${computerChoice} beats ${userChoice}. User score = ${userScore} and computer score = ${computerScore}`)
}
}
console.log(roundOfGame(userChoice, computerChoice));
}
}
game()
function waitForClick(options) {
return new Promise(r => {
const listeners = []
options.forEach(option => {
const waitFor = () => {
r(option.value)
listeners.forEach(listener => {
listener.element.removeEventListener('click', listener.fn)
})
}
option.element.addEventListener('click', waitFor)
listeners.push({
element: option.element,
fn: waitFor
})
})
})
}
<button class="rock">rock</button>
<button class="paper">paper</button>
<button class="scissors">scissors</button>
Whenever I run the code , computer-Point has score 1 before the game
started . Second issue that I couldn't figure out is that how to set a
play round for 5 set. these are the JavaScript code
describe the values
set computer choices
set check-winner Function
set Player choices
set game function
````
var playerPoint = 0;
var computerPoint = 0;
const userScore_p = document.querySelector(".human > p");
const computerScore_p = document.querySelector(".machine > p");
const result_p = document.querySelector('.result > p');
const rock = document.getElementById('rock')
const paper = document.getElementById('paper');
const scissors = document.getElementById('scissors');
const playerSelection = [rock, paper, scissors]
const weapons = ["rock", "paper", "scissors"];
// set the computer random choice
function getComputerChoice(){
const choice = weapons[Math.floor(Math.random() * weapons.length)];
return choice;
}
function checkWinner(playerSelection) {
const computerSelection = getComputerChoice();
if (playerSelection == computerSelection) {
result_p.textContent = "Tie";
}
else if ((playerSelection == "rock" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "rock")) {
result_p.textContent = "player Winnnn";
playerPoint++;
userScore_p.innerHTML = playerPoint;
} else {
result_p.textContent = "Player lost!!!!";
computerPoint++;
computerScore_p.innerHTML = computerPoint;
}
console.log(computerSelection)
console.log(playerSelection);
}
function getPlayerChoice() {
rock.addEventListener("click", function () {
checkWinner("rock");
});
paper.addEventListener("click", function() {
checkWinner("paper");
});
scissors.addEventListener("click", function() {
checkWinner("scissors")
});
}
function game() {
const computerSelection = getComputerChoice();
for (let i = 0; i < 5; i++) {
if (playerPoint > computerPoint) {
result_p.innerHTML = "you won the game"
} else if (playerPoint < computerPoint) {
result_p.innerHTML = "you lose the game"
} else {
result_p.innerHTML = "Drawwww"
}
}
}
game()
checkWinner();
getPlayerChoice();
````
The problem here is, player is not going to choose a weapon until they click on 1 of the 3 buttons, so when you call the function getPlayerChoice() it actually doesn't mean the player clicked on one of those buttons.
You should process the logics inside the checkWinner() function, which is called whenever the user clicks on a button.
let playerPoint = 0;
let computerPoint = 0;
const userScore_p = document.querySelector(".human > p");
const computerScore_p = document.querySelector(".machine > p");
const result_p = document.querySelector('.result > p');
const rock = document.getElementById('rock')
const paper = document.getElementById('paper');
const scissors = document.getElementById('scissors');
const playerSelection = [rock, paper, scissors]
rock.addEventListener("click", function() {
checkWinner("rock");
});
paper.addEventListener("click", function() {
checkWinner("paper");
});
scissors.addEventListener("click", function() {
checkWinner("scissors")
});
const weapons = ["rock", "paper", "scissors"];
// set the computer random choice
function getComputerChoice() {
const choice = weapons[Math.floor(Math.random() * weapons.length)];
return choice;
}
function checkWinner(playerSelection) {
const computerSelection = getComputerChoice();
if (playerSelection == computerSelection) {
result_p.textContent = "Tie";
} else if ((playerSelection == "rock" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "rock")) {
result_p.textContent = "player Winnnn";
playerPoint++;
userScore_p.innerHTML = playerPoint;
} else {
result_p.textContent = "Player lost!!!!";
computerPoint++;
computerScore_p.innerHTML = computerPoint;
}
console.log(computerSelection)
console.log(playerSelection);
}
<button id="rock">rock</button>
<button id="paper">paper</button>
<button id="scissors">scissors</button>
<div>
HUMAN
<div class="human">
<p>0</p>
</div>
</div>
<div>
MACHINE
<div class="machine">
<p>0</p>
</div>
</div>
<div>
RESULT
<div class="result">
<p></p>
</div>
</div>
I,n totally a beginner in javascript programming. I followed this rock paper scissors game making tutorial through youtube. But I can't make my program to restart and before that say a message showing that "Player wins!"/"Computer wins". Please give your suggestions to improve my code. The full code is provided down below:
const game = () => {
let pScore = 0;
let cScore = 0;
//Start the Game
const startGame = () => {
const playBtn = document.querySelector(".intro button");
const introScreen = document.querySelector(".intro");
const match = document.querySelector(".match");
playBtn.addEventListener("click", () => {
introScreen.classList.add("fadeOut");
match.classList.add("fadeIn");
});
};
//Play Match
const playMatch = () => {
const options = document.querySelectorAll(".options button");
const playerHand = document.querySelector(".player-hand");
const computerHand = document.querySelector(".computer-hand");
const hands = document.querySelectorAll(".hands img");
hands.forEach((hand) => {
hand.addEventListener("animationend", function () {
this.style.animation = "";
});
});
//Computer Options
const computerOptions = ["rock", "paper", "scissors"];
options.forEach((option) => {
option.addEventListener("click", function () {
//Computer Choice
const computerNumber = Math.floor(Math.random() * 3);
const computerChoice = computerOptions[computerNumber];
setTimeout(() => {
//Here is where we call compare hands
compareHands(this.textContent, computerChoice);
//Update Images
playerHand.src = `./assets/${this.textContent}.png`;
computerHand.src = `./assets/${computerChoice}.png`;
}, 2000);
//Animation
playerHand.style.animation = "shakePlayer 2s ease";
computerHand.style.animation = "shakeComputer 2s ease";
});
});
};
const updateScore = () => {
const playerScore = document.querySelector(".player-score p");
const computerScore = document.querySelector(".computer-score p");
playerScore.textContent = pScore;
computerScore.textContent = cScore;
};
const compareHands = (playerChoice, computerChoice) => {
//Update Text
const winner = document.querySelector(".winner");
//Checking for a tie
if (playerChoice === computerChoice) {
winner.textContent = "It's a tie!";
return;
}
//Check for Rock
if (playerChoice === "rock") {
if (computerChoice === "scissors") {
winner.textContent = "Player wins!";
pScore++;
updateScore();
return;
} else {
winner.textContent = "Computer wins!";
cScore++;
updateScore();
return;
}
}
//Check for Paper
if (playerChoice === "paper") {
if (computerChoice === "scissors") {
winner.textContent = "Computer wins!";
cScore++;
updateScore();
return;
} else {
winner.textContent = "Player wins!";
pScore++;
updateScore();
return;
}
}
//Check for scissors
if (playerChoice === "scissors") {
if (computerChoice === "rock") {
winner.textContent = "Computer wins!";
cScore++;
updateScore();
return;
} else {
winner.textContent = "Player wins!";
pScore++;
updateScore();
return;
}
}
};
//Is call all the inner function
startGame();
playMatch();
};
//Start the game function
game();
you can add click event listener on window and the reload the page.
window.addEventListener('click',()=>{ location.reload()})
I have tried making a function endGame() but I just can't figure out exactly what I need to do to reset everything back to 0. I've used result_p.innerHTML to change the message to say who has won the game after 5 points (user or computer) but the user can still continue after this and I'd like to actually have the game reset to 0-0. Any suggestions? Thanks
Code Below:
let userScore = 0;
let compScore = 0;
const userScore_span = document.getElementById("user-score");
const compScore_span = document.getElementById("comp-score");
// Get reference to scoreboard div
const scoreBoard_div = document.querySelector(".score-board");
const result_p = document.querySelector(".result > p");
const rock_div = document.getElementById("r");
const paper_div = document.getElementById("p");
const scissors_div = document.getElementById("s");
//Gets random selection from computer
function getComputerSelection() {
const choices=['r','p','s'];
const result = Math.floor(Math.random()*3);
return choices[result]
}
//Converts r,p,s to rock, paper, scissors for output on screen
function convertToWord(letter) {
if (letter === 'r') return "Rock";
if (letter === 'p') return "Paper";
return "Scissors";
}
function win(playerSelection, computerSelection) {
userScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (userScore < 5){result_p.innerHTML = `${convertToWord(playerSelection)} beats ${convertToWord(computerSelection)}. You win! =D`;
}else if(userScore === 5){result_p.innerHTML='Game over, you win! Refresh to play again'};
}
function lose(playerSelection, computerSelection) {
compScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (compScore<5){result_p.innerHTML = `${convertToWord(computerSelection)} beats ${convertToWord(playerSelection)}. You lose =(`;
}else if(compScore === 5){result_p.innerHTML='Game over, you lose! Refresh to play again'};
}
function draw() {
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_p.innerHTML = `It\'s a tie!`;
}
function game(playerSelection) {
const computerSelection = getComputerSelection();
if (playerSelection === computerSelection) {
draw(playerSelection, computerSelection);
} else if (playerSelection === 'r' && computerSelection === 's'){
win(playerSelection, computerSelection);
}else if (playerSelection === 'p' && computerSelection === 'r'){
win(playerSelection, computerSelection);
}else if (playerSelection === 's' && computerSelection === 'p'){
win(playerSelection, computerSelection);
}else{
lose(playerSelection, computerSelection);
}
}
function main() {
rock_div.addEventListener('click', () => game("r"));
paper_div.addEventListener('click', () => game("p"));
scissors_div.addEventListener('click', () => game("s"));
}
main ();
your score: <div id="user-score"></div> <br>
computer's score: <div id="comp-score"></div>
<div id="a1" class="score-board"></div>
<div id="a2" class="result"><p></p></div>
<button id="r">use rock</button>
<button id="p">use paper</button>
<button id="s">use scissor</button>
What should happen when the game ends?
show the result
show a button to play again
disable the RPS buttons so that user cannot continue to play
therefore, the code to end the game when score is already 5 is:
...
else if(userScore === 5){
// show the result & show a button to play again
result_p.innerHTML='Game over, you win! <button onclick="endGame()">Click here to play again</button>';
// disable the RPS buttons so that user cannot continue to play
rock_div.setAttribute("disabled", 1);
paper_div.setAttribute("disabled", 1);
scissors_div.setAttribute("disabled", 1);
};
...
What should happen when the game starts again?
reset both score to 0
display the new score to user
show blank result
reenable all the RPS buttons so that user can continue to play
therefore, the code to restart the game is:
function endGame() {
// reset both score to 0
userScore = 0;
compScore = 0;
// display the new score to user
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
// show blank result
result_p.innerHTML = ``;
// reenable all the RPS buttons so that user can continue to play
rock_div.removeAttribute("disabled");
paper_div.removeAttribute("disabled");
scissors_div.removeAttribute("disabled");
}
Here is working snippet
let userScore = 0;
let compScore = 0;
const userScore_span = document.getElementById("user-score");
const compScore_span = document.getElementById("comp-score");
// Get reference to scoreboard div
const scoreBoard_div = document.querySelector(".score-board");
const result_p = document.querySelector(".result > p");
const rock_div = document.getElementById("r");
const paper_div = document.getElementById("p");
const scissors_div = document.getElementById("s");
//Gets random selection from computer
function getComputerSelection() {
const choices=['r','p','s'];
const result = Math.floor(Math.random()*3);
return choices[result]
}
//Converts r,p,s to rock, paper, scissors for output on screen
function convertToWord(letter) {
if (letter === 'r') return "Rock";
if (letter === 'p') return "Paper";
return "Scissors";
}
function win(playerSelection, computerSelection) {
userScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (userScore < 5){result_p.innerHTML = `${convertToWord(playerSelection)} beats ${convertToWord(computerSelection)}. You win! =D`;
}else if(userScore === 5){
result_p.innerHTML='Game over, you win! <button onclick="endGame()">Click here to play again</button>'
rock_div.setAttribute("disabled", 1);
paper_div.setAttribute("disabled", 1);
scissors_div.setAttribute("disabled", 1);
};
}
function lose(playerSelection, computerSelection) {
compScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (compScore<5){result_p.innerHTML = `${convertToWord(computerSelection)} beats ${convertToWord(playerSelection)}. You lose =(`;
}else if(compScore === 5){
result_p.innerHTML='Game over, you lose! <button onclick="endGame()">Click here to play again</button>'
rock_div.setAttribute("disabled", 1);
paper_div.setAttribute("disabled", 1);
scissors_div.setAttribute("disabled", 1);
};
}
function draw() {
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_p.innerHTML = `It\'s a tie!`;
}
function game(playerSelection) {
const computerSelection = getComputerSelection();
if (playerSelection === computerSelection) {
draw(playerSelection, computerSelection);
} else if (playerSelection === 'r' && computerSelection === 's'){
win(playerSelection, computerSelection);
}else if (playerSelection === 'p' && computerSelection === 'r'){
win(playerSelection, computerSelection);
}else if (playerSelection === 's' && computerSelection === 'p'){
win(playerSelection, computerSelection);
}else{
lose(playerSelection, computerSelection);
}
}
function endGame() {
userScore = 0;
compScore = 0;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_p.innerHTML = ``;
rock_div.removeAttribute("disabled"); paper_div.removeAttribute("disabled"); scissors_div.removeAttribute("disabled");
}
function main() {
rock_div.addEventListener('click', () => game("r"));
paper_div.addEventListener('click', () => game("p"));
scissors_div.addEventListener('click', () => game("s"));
}
main ();
your score: <div id="user-score"></div> <br>
computer's score: <div id="comp-score"></div>
<div id="a1" class="score-board"></div>
<div id="a2" class="result"><p></p></div>
<button id="r">use rock</button>
<button id="p">use paper</button>
<button id="s">use scissor</button>
userScore = 0;
compScore = 0;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
I think this will be enough to "refresh" your game. So you should basically call this in lose and win functions when score of the winner is bigger than 5. Please note that the code can be refactored as you are repeating the same pattern in win and lose functions. Applying these changes, I added a refresh button, here is the code (again, note that I did not refactor the code):
let userScore = 0;
let compScore = 0;
const userScore_span = document.getElementById("user-score");
const compScore_span = document.getElementById("comp-score");
// Get reference to scoreboard div
const scoreBoard_div = document.querySelector(".score-board");
const result_p = document.querySelector(".result > p");
const rock_div = document.getElementById("r");
const paper_div = document.getElementById("p");
const scissors_div = document.getElementById("s");
//Gets random selection from computer
function getComputerSelection() {
const choices = ['r', 'p', 's'];
const result = Math.floor(Math.random() * 3);
return choices[result]
}
//Converts r,p,s to rock, paper, scissors for output on screen
function convertToWord(letter) {
if (letter === 'r') return "Rock";
if (letter === 'p') return "Paper";
return "Scissors";
}
function win(playerSelection, computerSelection) {
userScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (userScore < 5) {
result_p.innerHTML = `${convertToWord(playerSelection)} beats ${convertToWord(computerSelection)}. You win! =D`;
} else if (userScore === 5) {
result_p.innerHTML = 'Game over, you win! Refresh to play again'
endGame();
};
}
function lose(playerSelection, computerSelection) {
compScore++;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
if (compScore < 5) {
result_p.innerHTML = `${convertToWord(computerSelection)} beats ${convertToWord(playerSelection)}. You lose =(`;
} else if (compScore === 5) {
result_p.innerHTML = 'Game over, you lose! Refresh to play again'
endGame();
};
}
function draw() {
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
result_p.innerHTML = `It\'s a tie!`;
}
function game(playerSelection) {
const computerSelection = getComputerSelection();
if (playerSelection === computerSelection) {
draw(playerSelection, computerSelection);
} else if (playerSelection === 'r' && computerSelection === 's') {
win(playerSelection, computerSelection);
} else if (playerSelection === 'p' && computerSelection === 'r') {
win(playerSelection, computerSelection);
} else if (playerSelection === 's' && computerSelection === 'p') {
win(playerSelection, computerSelection);
} else {
lose(playerSelection, computerSelection);
}
}
function endGame() {
rock_div.disabled = true;
paper_div.disabled = true;
scissors_div.disabled = true;
}
function restartGame() {
restartScores();
rock_div.disabled = false;
paper_div.disabled = false;
scissors_div.disabled = false;
}
function restartScores() {
userScore = 0;
compScore = 0;
userScore_span.innerHTML = userScore;
compScore_span.innerHTML = compScore;
}
function main() {
rock_div.addEventListener('click', () => game("r"));
paper_div.addEventListener('click', () => game("p"));
scissors_div.addEventListener('click', () => game("s"));
}
main();
your score:
<div id="user-score"></div> <br> computer's score:
<div id="comp-score"></div>
<div id="a1" class="score-board"></div>
<div id="a2" class="result">
<p></p>
</div>
<button id="r">use rock</button>
<button id="p">use paper</button>
<button id="s">use scissor</button>
<button onclick="restartGame()">restart game</button>
Now when you win or lose, the game "stops", and the buttons used to play the game are disabled. When the user clicks the refresh button, the score refreshes and the buttons are again enabled.