Rock Paper Scissors: How can I disable buttons to end game? - javascript

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.

Related

How I make my function in a rock, pepper, scissors game wait for a button press in Javascript?

So I have this code(I added the whole JS code but the part I want help is in the function game) that simply runs 5 rounds of a game of rock, papper, scissors with a press of a button in my html file.
The thing is that each round I want the function to wait for a button click of any of the three buttons (rock, papper or scissors)
I will appriciate any help, thank you and have a nice day!
let rock = "Rock";
let papper = "Papper";
let scissors = "Scissors";
let wins = 0;
let playerSelection;
const btnrock = document.getElementById('btn1');
const btnpapper = document.getElementById('btn2');
const btnscissors = document.getElementById('btn3');
const btnplay = document.getElementById('game')
function getPlayerChoice() {
btnrock.addEventListener('click', () => {
playerSelection = rock;
return playerSelection;
});
btnpapper.addEventListener('click', () => {
playerSelection = papper;
return playerSelection;
});
btnscissors.addEventListener('click', () => {
playerSelection = scissors;
return playerSelection;
});
}
btnplay.addEventListener('click', game)
function getComputerChoice() {
let min = Math.ceil(0);
let max = Math.floor(2);
let random = Math.floor(Math.random() * (max - min + 1) + min);
if (random == 0)
{
return rock;
}
if (random == 1){
return papper;
}
if (random == 2){
return scissors;
}
}
function playRound(playerSelection,pcChoice) {
if(pcChoice == rock && playerSelection == papper) {
wins++;
return "Player Wins!";
}
else if (pcChoice == rock && playerSelection == scissors) {
return "Player Loses!"
}
else if (pcChoice == scissors && playerSelection == rock){ wins++; return "Player Wins!"}
else if (pcChoice == scissors && playerSelection == papper){return "Player Loses!"}
else if (pcChoice == papper && playerSelection == rock){return "Player Loses!"}
else if (pcChoice == papper && playerSelection == scissors){wins++; return "Player Wins!"}
else {return "It's a Draw!"}
}
function game() {
for(let i = 0; i < 5; i++){
const pcChoice = getComputerChoice();
playerSelection = getPlayerChoice(); // I want this to wait
console.log("PC "+ pcChoice );
console.log('Player '+playerSelection);
let roundwinner = playRound(playerSelection,pcChoice);
console.log(roundwinner);
if(i === 2 && wins == 0){
break;
}
if(i === 3 && wins <= 1) {
break;
}
if(wins==3){
break;
}
}
if(wins >= 3) {
console.log("You are the winner of this match")
}
else {console.log('You lost the game');}
}
getPlayerChoice doesn't really get the player's choice - it adds event listeners. Run it 5 times and you get 5 listeners hooked up to the same event. I don't think you can wait for an event to fire in a loop like you're currently trying to. This would be a perfectly fine design in a console app when you want some input from the user, but in JS when working with events you have to leverage the events to execute your game's logic.
In other words, you might want to get rid of the for loop and consider moving that logic to event chain with a listener that first adds the user's input to the board and then executes the follow logic - e.g. gets the computer choice or determines whether the game is finished or not.

How do add a reset button to a Rock Paper Scissors game?

I'm learning JavaScript and having an issue trying to make a reset button for my game.
Im assuming the way I have coded it has scope tripping me up. any pointers would help immensely.
I have tried but the best i managed was to make the current score say 0 upon clicking the button, but if rock, paper or scissors were selected again, the score would jump straight back to where it was before + the result of the current round.
here is my code:
let userScore = 0;
let computerScore = 0;
let choice = document.querySelector("#selections");
choice.addEventListener("click", event => {
if (event.target.nodeName == "BUTTON") {
let playerSelecion = (event.target.textContent);
let computerSelection = getCompChoice();
document.getElementById("player").innerHTML = playerSelecion;
document.getElementById("computer").innerHTML = computerSelection;
playRound(playerSelecion, computerSelection);
}
});
function playRound(playerSelecion, computerSelection) {
if (playerSelecion === computerSelection) {
document.getElementById("currentRound").innerHTML = ("tie");
} else if (playerSelecion === "rock" && computerSelection === "scissors") {
userScore++;
document.getElementById("currentRound").innerHTML = ("you win rock beats scissors");
} else if (playerSelecion === "paper" && computerSelection === "rock") {
userScore++
document.getElementById("currentRound").innerHTML = ("you win paper beats rock")
} else if (playerSelecion === "scissors" && computerSelection === "paper") {
userScore++
document.getElementById("currentRound").innerHTML = ("you win scissors beats paper")
} else if (playerSelecion === "paper" && computerSelection === "scissors") {
computerScore++
document.getElementById("currentRound").innerHTML = ("you lose scissors beats paper")
} else if (playerSelecion === "rock" && computerSelection === "paper") {
computerScore++
document.getElementById("currentRound").innerHTML = ("you lose paper beats rock")
} else if (playerSelecion === "scissors" && computerSelection === "rock") {
computerScore++
document.getElementById("currentRound").innerHTML = ("you lose rock beats scissors")
} if (userScore >= 5) {
document.getElementById("result").innerHTML = "You win";
} else if (computerScore >= 5) {
document.getElementById("result").innerHTML = "Computer wins";
}
document.getElementById("userScore").innerHTML = userScore;
document.getElementById("compScore").innerHTML = computerScore;
}
function getCompChoice() {
let a = Math.random();
if (a < 0.34) {
return "rock";
} else if (a <= 0.67) {
return "paper";
} else {
return "scissors";
}
}```
To avoid the previous results to be added with the new score, the scores should be set to 0 in your reset button too.
//create a reset button
<button onclick="resetScore()"> Reset The Game </button>
//reset function
const reset = () => {
useScore = 0;
computerScore = 0;
document.querySelector("#userScore").innerHTML = userScore;
document.querySelector("#compScore").innerHTML = computerScore;
}
I think you want a reset button in your game that should set user and comp score to "0".
You can make a button and add some reset code to that so that when someone clicks on the button the game will reset the user and comp score to "0":
//adding a reset button
<button onclick="reset()">Reset</button>//remember to put () here
//normal function
function reset(){
document.getElementById("userScore").innerHTML = 0;
document.getElementById("compScore").innerHTML = 0;
}
//with arrow function
let reset=()=>{
document.getElementById("userScore").innerHTML = 0;
document.getElementById("compScore").innerHTML = 0;
}

how can i get what is being assigned to a variable with textContent to act as an argument for my player input in javascript?

i'm currently working on a javascript project where i create an ui for my rock, paper, scissors game which as of now only plays in the console and takes the player input for a prompt.
so far, i've created three buttons(one for rock, paper, and scissors). i've added an event listener to those buttons that listen for a click. i've also assigned that button.textContent to a variable buttonText in that event listener function. outside of that event listener function, i've declared the variable buttonText in the global scope and left it blank. in my playRound function that looks for two arguments(computerSelection and playerSelection), i've assigned buttonText to the playerSelection argument.
i'm not sure if what i did is correct and i'm just not calling my game to run correctly or if i need to rethink how to assign my playerSelection to be what is outputting for my button.textContent.
i have commented out parts of my code as my current assignment says "For now, remove the logic that plays exactly five rounds." until i get my core function to work before adding it back in.
this is my javascript code:
// DECLARES THE CHOICES FOR ANSWERS, PLAYER SCORE, COMPUTER SCORE, AND SETS BOTH SCORES TO 0.
const choices = ['rock', 'paper', 'scissors'];
let playerScore = 0;
let computerScore = 0;
// FUNCTION TO RANDOMIZE THE ANSWER FOR computerSelection.
function computerPlay() {
return choices[~~(Math.random() * choices.length)]
}
// DECLARES VARIABLE FOR BUTTONTEXT, PLAYER SELECTION, AND COMPUTER SELECTION IN THE GLOBAL SCOPE.
let buttonText = '';
let playerSelection = '';
let computerSelection = computerPlay();
// FUNCTION THAT PLAYS A ROUND, CHECKS ANSWERS TO SEE WHO WON THE ROUND, AND RETURNS A MESSAGE-
// -STATING WHO WON THE ROUND.
function playRound(playerSelection, computerSelection) {
// playerSelection = prompt('rock, paper, or scissors?').toLowerCase();
playerSelection = buttonText;
computerSelection = computerPlay();
if (playerSelection === computerSelection) {
return 'you tied';
} else if (computerSelection === 'paper' && playerSelection === 'rock') {
computerScore++;
return 'you lose, paper beats rock! ):';
} else if (computerSelection === 'scissors' && playerSelection === 'paper') {
computerScore++;
return 'you lose, scissors beats paper! ):';
} else if (computerSelection === 'rock' && playerSelection === 'scissors') {
computerScore++;
return 'you lose, rock beats scissors! ):';
} else if (computerSelection === 'rock' && playerSelection === 'paper') {
playerScore++;
return 'you win, paper beats rock! (:';
} else if (computerSelection === 'paper' && playerSelection === 'scissors') {
playerScore++;
return 'you win, scissors beats paper! (:';
} else if (computerSelection === 'scissors' && playerSelection === 'rock') {
playerScore++;
return 'you win, rock beats scissors! (:';
} else {
return 'that\'s not an acceptable answer!'
}
}
const buttons = document.querySelectorAll('button');
buttons.forEach((button) => {
button.addEventListener('click', () => {
let buttonText = button.textContent;
console.log(buttonText);
})
})
// LOGIC THAT PLAYS 5 ROUNDS OF THE GAME
// function game() {
// console.log(playRound(playerSelection, computerSelection));
// if (playerScore < 5 && computerScore < 5) {
// game();
// } else {
// endGame();
// }
// }
// FUNCTION THAT ENDS THE GAME AND DECLARES THE WINNER
// function endGame() {
// if (playerScore > computerScore) {
// console.log('you win! (:')
// } else if (computerScore > playerScore) {
// console.log('you lose! ):');
// }
// }
// console.log(buttonText);
playRound(playerSelection, computerSelection);
console.log(playRound(playerSelection, computerSelection));
// CALLS THE FUNCTION TO PLAY THE GAME
// game();
here is the code for my html's body that contains my buttons:
<body>
<button id="rock">rock</button>
<button id="paper">paper</button>
<button id="scissors">scissors</button>
<script src="index.js"></script>
</body>
You can use the event from the eventListener to know which button was clicked.
button.addEventListener('click', (event) => {
let buttonText = event.target.textContent;
console.log(buttonText);
})

How do you display a counter variable inside a div?

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) => {
...

Javascript game, connecting button as input

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) {
// ....
}

Categories

Resources