Why is this loop executing without me clicking any button? - javascript

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>

Related

Rock,Paper&Scissors game problem in JavaScript

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>

How to call a function inside of another function multiple times

I am creating a rock paper scissors game where I have a playRound() function. I am trying to create a game() function where I can call this playRound() function multiple times with different results.
I want to use this game() function to play multiple rounds in order to find a winner
but I am still stuck on getting the playRound() to run multiple times.
With my current code, the playRound() function only runs once in the console.
Here is my code :
function playRound(playerSelection, computerSelection) {
const lose = "You Lose! Paper beats rock";
const win = "You Win! rock beats paper";
const tie = "its a tie";
console.log(`Your selection is : ${playerSelection}`);
console.log(`PC selection is : ${computerSelection}`);
if (playerSelection === playerSelection && computerSelection === "paper") {
return lose;
} else if (
playerSelection === playerSelection &&
computerSelection === "scissors"
) {
return win;
} else {
return tie;
}
}
function game() {
for (let i = 0; i < 3; i++) {
return playRound(playerSelection, computerSelection);
}
}
function computerPlay() {
let choices = ["rock", "paper", "scissors"];
let choice = choices[Math.floor(Math.random() * choices.length)];
return choice;
}
const string = "ROck";
const playerSelection = string.toLowerCase() || string.toUpperCase();
const computerSelection = computerPlay();
console.log(game());
Not only is your game() function returning the results of the round thus leaving the loop... but you are setting the computerSelection only once... before calling the game() function.. so neither playerSelection or computerSelection ever changes.
I rearranged your code a bit and added an overall game score. Take a look.
function playRound(playerSelection, round) {
console.log("Round " + round);
const computerSelection = computerPlay();
console.log(`Your selection is : ${playerSelection}`);
console.log(`PC selection is : ${computerSelection}`);
if (playerSelection === playerSelection && computerSelection === "paper") {
return 'lose';
} else if (
playerSelection === playerSelection &&
computerSelection === "scissors"
) {
return 'win';
} else {
return 'tie';
}
}
function game() {
const lose = "You Lose! Paper beats rock";
const win = "You Win! Rock beats scissors";
const tie = "It's a tie";
let playerScore = 0;
let computerScore = 0;
for (let i = 1; i < 4; i++) {
const result = playRound(playerSelection, i);
switch (result) {
case 'win':
console.log(win);
playerScore++;
break;
case 'lose':
console.log(lose);
computerScore++;
break;
default:
console.log(tie);
playerScore++;
computerScore++;
break;
}
}
console.log("Final Results: Player: " + playerScore + " Computer: " + computerScore);
if (playerScore > computerScore) {
console.log("You win the game!");
} else if (playerScore < computerScore) {
console.log("You lose the game.");
} else {
console.log("The game was an overall tie.");
}
}
function computerPlay() {
let choices = ["rock", "paper", "scissors"];
let choice = choices[Math.floor(Math.random() * choices.length)];
return choice;
}
const playerSelection = "rock";
game();

How to restart my game in javascript when a condition is met?

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()})

How do I get my rock paper scissors game to reset after 5 wins with javascript (The Odin Project)?

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.

Rock, paper, scissors game javascript

Currently stuck with a rock, paper, scissors game in javascript. Only my last function game() which needs to play a round 5 times is not working. Have tried to work with a for loop but it seems that I'm getting 5 times the same answer instead of 5 different random ones.
Could someone please help me out?
let playerScore = 0;
let computerScore = 0;
const playerSelection = playerPlay();
const computerSelection = computerPlay();
// computer select function
function computerPlay() {
const option = ['rock', 'paper', 'scissors'];
let random = Math.floor(Math.random() * 3);
return option[random];
}
console.log('Computer: ' + computerSelection);
// player select function
function playerPlay() {
const input = prompt('Please enter input');
const option = input.toLowerCase();
return option;
}
console.log('Player: ' + playerSelection);
// play 1 single round
function playRound(playerSelection, computerSelection) {
if(playerSelection === computerSelection) {
return 'It is a tie';
}
if(playerSelection === 'rock') {
if(computerSelection === 'scissors') {
playerScore++;
return 'Player wins with rock';
} else if(computerSelection === 'paper') {
computerScore++;
return 'Computer wins with paper'
}
}
if(playerSelection === 'paper') {
if(computerSelection === 'rock') {
playerScore++;
return 'Player wins with paper';
} else if(computerSelection === 'scissors') {
computerScore++;
return 'Computer wins with scissors';
}
}
if(playerSelection === 'scissors') {
if(computerSelection === "paper") {
playerScore++;
return 'Player wins with scissors';
} else if(computerSelection === 'rock') {
computerScore++;
return 'Computer wins with rock';
}
}
}
// console.log(playRound(playerSelection, computerSelection));
playRound(playerSelection, computerSelection);
console.log('Player: ' + playerScore);
console.log('Computer: ' + computerScore);
// game
function game() {
for(var i = 1; i <= 5; i++) {
console.log('repeat 5 times');
playRound(playerSelection, computerSelection);
}
}
game();
You have put a loop without asking for the player and computer input, hence it runs 5 times without taking any input. I have fixed this in the snippet. Not entirely sure if you want to run it this way though.
let playerScore = 0;
let computerScore = 0;
// computer select function
function computerPlay() {
const option = ['rock', 'paper', 'scissors'];
let random = Math.floor(Math.random() * 3);
return option[random];
}
// player select function
function playerPlay() {
const input = prompt('Please enter input');
const option = input.toLowerCase();
return option;
}
// play 1 single round
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return 'It is a tie';
}
if (playerSelection === 'rock') {
if (computerSelection === 'scissors') {
playerScore++;
return 'Player wins with rock';
} else if (computerSelection === 'paper') {
computerScore++;
return 'Computer wins with paper'
}
}
if (playerSelection === 'paper') {
if (computerSelection === 'rock') {
playerScore++;
return 'Player wins with paper';
} else if (computerSelection === 'scissors') {
computerScore++;
return 'Computer wins with scissors';
}
}
if (playerSelection === 'scissors') {
if (computerSelection === "paper") {
playerScore++;
return 'Player wins with scissors';
} else if (computerSelection === 'rock') {
computerScore++;
return 'Computer wins with rock';
}
}
}
// console.log(playRound(playerSelection, computerSelection));
// game
function game() {
for (i = 0; i <= 5; i++) {
var playerSelection = playerPlay();
var computerSelection = computerPlay();
playRound(playerSelection, computerSelection);
console.log('Computer: ' + computerSelection);
console.log('Player: ' + playerSelection);
console.log('Player: ' + playerScore);
console.log('Computer: ' + computerScore);
}
console.log('Final Player: ' + playerScore);
console.log('Final Computer: ' + computerScore);
}
game();
Your probleme is because you're set your playerSelection and computerSelection once (and even on a const ! So choice cannot be updated)
You just have to move this part into you for loop (and update to let instead of const)
let playerSelection = playerPlay();
let computerSelection = computerPlay();
let playerScore = 0;
let computerScore = 0;
// computer select function
function computerPlay() {
const option = ['rock', 'paper', 'scissors'];
let random = Math.floor(Math.random() * 3);
return option[random];
}
// player select function
function playerPlay() {
const input = prompt('Please enter input');
const option = input.toLowerCase();
return option;
}
// play 1 single round
function playRound(playerSelection, computerSelection) {
if(playerSelection === computerSelection) {
return 'It is a tie';
}
if(playerSelection === 'rock') {
if(computerSelection === 'scissors') {
playerScore++;
return 'Player wins with rock';
} else if(computerSelection === 'paper') {
computerScore++;
return 'Computer wins with paper'
}
}
if(playerSelection === 'paper') {
if(computerSelection === 'rock') {
playerScore++;
return 'Player wins with paper';
} else if(computerSelection === 'scissors') {
computerScore++;
return 'Computer wins with scissors';
}
}
if(playerSelection === 'scissors') {
if(computerSelection === "paper") {
playerScore++;
return 'Player wins with scissors';
} else if(computerSelection === 'rock') {
computerScore++;
return 'Computer wins with rock';
}
}
}
// game
function game() {
for(var i = 1; i <= 5; i++) {
let playerSelection = playerPlay();
let computerSelection = computerPlay();
console.log(`[Play turn ${i}] Player: ${playerSelection} | Computer: ${computerSelection}`);
playRound(i);
}
}
game();
Your code has a few issues.
You don't display output of next games. They are played but result is the same. It's same game configuration repeated 5 times.
console.log('repeat 5 times');
console.log(playRound(playerSelection, computerSelection));
Instead of:
console.log('repeat 5 times');
console.log(playRound(playerSelection, computerSelection));
You run functions playerSelection, computerSelection only once. So every next play has the same result.
You should execute these functions with every loop iteration.
Example:
let playerSelection = function () {
const input = prompt('Please enter input');
const option = input.toLowerCase();
return option;
};
let computerSelection = function () {
const option = ['rock', 'paper', 'scissors'];
let random = Math.floor(Math.random() * 3);
return option[random];
};
[...]
playRound(playerSelection(), computerSelection());

Categories