Im building rock/paper/scissors where user plays against computer. I want to update the score after each round and display it inside a div. The code works after the 1st score, but never increments after 1.
let computerPlay = () => {
let compChoices = ["rock", "paper", "scissors"]; //array storing computer possible actions
let i = Math.floor(Math.random() * 3);
let choice = compChoices[i];
return choice;
};
//select buttons for player choice
let buttons = document.querySelectorAll(".btn");
//select elements for updating scoreboard
let homeScore = document.querySelector(".home-score");
let awayScore = document.querySelector(".away-score");
let display = document.querySelector(".score-board-display");
//declare player and computer score variables
let playerScore, compScore;
//compare player and computer selections update score of winner
let playRound = (playerSelection, computerSelection) => {
let result = ``;
playerScore = 0;
compScore = 0;
if (playerSelection === computerSelection) {
result = `Tie ${playerSelection} equals ${computerSelection}`;
} else if (
(playerSelection == "rock" && computerSelection == "scissors") ||
(playerSelection == "paper" && computerSelection == "rock") ||
(playerSelection == "scissors" && computerSelection == "paper")
) {
result = `LFG!! ${playerSelection} beats ${computerSelection}`;
playerScore += 1;
homeScore.innerText = playerScore.toLocaleString();
} else {
result = `You Lose! ${computerSelection} beats ${playerSelection}`;
}
return (display.innerHTML = result);
};
buttons.forEach((button) => {
button.addEventListener("click", () => {
let computerSelection = computerPlay();
let playerSelection = button.innerHTML.toLowerCase();
playRound(playerSelection, computerSelection);
});
});
on every playRound the playerScore is reseted / defined as 0
to solve that define playerScore as number before your playRound definition
...
let playerScore=0;
let playRound = (playerSelection, computerSelection) => {
...
Related
The game works fine after 1 round. I'm trying to play 5 rounds. I tried a for-loop before the while loop. But, it still only prompts the user for input one time.
let computerPlay = () => {
let compChoices = ["rock", "paper", "scissors"]; //array storing computer possible actions
let i = Math.floor(Math.random() * 3);
let choice = compChoices[i];
return choice;
};
//
let playerChoice = prompt("Select your action").toLowerCase();
let computerChoice = computerPlay();
let playRound = (playerSelection, computerSelection) => {
let winner = "";
if (playerSelection === computerSelection) {
winner = "tie";
} else if (playerSelection > computerSelection) {
winner = "player";
} else {
winner = "computer";
}
return console.log(winner);
};
let i = 0;
while (i < 5) {
playRound(playerChoice, computerChoice);
i++;
}
UPDATED
As requirement, author is asking to keep playerSelection and computerSelection params for playRound. I'd propose the fix is to put playerChoice and computerChoice in while loop
let computerPlay = () => {
let compChoices = ["rock", "paper", "scissors"]; //array storing computer possible actions
let i = Math.floor(Math.random() * 3);
let choice = compChoices[i];
return choice;
};
let playRound = (playerSelection, computerSelection) => {
let winner = "";
if (playerSelection === computerSelection) {
winner = "tie";
} else if (playerSelection > computerSelection) {
winner = "player";
} else {
winner = "computer";
}
return console.log(winner);
};
let i = 0;
while (i < 5) {
//here is the change
let playerChoice = prompt("Select your action").toLowerCase();
let computerChoice = computerPlay();
playRound(playerChoice, computerChoice);
i++;
}
OLD ANSWER
Your problem is you pass prompt outside of your playRound. playerSelection and computerSelection should be in playRound too that would help for resetting values of computer and your choices' every round.
let computerPlay = () => {
let compChoices = ["rock", "paper", "scissors"]; //array storing computer possible actions
let i = Math.floor(Math.random() * 3);
let choice = compChoices[i];
return choice;
};
let playRound = () => {
let playerSelection = prompt("Select your action").toLowerCase();
let computerSelection = computerPlay();
let winner = "";
if (playerSelection === computerSelection) {
winner = "tie";
} else if (playerSelection > computerSelection) {
winner = "player";
} else {
winner = "computer";
}
return console.log(winner);
};
let i = 0;
while (i < 5) {
playRound();
i++;
}
I've put playerScore and computerScore variables in global scope. When user wins or loses these values increment by one number. They do work well. But in my HTML page they do not change dynamically.
Why my playerScore and computerScore values do not change in my HTML page, when I console.log them separately in console they are changed, but not in html page. I've tried to put them in function but it didn't work as expected.
// Selecting all the items with tag button
const buttons = document.querySelectorAll('button');
// Returns random item and assignes it to computerSelection variable
function computerPlay() {
const rps = ['rock', 'paper', 'scissors'];
let numberItem = Math.floor(Math.random() * rps.length);
computerSelection = rps[numberItem];
if (computerSelection === 'rock') {
console.log('computer selections is rock');
return computerSelection;
}
else if (computerSelection === 'paper' ) {
console.log('It is a paper!');
return computerSelection;
}
console.log('it is scissors');
return computerSelection;
}
// Plays game only five rounds;
let computerScore = 0;
let playerScore = 0;
function playRound(playerSelection, computerSelection) {
if(playerScore < 5 && computerScore < 5 ) {
if(((playerSelection == 'rock') && (computerSelection == 'paper')) || ((playerSelection == 'paper') && (computerSelection == 'scissors')) ||
((playerSelection == 'scissors') && (computerSelection == 'rock') )) {
console.log(`${computerSelection} beats ${playerSelection} the ROBOT WINS!`);
playerScore++;
return console.log(playerScore);
}
else if (((playerSelection == 'rock') && (computerSelection == 'scissors')) || ((playerSelection == 'paper') && (computerSelection == 'rock')) ||
((playerSelection == 'scissors') && (computerSelection == 'paper'))) {
console.log(` ${playerSelection} beats ${computerSelection} the PLAYER WINS!`);
computerScore++;
return console.log(computerScore);
}
return console.log('It is a DRAW');;
}
return console.log("GAME OVER!!!");
}
// returns value of clicked button and plays round
function fetchButtonValue(e) {
let itemClicked = e.target.dataset.item;
console.log(` THIS WAS CLICKED ${itemClicked}`);
return playRound(itemClicked, computerPlay());
}
// uses fetchButtonValue
buttons.forEach(function(button) {
button.addEventListener('click', fetchButtonValue);
});
// implement the vlaues to HTML but they doesn't change but the value changes when tracking them in console of browser.
let score= `
<p class = 'playerPoints'>Player: ${playerScore}</p>
<p class = 'computerPoints'>Computer: ${computerScore}</p>
`;
const divScore = document.querySelector('.score');
divScore.insertAdjacentHTML('beforebegin', scoreHTML);
I want to disable the buttons after the user or computer reaches 5 points. I've been trying to remove the event listeners for the rock, paper and scissor divs where it says "if userScore===5" and "compScore===5" in the win/lose functions but it doesn't work. I've seen people disable the buttons to end the game, but my 'buttons' are images in divs that I added a click event listener to so I don't think that would work in my case.
let userScore = 0;
let compScore = 0;
const userScore_span = document.getElementById("user-score");
const compScore_span = document.getElementById("comp-score");
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';
rock_div.removeEventListener('click', () => game("r"));
paper_div.removeEventListener('click', () => game("p"));
scissors_div.removeEventListener('click', () => game("s"));
}
}
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';
rock_div.removeEventListener('click', () => game("r"));
paper_div.removeEventListener('click', () => game("p"));
scissors_div.removeEventListener('click', () => game("s"));
}
}
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);
}
}
//Links images to game play
rock_div.addEventListener('click', () => game("r"));
paper_div.addEventListener('click', () => game("p"));
scissors_div.addEventListener('click', () => game("s"));
You can "disable" the buttons by removing the event listener.
First, you need your event listener function to be a single function like this:
function handleRock() {
game("r");
}
Then, you can use addEventListener to add the listener and removeEventListener to remove it like this:
rock_div.addEventListener('click', handleRock);
// And when you're ready to disable the rock button:
rock_div.removeEventListener('click', handleRock);
NOTE: For removeEventListener to work, its arguments must be excatly the same as the arguments to addEventListener. The function must be the same function, not just an identical one.
I am creating rock paper scissors with a user interface in html/css.
I have 3 html buttons for the choices:
<div class="options">
<button class="button rock"><i class="fas fa-hand-rock fa-10x"></i>Rock</button>
<button class="button paper"><i class="fas fa-toilet-paper fa-10x"></i>Paper</button>
<button class="button scissor"><i class="fas fa-cut fa-10x"></i>Scissor</button>
</div>
My problem is connecting a click event on the buttons to input as the player selection variable in the playRound function. Can someone provide insight on how to accomplish this. I was trying to connect them in the userPlay function using event listeners. Thanks in advance.
Javascript:
// returns a random computer choice
function computerPlay() {
options = ['Rock', 'Paper', 'Scissor'];
return options[Math.floor(Math.random() * options.length)]
}
// should return a user choice
function userPlay() {
let rock = document.querySelector('.button.rock');
rock.addEventListener('click', setChoice);
let paper = document.querySelector('.button.paper');
paper.addEventListener('click', setChoice)
let scissor = document.querySelector('.button.scissor');
scissor.addEventListener('click', setChoice)
var userChoice;
function setChoice() {
userChoice=
}
return userChoice
}
function playRound() {
// defining the starting score
let playerScore = 0;
let computerScore = 0;
// play 5 times per round
for (let i = 0; i <= 4; i++) {
computerSelection = computerPlay();
playerSelection = userPlay()
// game conditionals
if (
(playerSelection === 'Rock' && computerSelection === 'Paper') ||
(playerSelection === 'Paper' && computerSelection === 'Scissor') ||
(playerSelection === 'Scissor' && computerSelection === 'Rock')
) {
computerScore++;
console.log(`Computer: ${computerSelection} You: ${playerSelection} You Lost`)
console.log(`computer: ${computerScore} You: ${playerScore}`)
}
if (
(playerSelection === 'Paper' && computerSelection === 'Rock') ||
(playerSelection === 'Scissor' && computerSelection === 'Paper') ||
(playerSelection === 'Rock' && computerSelection === 'Scissor')
) {
playerScore++;
console.log(`Computer: ${computerSelection} You: ${playerSelection} You Won`)
console.log(`computer: ${computerScore} You: ${playerScore}`)
}
if (playerSelection === computerSelection) {
console.log(`Computer: ${computerSelection} You: ${playerSelection} Its a tie`);
console.log(`computer: ${computerScore} You: ${playerScore}`);
continue
}
}
// ending score
if (computerScore > playerScore) {
console.log('Sorry, you lost')
}
if (playerScore > computerScore) {
console.log('Congrats, you won')
}
else {
'It was a tie game'
}
}
You don't want the events inside the function.
Consider using a data-attribute on the buttons and event delegations like this
<button data-shake='rock'>
.
document.addEventListener('click', function(event) {
if ( event.target.matches('button') ) {
runFunction(event.target.dataset.shake); // would get 'rock' etc...
}
});
You can use the arrow function so you'd be able to pass a parameter to the function.
(Read more about it: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#event_listener_with_an_arrow_function)
let rock = document.querySelector('.button.rock');
rock.addEventListener('click', () => {setChoice("scissor")});
let paper = document.querySelector('.button.paper');
paper.addEventListener('click', () => {setChoice("scissor")})
let scissor = document.querySelector('.button.scissor');
scissor.addEventListener('click', () => {setChoice("scissor")})
var userChoice;
function setChoice(userChoice) {
// ....
}
I'm currently learning Javascript and they want me to build a Rock, paper and scissors game.
Here's the code I have so far:
let computerPlay = (array) => {
return array[Math.floor(Math.random() *
array.length)]
}
const array = (["Rock", "Paper", "Scissors"])
console.log(computerPlay(array))
let singleRound = (playerSelection,
computerSelection) => {
if ( playerSelection == "rock" || playerSelection
== "Paper" ||
playerSelection == "scissors") {
computerSelection = computerPlay
} else if (playerSelection == null) {
"Canceled"
}
}
let playerSelection = prompt("What do you
select?")
const computerSelection = computerPlay()
Thank You
Function Definition:
let computerPlay = (array) => { //... }
Calling The Funciton:
Remember computerPlay requires an array as a parameter when you call it.
computerPlay(YOUR_ARRAY_HERE);