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>
Related
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>
I'm trying to understand why my code works well on Firefox and not on Chrome.
Basically what happens is that on Firefox the loop works and it prints the outputs on the page at every iteration and at the end.
On Chrome it only prints some of the outputs at the end of the loop.
I read that it might have to do with the way I'm asking the code to print the output on the page, which is .textContent, but I also tried to use .innerHtml and the problem persists.
The code is a bit long and I'm sure there is a shorter cleaner way to write, but it is my first project and this is the best I could do at this stage.
Thank you for your help :)
Here is what the html looks like:
const forma = document.querySelector('form');
const out0 = document.getElementById('user-choice');
const out1 = document.getElementById('computer-choice');
const out2 = document.getElementById('game-result');
const out3 = document.getElementById('user-score');
const out4 = document.getElementById('computer-score');
const out5 = document.getElementById('final-result');
// get a ramdom choice between Rock-paper-scissor from Computer
let choices = ['rock', 'paper', 'scissors'];
let randomValue = function computerPlay() {
let randomChoice = choices[Math.floor(Math.random() * choices.length)];
out1.textContent = randomChoice;
return randomChoice;
};
function game() {
let userScore = 0;
let computerScore = 0;
// iterate the function playRound 5 times with a for loop
for (let i = 0; i < 5; i++) {
// prompt an initial message "Rock, paper, scissor" to ask the user to input one of the 3
let sign = prompt("Rock, paper or scissors?");
// use a function to compare the random choice from computer with what the user has input in the prompt and return a result
function playRound(playerSelection, computerSelection) {
if (playerSelection == "rock" && computerSelection == choices[0]) {
i = i -1;
return "It's a tie! Play again!";
} else if (playerSelection == "rock" && computerSelection == choices[1]) {
computerScore = computerScore + 1;
out4.textContent = computerScore;
// this is when the computer wins
if(computerScore == 3) {
i = 5; // so that it practically breaks out of the loop
out5.textContent = "Unfortunately you lost the game :("
} else return "You lose this round! Paper beats rock.";
} else if (playerSelection == "rock" && computerSelection == choices[2]) {
userScore = userScore + 1;
out3.textContent = userScore;
if(userScore == 3) {
i = 5;
out5.textContent = "Congratulations, you won the game!"
} else return "You win this round! Rock beats scissors.";
} else if (playerSelection == "paper" && computerSelection == choices[0]) {
userScore = userScore + 1;
out3.textContent = userScore;
if(userScore == 3) {
i = 5;
out5.textContent = "Congratulations, you won the game!"
} else return "You win this round! Paper beats rock.";
} else if (playerSelection == "paper" && computerSelection == choices[1]) {
i = i -1;
return "It's a tie! Play again!";
} else if (playerSelection == "paper" && computerSelection == choices[2]) {
computerScore = computerScore + 1;
out4.textContent = computerScore;
if (computerScore == 3) {
i = 5;
out5.textContent = "Unfortunately you lost the game :("
} else return "You lose this round! Scissors beat paper.";
} else if (playerSelection == "scissors" && computerSelection == choices[0]) {
computerScore = computerScore + 1;
out4.textContent = computerScore;
if (computerScore == 3) {
i = 5;
out5.textContent = "Unfortunately you lost the game :("
} else return "You lose this round! Rock beats scissors.";
} else if (playerSelection == "scissors" && computerSelection == choices[1]) {
userScore = userScore + 1;
out3.textContent = userScore;
if(userScore == 3) {
i = 5;
out5.textContent = "Congratulations, you won the game!"
} else return "You win this round! Scissors beat paper.";
} else if (playerSelection == "scissors" && computerSelection == choices[2]) {
i = i -1;
return "It's a tie! Play again!";
// this currently doesn't work as it tries to convert the playerSelection toLowerCase, as requested in the let playerSelection = sign.toLowerCase(), but it cannot because the sign is null and so it returns an error that sign is null
} else if(playerSelection === '' || playerSelection === null) {
i = 0;
} else {
i = i -1;
return "I think you forgot how to play this game!";
}
}
// store the playerSelection argument value (equal to user input made lower case) in a variable
let playerSelection = sign.toLowerCase();
// store the computerSelection argument value (equal to radom choice determined by function randomValue) in a variable
let computerSelection = randomValue();
// print the user input made to lower case in the paragraph tag
out0.textContent = sign;
// print the return statement from the function in the out2 tag
out2.textContent= playRound(playerSelection, computerSelection);
}
}
// run the function
game();
And this is my Html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>
<form>
<strong>Your choice:</strong>
<output type="text" id="user-choice"></output>
</form>
</div>
<div>
<form>
<strong>Computer choice:</strong>
<output type="text" id="computer-choice"></output>
</form>
</div>
<div>
<form>
<strong>Result of this round:</strong>
<output type="text" id="game-result"></output>
</form>
</div>
<div>
<form>
<strong>User score:</strong>
<output type="number" id="user-score"></output>
</form>
</div>
<div>
<form>
<strong>Computer score:</strong>
<output type="number" id="computer-score"></output>
</form>
</div>
<div>
<form>
<strong>Game result:</strong>
<output type="text" id="final-result"></output>
</form>
</div>
<script src="script.js"></script>
</body>
</html>
You can use window.requestAnimationFrame to force the browser to render something. You will need to promisify it however, because requestAnimationFrame has a callback, and does not directly return a promise.
After doing that, your code should look like this:
const forma = document.querySelector('form');
const out0 = document.getElementById('user-choice');
const out1 = document.getElementById('computer-choice');
const out2 = document.getElementById('game-result');
const out3 = document.getElementById('user-score');
const out4 = document.getElementById('computer-score');
const out5 = document.getElementById('final-result');
// get a ramdom choice between Rock-paper-scissor from Computer
let choices = ['rock', 'paper', 'scissors'];
let userScore = 0;
let computerScore = 0;
let randomValue = function computerPlay() {
let randomChoice = choices[Math.floor(Math.random() * choices.length)];
out1.textContent = randomChoice;
return randomChoice;
};
async function game() {
// iterate the function playRound 5 times with a for loop
for (let i = 0; i < 5; i++) {
// prompt an initial message "Rock, paper, scissor" to ask the user to input one of the 3
let sign = prompt("Rock, paper or scissors?");
// use a function to compare the random choice from computer with what the user has input in the prompt and return a result
function playRound(playerSelection, computerSelection) {
if (playerSelection == "rock" && computerSelection == choices[0]) {
i = i - 1;
return "It's a tie! Play again!";
} else if (playerSelection == "rock" && computerSelection == choices[1]) {
computerScore = computerScore + 1;
out4.textContent = computerScore;
// this is when the computer wins
if (computerScore == 3) {
i = 5; // so that it practically breaks out of the loop
out5.textContent = "Unfortunately you lost the game :("
} else return "You lose this round! Paper beats rock.";
} else if (playerSelection == "rock" && computerSelection == choices[2]) {
userScore = userScore + 1;
out3.textContent = userScore;
if (userScore == 3) {
i = 5;
out5.textContent = "Congratulations, you won the game!"
} else return "You win this round! Rock beats scissors.";
} else if (playerSelection == "paper" && computerSelection == choices[0]) {
userScore = userScore + 1;
out3.textContent = userScore;
if (userScore == 3) {
i = 5;
out5.textContent = "Congratulations, you won the game!"
} else return "You win this round! Paper beats rock.";
} else if (playerSelection == "paper" && computerSelection == choices[1]) {
i = i - 1;
return "It's a tie! Play again!";
} else if (playerSelection == "paper" && computerSelection == choices[2]) {
computerScore = computerScore + 1;
out4.textContent = computerScore;
if (computerScore == 3) {
i = 5;
out5.textContent = "Unfortunately you lost the game :("
} else return "You lose this round! Scissors beat paper.";
} else if (playerSelection == "scissors" && computerSelection == choices[0]) {
computerScore = computerScore + 1;
out4.textContent = computerScore;
if (computerScore == 3) {
i = 5;
out5.textContent = "Unfortunately you lost the game :("
} else return "You lose this round! Rock beats scissors.";
} else if (playerSelection == "scissors" && computerSelection == choices[1]) {
userScore = userScore + 1;
out3.textContent = userScore;
if (userScore == 3) {
i = 5;
out5.textContent = "Congratulations, you won the game!"
} else return "You win this round! Scissors beat paper.";
} else if (playerSelection == "scissors" && computerSelection == choices[2]) {
i = i - 1;
return "It's a tie! Play again!";
// this currently doesn't work as it tries to convert the playerSelection toLowerCase, as requested in the let playerSelection = sign.toLowerCase(), but it cannot because the sign is null and so it returns an error that sign is null
} else if (playerSelection === '' || playerSelection === null) {
i = 0;
} else {
i = i - 1;
return "I think you forgot how to play this game!";
}
}
// store the playerSelection argument value (equal to user input made lower case) in a variable
let playerSelection = sign.toLowerCase();
// store the computerSelection argument value (equal to radom choice determined by function randomValue) in a variable
let computerSelection = randomValue();
// print the user input made to lower case in the paragraph tag
out0.textContent = sign;
// print the return statement from the function in the out2 tag
out2.textContent = playRound(playerSelection, computerSelection);
await promisifiedRequestAnimationFrame();
}
}
function promisifiedRequestAnimationFrame() {
return new Promise((resolve, reject) => {
window.requestAnimationFrame(() => {resolve()});
})
}
// run the function
game();
So what exactly changed?
We added a function, that returns a promise that resolves when the requestAnimationFrame is finished executing.
We made game() asynchronous. This allows us to use "await"
But why does it work?
Well, alerts, prompts and confirms are supposed to halt the code until a user does something. Firefox does not allow direct spamming of them, so there is a small time frame between your prompts on FF, but Chrome doesn't really care about that. You want a lot of prompts? Fine! By using window.requestAnimationFrame combined with await we will force chrome to wait until a frame has been drawn.
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();
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.
Hello I'm working on Rock,Paper and Scissors project. I'm stuck at this problem. I don't know how to assign value to variable using DOM. When user clicks rock button the value of rocks hould be passed to variable and the variable should be used in playRound function. I don't understand how to fix the problem. When I click to button nothing works.
//Gives the random item to item var
function computerPlay() {
const theArr = ["rock", "paper", "scissors"];
var item = theArr[Math.floor(Math.random() * 3)];
return item;
}
//Returns players selection
function playerPlay(e) {
var pItem = e;
console.log(`${e}`);
return pItem;
}
var r = document.querySelector('.rock').addEventListener('click', playerPlay);
var p = document.querySelector('.paper').addEventListener('click', playerPlay);
var s = document.querySelector('.scissors').addEventListener('click', playerPlay);
var play = document.querySelector('.playbtn').addEventListener('click', playRound);
function playRound(playerSelection, computerSelection) {
playerSelection = playerPlay();
computerSelection = computerPlay();
if (playerSelection == 'rock' && computerSelection == 'paper' || playerSelection == 'paper' && computerSelection == 'scissors' ||
playerSelection == 'scissors' && computerSelection == 'rock') {
window.alert(`${computerSelection} beats ${playerSelection} YOU LOST!`);
} else if (playerSelection == computerSelection) {
window.alert(`${computerSelection} and ${playerSelection} it is a DRAW!`);
} else {
window.alert(`${playerSelection} beats ${computerSelection} YOU WIN!!!`);
}
}
<div class="buttons">
<button class="rock">ROCK</button>
<button class="paper">PAPER</button>
<button class="scissors">SCISSORS</button>
</div>
<div class="play-btn">
<button class="playbtn">PLAY</button>
</div>
</div>
</div>
You're not fetching the player's selection anywhere, and calling playerPlay() manually does not work, because it is supposed to be a callback.
I changed your code a little and the play button can be removed because it is kind of ambiguous. Try this out:
function computerPlay() {
const theArr = ["rock", "paper", "scissors"];
var item = theArr[Math.floor(Math.random() * 3)];
return item;
}
//Returns players selection
function playerPlay(e) {
var playerSelection = e.srcElement.classList[0];
console.log(playerSelection);
computerSelection = computerPlay();
if (playerSelection == 'rock' && computerSelection == 'paper' || playerSelection == 'paper' && computerSelection == 'scissors' || playerSelection == 'scissors' && computerSelection == 'rock') {
window.alert(`${computerSelection} beats ${playerSelection} YOU LOST!`);
} else if (playerSelection == computerSelection) {
window.alert(`${computerSelection} and ${playerSelection} it is a DRAW!`);
} else {
window.alert(`${playerSelection} beats ${computerSelection} YOU WIN!!!`);
}
}
var r = document.querySelector('.rock').addEventListener('click', playerPlay);
var p = document.querySelector('.paper').addEventListener('click', playerPlay);
var s = document.querySelector('.scissors').addEventListener('click', playerPlay);