Rock Paper Scissors declare winner logic - javascript

I'm trying to code a simple Rock Paper Scissors game with three images that the player clicks on to trigger an event listener and initiate the start of the game playGame().
Where I'm running into problems with my second function, declareWinner() which should evaluate the if/else statements and user and computer selection and declare the winner. I think the issue is with the userInput but I don't know what the problem is. Each time the game runs it skips to the else statement and console.logs "It's a tie.".
What am I doing wrong?
Here is my HTML and CSS
//Initialize scores to zero
let yourScore = 0;
let computerScore = 0;
let roundNum = 0;
let userInput;
let computerInput;
//Global Variables
const userRock = document.querySelector(".user-rock");
const userPaper = document.querySelector(".user-paper");
const userScissors = document.querySelector(".user-scissors");
const computerRock = document.querySelector(".computer-rock");
const computerPaper = document.querySelector(".computer-paper");
const computerScissors = document.querySelector(".computer-scissors");
const scoreUser = document.querySelector(".user-score");
const scoreComputer = document.querySelector(".computer-score");
let computerSelection = document.getElementById("computer-selection");
// Adding event listener to User icons
userRock.addEventListener("click", playGame);
userPaper.addEventListener("click", playGame);
userScissors.addEventListener("click", playGame);
// Create playGame() to start game when image is clicked
function playGame (){
let computerInput = Math.floor(Math.random() * 4);
if (computerInput === 1) {
computerInput === 'rock'
console.log ("computer chose rock");
}
if (computerInput === 2) {
computerInput === 'paper'
console.log ("computer chose paper");
}
if (computerInput === 3) {
computerInput === 'scissors'
console.log ("computer chose scissors");
}
evaluateRound(userInput, computerInput);
}
function evaluateRound(userInput, computerInput) {
if(userInput === 'rock' && computerInput === 'paper') {
console.log ('You lose! Paper beats rock!');
scoreComputer.innerHTML = scoreComputer++;
} if (userInput === 'rock' && computerInput === 'rock') {
console.log ('Its a tie!');
} if (userInput === 'rock' && computerInput === 'scissors') {
console.log ('You win! Rock beats scissors!');
scoreUser.innerHTML = scoreUser++;
// User Chooses Paper
} else if(userInput === "paper" && computerInput === 'rock') {
console.log ('You win! Rock beats paper!');
scoreUser.innerHTML = scoreUser++;
} else if (userInput === 'paper' && computerInput === 'paper') {
console.log ('Its a tie!');
} else if (userInput === 'paper' && computerInput === 'scissors') {
console.log ('You lose! Scissors beats paper!');
scoreComputer.innerHTML = scoreComputer++;
// User Chooses Scissors
} else if(userInput === "scissors" && computerInput === 'rock') {
console.log ('You lose! Rock beats scissors!');
scoreComputer.innerHTML = scoreComputer++;
} else if (userInput === 'scissors' && computerInput === 'paper') {
console.log ('You win! Scissors beats paper!');
scoreUser.innerHTML = scoreUser++;
} else {
console.log ('It"s a tie!');
}
}
and
<!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">
<link rel="stylesheet" href="index.css">
<title>Rock Paper Scissors</title>
<h1> Rock Paper Scissors</h1>
<h2> The first player to get <span>5 points</span> wins!</h2>
<p>SCORE:</p>
<div class="score-board">
<div class="computer-score">0</div>
<div class="user-score">0</div>
</div>
<div class="gameboard">
<div class="user-choices">
<div class="user-instructions">You chose:<div class="user-selection"></div>
<div class="user-icons">
<div class="game-button">
<img class ="user-rock" src="rock.jpg" height="60px"></img>
<h3>Rock</h3>
</div>
<div class="game-button">
<img class="user-paper" src="paper.jpg" height="60px"></img>
<h3>Paper</h3>
</div>
<div class="game-button">
<img class="user-scissors" src="scissors.jpg" height="60px"></img>
<h3>Scissors</h3>
</div>
</div>
</div>
</div>
<div class="computer-choices">
<div class="computer-instructions">Computer chose:<div class="computer-selection"></div>
<div class="computer-icons">
<div class="rock-selection">
<img class="computer-rock" src="rock.jpg" height="60px"></img>
<h3>Rock</h3>
</div>
<div class="paper-selection">
<img class="computer-paper" src="paper.jpg" height="60px"></img>
<h3>Paper</h3>
</div>
<div class="scissors-selection">
<img class="computer-scissors" src="scissors.jpg" height="60px"></img>
<h3>Scissors</h3>
</div>
</div>
</div>
</div>
</head>
<body>
<script src="index.js"></script>
</body>
</html>

Your indexes logic is wrong Math.floor(Math.random() * 4) can give you 0,1,2,3 — but you only need 0,1,2.
The document tags that are part of your app should go in <body>, not in <head>
Also given Rock Paper Scissors is actually a game of indexes, you could convert your logic to something more simpler:
const fig = ["Rock", "Paper", "Scissors"];
const msg = ["You won", "You lost", "It's a draw"];
const score = [0, 0, 0]; // 0= PL's score, 1= AI's score, 2=Total Draws
function play() {
const PL = Number(this.dataset.player); // Get 0, 1, 2 from button data-player
const AI = Math.floor(Math.random() * 3); // Generate random 0, 1, 2 integer
let res; // Result to be determined:
if (PL === AI) {
res = 2; // Draw
} else if ((AI + 1) % 3 === PL) {
res = 0; // Player wins
} else {
res = 1; // Computer wins
}
score[res] += 1;
console.log(`
${msg[res]}
You played: ${fig[PL]}
Computer played: ${fig[AI]}
Score: Player: ${score[0]} Computer: ${score[1]} Draws: ${score[2]}
`);
}
document.querySelectorAll("[data-player]").forEach((el) => {
el.addEventListener("click", play);
});
<button data-player="0" type="button">ROCK</button>
<button data-player="1" type="button">PAPER</button>
<button data-player="2" type="button">SCISSORS</button>
Let's examine the key concept of "RPS is a game if indexes".
The easiest logic is when PL equals AI. So having that one eliminated,
Player wins if: we add 1 to AI's result and after a Modulo %3 the values are equal. The last one possibility is: Computer has won.
Why the modulo logic works is because of the order R-P-S or 0 1 2, which is a linear wins-over sequence.
// Rock Paper Scissors - win logic:
... 0R 1P 2S ... wins over:
/ / / /
/ / / /
... 0R 1P 2S ...
by using % 3 (in the (AI + 1) % 3) we're just making sure to cover the above's ... cases.
Without the if, else the above can be also rewritten using the (Conditional) Ternary Operator statement ? ifTrue : ifFalse :
const fig = ["Rock", "Paper", "Scissors"];
const msg = ["You won", "You lost", "It's a draw"];
const score = [0, 0, 0];
function play() {
const PL = Number(this.dataset.player); // Get 0, 1, 2 from button data-player
const AI = Math.floor(Math.random() * 3); // Generate random 0, 1, 2 integer
let res = PL === AI ? 2 : (AI + 1) % 3 === PL ? 0 : 1; // Determine result
score[res] += 1;
console.log(`
${msg[res]}!
You played: ${fig[PL]},
Computer played: ${fig[AI]}
Score: Player: ${score[0]} Computer: ${score[1]} Draws: ${score[2]}
`);
}
document.querySelectorAll("[data-player]").forEach(el => el.addEventListener("click", play));
<button data-player="0" type="button">ROCK</button>
<button data-player="1" type="button">PAPER</button>
<button data-player="2" type="button">SCISSORS</button>

I defined userInput and kept my if/else statements and now it works. Will work on refactoring my code and trying different simpler types of logic next. thanks for everyone who looked at my code!
function getComputerChoice() {
const choices = ['rock', 'paper', 'scissors'];
const ranNum = choices[Math.floor(Math.random() * 3)];
return ranNum;
}
function playRound(userInput) {
const computerInput = getComputerChoice();
if(userInput === 'rock' && computerInput === 'paper') {
computerScore++;
computerScore_div.innerHTML = computerScore;
userSelection_div.innerHTML = "You chose " + userInput;
computerSelection_div.innerHTML = "Computer chose " + computerInput;
} if (userInput === 'rock' && computerInput === 'rock') {
userSelection_div.innerHTML = "You chose " + userInput;
computerSelection_div.innerHTML = "Computer chose " + computerInput;
} if (userInput === 'rock' && computerInput === 'scissors') {
userScore++;
userScore_div.innerHTML = userScore;
userSelection_div.innerHTML = "You chose " + userInput;
computerSelection_div.innerHTML = "Computer chose " + computerInput;
// User Chooses Paper
} else if(userInput === "paper" && computerInput === 'rock') {
userScore++;
userScore_div.innerHTML = userScore;
userSelection_div.innerHTML = "You chose " + userInput;
computerSelection_div.innerHTML = "Computer chose " + computerInput;
} else if (userInput === 'paper' && computerInput === 'paper') {
console.log ('You chose paper and computer chose paper. It"s a tie!');
} else if (userInput === 'paper' && computerInput === 'scissors') {
computerScore++;
computerScore_div.innerHTML = computerScore;
userSelection_div.innerHTML = "You chose " + userInput;
computerSelection_div.innerHTML = "Computer chose " + computerInput;
// User Chooses Scissors
} else if(userInput === "scissors" && computerInput === 'rock') {
computerScore++;
computerScore_div.innerHTML = computerScore;
userSelection_div.innerHTML = "You chose " + userInput;
computerSelection_div.innerHTML = "Computer chose " + computerInput;
} else if (userInput === 'scissors' && computerInput === 'paper') {
userScore++;
userScore_div.innerHTML = userScore;
userSelection_div.innerHTML = "You chose " + userInput;
computerSelection_div.innerHTML = "Computer chose " + computerInput;
} else {
userSelection_div.innerHTML = "You chose " + userInput;
computerSelection_div.innerHTML = "Computer chose " + computerInput;
}
}
function playGame() {
userRock.addEventListener("click", function () {
playRound("rock");
})
userPaper.addEventListener("click", function () {
playRound("paper");
})
userScissors.addEventListener("click", function () {
playRound("scissors");
})
}
playGame();

Related

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;
}

rock/paper/scissors game outputting random results and I have no idea why

I want my buttons to interact with JavaScript, so I added event listeners to them. The weird thing is when for example: I click a button 'rock' and the output is 'You win! Rock beats scissors' but I don't get a point. I will get a point if I click a random button again. Next example: Computer wins and computer doesn't get a point and let's say next click is a draw and then computer gets the point. I have no idea why.
const gameElements = ['rock', 'paper', 'scissors'];
function computerPlay() {
let elementsRun = gameElements[Math.floor(Math.random()*gameElements.length)];
return elementsRun;
}
let playerScore = document.querySelector('.playerScore');
let computerScore = document.querySelector('.computerScore');
let playRounds = ''
let compRounds = ''
function singleRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return "It's a draw!"
} else if (playerSelection === 'rock' && computerSelection === 'scissors') {
playRounds ++;
return "You win! Rock beats scissors"
} else if (playerSelection === 'paper' && computerSelection == 'rock') {
playRounds ++;
return "You win! Paper beats rock"
} else if (playerSelection === 'scissors' && computerSelection == 'paper') {
playRounds ++;
return "You win! Scissors beat paper"
} else if (playerSelection === 'scissors' && computerSelection === 'rock') {
compRounds ++;
return "You lose! Rock beat scissors"
} else if (playerSelection == 'paper' && computerSelection == 'scissors') {
compRounds ++;
return "You lose! Scissors beat paper"
} else if (playerSelection === 'rock' && computerSelection === 'paper') {
compRounds ++;
return "You lose! Paper beat rock"
}
}
const buttonRock = document.querySelector('.rock')
buttonRock.addEventListener('click', function() {
computerSelection = computerPlay();
playerScore.innerHTML = 'Player:' + playRounds;
computerScore.innerHTML = 'Computer:' + compRounds;
const result = singleRound('rock', computerSelection)
console.log(result)
});
const buttonPaper = document.querySelector('.paper')
buttonPaper.addEventListener('click', function() {
computerSelection = computerPlay();
playerScore.innerHTML = 'Player:' + playRounds;
computerScore.innerHTML = 'Computer:' + compRounds;
const result = singleRound('paper', computerSelection)
console.log(result)
});
const buttonScissors = document.querySelector('.scissors')
buttonScissors.addEventListener('click', function() {
computerSelection = computerPlay();
playerScore.innerHTML = 'Player:' + playRounds;
computerScore.innerHTML = 'Computer:' + compRounds;
const result = singleRound('scissors', computerSelection)
console.log(result)
});
<div class="choices">
<div class="buttons">
<div class="tekst">
<button class="rock"><span>Rock</span></button>
<span class="playerScore">Player:</span>
</div>
<div class="tekst">
<button class="paper"><span>Paper</span></button>
<span class="winnerScore">Winner</span>
</div>
<div class="tekst">
<button class="scissors"><span>Scissors</span></button>
<span class="computerScore">Computer:</span>
</div>
</div>
</div>
There's a lot going on here. You've got a lot of unnecessary variables and functions.
But basically you are updating the scores when a selection is made and not after comparing it to the computer to see who won.
See the comments inline below:
const gameElements = ['rock', 'paper', 'scissors'];
let playerScore = document.querySelector('.playerScore');
let computerScore = document.querySelector('.computerScore');
let playRounds = 0; // Needs to be initialized as a number
let compRounds = 0; // Needs to be initialized as a number
const output = document.getElementById("output");
// Since each of the buttons does almost the same thing, there's no need
// to create 3 functions. Instead, let the event bubble up to a common
// ancestor and handle it there.
document.addEventListener('click', function(event) {
// Then, test to see if the event originated at an element we
// care about (event.target)
if(event.target.classList.contains("choice")){
output.textContent = singleRound(event.target.textContent.toLowerCase(), computerPlay());
}
});
function computerPlay() {
// There's no need to set up a variable if you are only going to use it once.
return gameElements[Math.floor(Math.random()*gameElements.length)];
}
function singleRound(playerSelection, computerSelection) {
// Instead of returning at each branch, just record the result in a variable
let result = "";
if (playerSelection === computerSelection) {
result = "It's a draw!"
} else if (playerSelection === 'rock' && computerSelection === 'scissors') {
playRounds++;
result = "You win! Rock beats scissors"
} else if (playerSelection === 'paper' && computerSelection == 'rock') {
playRounds++;
result = "You win! Paper beats rock"
} else if (playerSelection === 'scissors' && computerSelection == 'paper') {
playRounds++;
result = "You win! Scissors beat paper"
} else if (playerSelection === 'scissors' && computerSelection === 'rock') {
compRounds++;
result = "You lose! Rock beat scissors"
} else if (playerSelection == 'paper' && computerSelection == 'scissors') {
compRounds++;
result = "You lose! Scissors beat paper"
} else if (playerSelection === 'rock' && computerSelection === 'paper') {
compRounds++;
result = "You lose! Paper beat rock"
}
// Now that we know the outcome, update the screen
// Don't use .innerHTML when the text you are working with isn't HTML
// as .innerHTML has security and performance issues. Instead, use
// .textContent
playerScore.textContent = 'Player: ' + playRounds;
computerScore.textContent = 'Computer: ' + compRounds;
return result;
}
<div class="choices">
<div class="buttons">
<div class="tekst">
<!-- Button elements are already inline elements.
Wrapping their contents inside of a span is redundant.
Also, if we give each button the same class, we can
isolate only those buttons later. And we don't need
unique class names to know what the button represents.
We can just look at the .textContent of the button and
convert it to lower case to compare against the computer's
selection. -->
<button class="choice">Rock</button>
<span class="playerScore">Player:</span>
</div>
<div class="tekst">
<button class="choice">Paper</button>
<span class="winnerScore">Winner</span>
</div>
<div class="tekst">
<button class="choice">Scissors</button>
<span class="computerScore">Computer:</span>
</div>
</div>
<div id="output"></div>
</div>
Your issue is that you're not updating the InnerHTML value of the playerScore and the computerScore elements after updating the playRounds and compRounds variables. Instead, you are only updating the innerHTML after the user clicks a button, which happens before the score is updated.
In Javascript, when you do something like:
element.InnerHTML = someVariable
If someVariable changes, the value of element.InnerHTML does not change with the variable, it stays the same as it was when you initially set it. You need to call element.InnerHTML = someVariable again after updating someVariable in order to see it updated on the page.
For your case, try adding another function updateScore() which will update the innerHTML of each of your elements after every call to singleRound().
Here's how I updated your Javascript, notice how updateScore() is called each time we play a round. I also adjusted the function so that there is only one return, which is the message to be displayed. This is just a best practice-type thing, but something to keep in mind where you can.
const gameElements = ['rock', 'paper', 'scissors'];
function computerPlay() {
let elementsRun = gameElements[Math.floor(Math.random() * gameElements.length)];
return elementsRun;
}
let playerScore = document.querySelector('.playerScore');
let computerScore = document.querySelector('.computerScore');
let playRounds = ''
let compRounds = ''
function singleRound(playerSelection, computerSelection) {
let msg;
if (playerSelection === computerSelection) {
msg = "It's a draw!";
}
else if (playerSelection === 'rock' && computerSelection === 'scissors') {
playRounds++;
msg = "You win! Rock beats scissors";
}
else if (playerSelection === 'paper' && computerSelection == 'rock') {
playRounds++;
msg = "You win! Paper beats rock";
}
else if (playerSelection === 'scissors' && computerSelection == 'paper') {
playRounds++;
msg = "You win! Scissors beat paper";
}
else if (playerSelection === 'scissors' && computerSelection === 'rock') {
compRounds++;
msg = "You lose! Rock beat scissors";
}
else if (playerSelection == 'paper' && computerSelection == 'scissors') {
compRounds++;
msg = "You lose! Scissors beat paper";
}
else if (playerSelection === 'rock' && computerSelection === 'paper') {
compRounds++;
msg = "You lose! Paper beat rock";
}
updateScore();
return msg;
}
function updateScore() {
playerScore.innerHTML = 'Player:' + playRounds;
computerScore.innerHTML = 'Computer:' + compRounds;
}
const buttonRock = document.querySelector('.rock')
buttonRock.addEventListener('click', function () {
computerSelection = computerPlay();
const result = singleRound('rock', computerSelection)
console.log(result)
});
const buttonPaper = document.querySelector('.paper')
buttonPaper.addEventListener('click', function () {
computerSelection = computerPlay();
const result = singleRound('paper', computerSelection)
console.log(result)
});
const buttonScissors = document.querySelector('.scissors')
buttonScissors.addEventListener('click', function () {
computerSelection = computerPlay();
const result = singleRound('scissors', computerSelection)
console.log(result)
});

Rock Paper Scissors game only one outcome unless I refresh page

So im making The Odin Project's rock paper scissors game and the only problem i have is that the computer's selection is always the same unless I refresh the page.
for example if i choose Rock three times in a row, the computer's selection will always be the same unless i refresh the page.
const thing1 = "Rock",
thing2 = "Paper",
thing3 = "Scissors";
function computerPlay() {
let a = Math.random();
if (a <= 0.33) {
return thing1;
} else if (a > 0.33 && a < 0.67) {
return thing2;
} else {
return thing3;
}
}
let playerScore = 0,
computerScore = 0;
const playerSelection = ["Rock", "Paper", "Scissors"];
let computerSelection = computerPlay();
function playRound(playerSelection, computerSelection) {
if (playerSelection.toLowerCase() == "rock" && computerSelection == thing2) {
computerScore++;
return "You lose! Rock loses to Paper";
} else if (playerSelection.toLowerCase() == "rock" && computerSelection == thing3) {
playerScore++;
return "You win! Rock beats Scissors";
} else if (playerSelection.toLowerCase() == "paper" && computerSelection == thing1) {
playerScore++;
return win = "You win! Paper beats Rock";
} else if (playerSelection.toLowerCase() == "paper" && computerSelection == thing3) {
computerScore++;
return win = "You lose! Paper loses to Scissors";
} else if (playerSelection.toLowerCase() == "rock" && computerSelection == thing1) {
computerScore++;
return win = "You lose! Rock loses Scissors";
} else if (playerSelection.toLowerCase() == "scissors" && computerSelection == thing2) {
playerScore++;
return win = "You win! Scissors beats Paper!";
} else {
return "Tie!";
}
}
function game() {
let playerSelection = prompt("Rock, paper or scissors?");
result = playRound(playerSelection, computerSelection);
scoreboard = "User:" + " " + playerScore + " " + "Computer" + " " + computerScore;
console.log(scoreboard);
return result;
}
You only call computerPlay() once, leading it computerSelection being the exact same every round. Call it every round to get a new random value.
function game() {
let playerSelection = prompt("Rock, paper or scissors?");
computerSelection = computerPlay(); // <---
result = playRound(playerSelection, computerSelection);
scoreboard = "User:" + " " + playerScore + " " + "Computer" + " " + computerScore;
console.log(scoreboard);
return result;
}

Rock Paper Scissors game returns same result

So I'm having some difficulty with my code (hence the post). I'm trying to make it so where when you click on the picture of the rock, the game begins and it returns the computer's decision. It worked before when I prompted the user but since I've rewritten the logic when I click on the rock, it only returns one answer. Is it because of the lack of loops? I assumed each time I would click on the icon, a different answer would display. I haven't done the code for the other options yet because I figured I would use similar logic for the other options. The only thing I can think of is that because I'm not using a loop, the game basically plays only 1 round.
const rock = document.querySelector('.rock');
const paper = document.querySelector('.paper');
const scissors = document.querySelector('.scissors');
const h3 = document.querySelector('h3');
let computerScore = 0;
let playerScore = 0;
function computerPlay() {
var choice = Math.floor(Math.random() * 3 ) + 1; //generate a number 1-3 to find computer choice
if(choice == 1) {
return 'rock';
}
else if(choice == 2) {
return 'paper';
}
else {
return 'scissors'
}
}
// function playGame(computerChoice) {
// // let round = 0
// // while(round < 6) {
// var playerChoice = playerRock || playerPaper || playerScissors;
// var computerChoice = computerPlay();
// if(playerChoice === computerChoice) {
// console.log('Tie!');
// round++;
// }
// else if(playerChoice == 'rock' && computerChoice == 'scissors') {
// playerScore++;
// console.log(`Player chose rock and computer chose scissors! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// round++;
// }
// else if(playerChoice == 'paper' && computerChoice == 'rock') {
// playerScore++;
// round++;
// console.log(`Player chose paper and computer chose rock! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// }
// else if(playerChoice == 'scissors' && computerChoice == 'paper') {
// playerScore++;
// round++;
// console.log(`Player chose scissors and computer chose paper! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// }
// else {
// computerScore++;
// console.log(`The player chose ${playerChoice} and the computer chose ${computerChoice}! The computer wins! Player: ${playerScore} Computer: ${computerScore}.`)
// }
// // }
// }
// computerPlay()
// playerChoice()
// console.log(playGame())
function playGame(computerChoice) {
computerChoice = computerPlay();
let result;
rock.addEventListener('click', () => {
if(computerChoice == 'rock') {
result = `The computer chose ${computerChoice} and you chose rock! It's a tie!`;
h3.textContent = result;
}
else if(computerChoice == 'paper') {
result = `The computer chose ${computerChoice} and you chose rock! You lose!`;
h3.textContent = result;
computerScore++;
}
else {
result = `The computer chose ${computerChoice} and you chose rock! You win!`;
h3.textContent = result;
playerScore++;
}
});
let playerPaper = paper.addEventListener('click', () => {
return 'paper'
});
let playerScissors = scissors.addEventListener('click', () => {
return 'scissors'
})
}
playGame()
console.log(playGame())
This is what I have so far. Initially, I didn't have a result variable but I thought that might help.
When calling playGame() once, computerChoice is only generated once. Everytime you click on rock paper or scissor it evaluates the players choice, but the computers choice has never changed. If it chooses rock at the beginning it will always compare the users choice to rock.
Either take the eventListeners out of the playGame function and call playGame after the result is shown (Recursive-style loop)
Or, after the result is shown reset computerChoice to the result of another computerPlay() call. You can add computerChoice = computerPlay() to the end of your event listener function after the else statement to run regardless of the outcome.
You need to do some changes ...
1- add event at first time
add useChoicevariable
and show reult of game on click
const rock = document.querySelector('.rock');
const paper = document.querySelector('.paper');
const scissors = document.querySelector('.scissors');
const h3 = document.querySelector('h3');
let computerScore = 0;
let playerScore = 0;
let computerChoice = "";
let userChoice = "";
rock.addEventListener('click', () => {
userChoice = "rock";
ShowResult()
});
paper.addEventListener('click', () => {
userChoice = 'paper';
ShowResult()
});
scissors.addEventListener('click', () => {
userChoice = 'scissors';
ShowResult()
})
function computerPlay() {
var choice = Math.floor(Math.random() * 3) + 1; //generate a number 1-3 to find computer choice
if (choice == 1) {
return 'rock';
}
else if (choice == 2) {
return 'paper';
}
else {
return 'scissors'
}
}
// function playGame(computerChoice) {
// // let round = 0
// // while(round < 6) {
// var playerChoice = playerRock || playerPaper || playerScissors;
// var computerChoice = computerPlay();
// if(playerChoice === computerChoice) {
// console.log('Tie!');
// round++;
// }
// else if(playerChoice == 'rock' && computerChoice == 'scissors') {
// playerScore++;
// console.log(`Player chose rock and computer chose scissors! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// round++;
// }
// else if(playerChoice == 'paper' && computerChoice == 'rock') {
// playerScore++;
// round++;
// console.log(`Player chose paper and computer chose rock! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// }
// else if(playerChoice == 'scissors' && computerChoice == 'paper') {
// playerScore++;
// round++;
// console.log(`Player chose scissors and computer chose paper! The player wins! Player: ${playerScore} Computer:${computerScore}`);
// }
// else {
// computerScore++;
// console.log(`The player chose ${playerChoice} and the computer chose ${computerChoice}! The computer wins! Player: ${playerScore} Computer: ${computerScore}.`)
// }
// // }
// }
// computerPlay()
// playerChoice()
// console.log(playGame())
function ShowResult() {
if (computerChoice == userChoice) {
result = `The computer chose ${computerChoice} and you chose ${userChoice}! It's a tie!`;
h3.textContent = result;
} else if (
computerChoice == 'paper' && userChoice == "rock"
|| computerChoice == 'scissors' && userChoice == "paper"
|| computerChoice == 'rock' && userChoice == "scissors"
) {
result = `The computer chose ${computerChoice} and you chose ${userChoice}! You lose!`;
h3.textContent = result;
computerScore++;
} else {
result = `The computer chose ${computerChoice} and you chose ${userChoice}! You win!`;
playerScore++;
h3.textContent = result + playerScore ;
}
playGame()
}
function playGame() {
computerChoice = computerPlay();
console.log( "Computer Choice:" + computerChoice);
}
playGame()
<div class="rock">rock</div>
<div class="paper">paper</div>
<div class="scissors">scissors</div>
<h3></h3>

Score counter for rock paper scissor game javascript

i have finished my rock paper scissor game, and i am now working on adding a score to it. The problem i have is that i can't get the program to increment the score, but instead it resets every round.
I have tried making the two variables, and then adding +1 in my function whenever one of them wins but i can't get it to save.
var userscore = 0;
var computerscore = 0;
function computerdecision() {
var Number = Math.floor(Math.random() * 3);
switch (Number) {
case 0:
return "rock";
case 1:
return "scissor";
case 2:
return "paper";
}
}
function declareWinner(userweapon, computerweapon) {
if (userweapon === computerweapon) {
console.log("Tiebreak");
} else if (userweapon === "rock" && computerweapon === "scissor" ||
userweapon === "paper" && computerweapon === "rock" || userweapon === "scissor" && computerweapon ===
"paper") {
console.log("User won");
userscore++;
} else {
console.log("Computer won");
computerscore++;
}
}
var userweapon = "rock"
var computerweapon = computerdecision();
console.log('Your weapon is: ' + userweapon);
console.log("Computer's weapon is: " + computerweapon);
declareWinner(userweapon, computerweapon);
console.log("User: " + userscore)
console.log("computer: " + computerscore)
Thanks in advance.
In order to play another round the user need to refresh the page (as #EmielZuurbier comment), so unless you use some sort of data saving - all records will lost.
A quick fix will be to make a button that will call the function again. But this won't save records after exit / refresh. And i guess this is not what you are searching...
Anyway, i edit and rewrite your code to make it playable + added some local storage score board. I leave you the fun part to change the onclick events and to style it as you want.
var userscore = localStorage.getItem('userScore');
document.querySelector("#userScore").textContent = userscore;
var computerscore = localStorage.getItem('computerScore');
document.querySelector("#computerScore").textContent = computerscore;
function computerdecision() {
var Number = Math.floor(Math.random() * 3);
switch (Number) {
case 0:
return "rock";
case 1:
return "scissor";
case 2:
return "paper";
}
}
function declareWinner() {
var computerweapon = computerdecision();
var userweapon = document.querySelector('input[name="weapon"]:checked').value;
if (userweapon === computerweapon) {
document.querySelector("#gameResult").textContent = " Tiebreak ";
}
else if (userweapon === "rock" && computerweapon === "scissor" || userweapon === "paper" && computerweapon === "rock" || userweapon === "scissor" && computerweapon === "paper") {
document.querySelector("#gameResult").textContent = " User won ";
userscore++;
} else {
document.querySelector("#gameResult").textContent = " Computer won ";
computerscore++;
}
document.querySelector("#userWeapon").textContent = " User weapon was: " + userweapon;
document.querySelector("#computerWeapon").textContent = " Computer's weapon was: " + computerweapon;
document.querySelector("#userScore").textContent = userscore;
localStorage.setItem('userScore', userscore);
document.querySelector("#computerScore").textContent = computerscore;
localStorage.setItem('computerScore', computerscore);
}
<label for="rock"><input type="radio" name="weapon" id="rock" value="rock" checked />Rock</label>
<label for="paper"><input type="radio"name="weapon" id="paper" value="paper" />Paper</label>
<label for="scissor"><input type="radio"name="weapon" id="scissor" value="scissor" />Scissor</label>
<button onclick="declareWinner();">Play</button>
<div>
Game Result: <span id="gameResult"></span>
<br />
Computer: <mark id="computerScore"></mark>
<br />
Computer Weapon: <span id="computerWeapon"></span>
<br />
User: <mark id="userScore"></mark>
<br />
User Weapon: <span id="userWeapon"></span>
</div>
<hr />
<button onclick="localStorage.clear();">clear saved records</button>
Hope it helps! If you have more questions leave a comment.
P.S - The score board won't work here on stack's since it restricted, so you should copy-paste and run it on your machine.

Categories

Resources