Random if/else behavior - Rock, Paper, Scissors game - javascript

So I have been working on this for awhile and can't figure out why my if/else statement does not console.log the correct response based on the computer and player selections. It seems like it will return a random statement regardless of the input from player or computer. Also, I don't understand why it will prompt me for input twice.
I get that there are other ways to build a simple RPS game in the console, but I don't understand why this won't work specifically. I'm more worried about what steps I'm missing in building a simple game that are essential for other projects later. I'm obviously new at this and am working on this through the Odin Project website, for reference. Thank you so much in advance for the help! Anyway, here's the code:
<script>
function computerChoice() {
let choices = ['rock', 'paper', 'scissors'];
let result = choices[Math.floor(Math.random() * choices.length)];
return result
};
let playerSelection = function() {
let playerChoice = prompt('What do you choose, young Padawan?')
return playerChoice.toLowerCase()
};
let computerSelection = computerChoice();
console.log(computerChoice());
console.log(playerSelection());
function play(playerSelection, computerSelection) {
if (playerSelection === 'rock' && computerSelection === 'paper') {
console.log('Paper beats rock! Computron wins!');
} else if (playerSelection === 'rock' && computerSelection === 'scissors') {
console.log('Rock smash scissors! You win!');
} else if (playerSelection === 'paper' && computerSelection === 'rock') {
console.log('Paper covers rock! You win Starlord!');
} else if (playerSelection === 'paper' && computerSelection === 'scissors') {
console.log('Scissors cuts paper! Thanos is king!');
} else if (playerSelection === 'scissors' && computerSelection === 'paper') {
console.log('Scissors cuts paper! The Avengers avenge!');
} else if (playerSelection === 'scissors' && computerSelection === 'rock') {
console.log('Rock smash! Avengers suck!');
} else {
console.log('Tie! You must select a different weapon!');
}
};
play();
</script>

You have a combination of different ways of defining and calling function here. You define your player selection function but do not call it in a single instance, like you do with your computer selection. To make the player selection be consistent for the results, define your player selection as a function and then assign the results to a variable before logging it.
function computerChoice() {
let choices = ['rock', 'paper', 'scissors'];
let result = choices[Math.floor(Math.random() * choices.length)];
return result
};
function playerChoice() {
let playerChoice = prompt('What do you choose, young Padawan?');
return playerChoice.toLowerCase();
}
let playerSelection = playerChoice();
let computerSelection = computerChoice();
console.log("Player selection", playerSelection);
console.log("Computer selection", computerSelection);
function play(playerSelection, computerSelection) {
if (playerSelection === 'rock' && computerSelection === 'paper') {
console.log('Paper beats rock! Computron wins!');
} else if (playerSelection === 'rock' && computerSelection === 'scissors') {
console.log('Rock smash scissors! You win!');
} else if (playerSelection === 'paper' && computerSelection === 'rock') {
console.log('Paper covers rock! You win Starlord!');
} else if (playerSelection === 'paper' && computerSelection === 'scissors') {
console.log('Scissors cuts paper! Thanos is king!');
} else if (playerSelection === 'scissors' && computerSelection === 'paper') {
console.log('Scissors cuts paper! The Avengers avenge!');
} else if (playerSelection === 'scissors' && computerSelection === 'rock') {
console.log('Rock smash! Avengers suck!');
} else {
console.log('Tie! You must select a different weapon!');
}
};
play(playerSelection, computerSelection);
EDIT
Also, you define two parameters for your play function but never pass them in to the function, make sure you pass in both playerSelection and computerSelection

You were calling your function with console.log, I added a promise to make sure nothing runs until user input is selected. Then showed you were to restart if it is a tie.
console.log(computerChoice()); // re-runs function
console.log(playerSelection()); // re-runs function
I also make sure the page is loaded before we start throwing some alerts to the user for curtesy.
document.addEventListener("DOMContentLoaded", function(event) { })
For computerChoice function let's remove the redundant variable, since we are returning what the variable value is. We do this instead.
return (choices[Math.floor(Math.random() * choices.length)]);
We used a promise for the user input, a promise basically is a function that promises a value or rejects something. When you call the function, you use .then((value)) to get the value.
let playerSelection = function() {
return new Promise((resolve) => {
let playerChoice = prompt('What do you choose, young Padawan?')
console.log(playerChoice); // we log the player choice here instead
resolve(playerChoice.toLowerCase());
})
};
We get the promise value like this
playerSelection().then((value) => { })
function computerChoice() {
let choices = ['rock', 'paper', 'scissors'];
return (choices[Math.floor(Math.random() * choices.length)]);
}
let playerSelection = function() {
return new Promise((resolve) => {
let playerChoice = prompt('What do you choose, young Padawan?')
console.log(playerChoice); // we log the player choice here instead
resolve(playerChoice.toLowerCase());
})
};
// Remove console.log(playerChoice); calling the function, causes two prompts
function play() {
playerSelection().then((playerChoice) => {
let computerSelection = computerChoice(); // We want new one each time.
if (playerChoice === 'rock' && computerSelection === 'paper') {
console.log('Paper beats rock! Computron wins!');
} else if (playerChoice === 'rock' && computerSelection === 'scissors') {
console.log('Rock smash scissors! You win!');
} else if (playerChoice === 'paper' && computerSelection === 'rock') {
console.log('Paper covers rock! You win Starlord!');
} else if (playerChoice === 'paper' && computerSelection === 'scissors') {
console.log('Scissors cuts paper! Thanos is king!');
} else if (playerChoice === 'scissors' && computerSelection === 'paper') {
console.log('Scissors cuts paper! The Avengers avenge!');
} else if (playerChoice === 'scissors' && computerSelection === 'rock') {
console.log('Rock smash! Avengers suck!');
} else {
alert('Tie! You must select a different weapon!');
play() // Tie-have user re-enter choice
}
})
};
// Make sure page loaded
document.addEventListener("DOMContentLoaded", function(event) {
//do work
play();
});

Related

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

TOP Rock Paper Scissors Project

This is my first time posting a question so I apologize if I posted incorrectly. I am doing The Odin Project and I am stuck on why my code returns undefined and does not run my return code on the function singleRound. I also do not understand why my game function console.logs all of the code and does not run based on if the computer or the player got the point. If someone could point me in the right direction it would be greatly appreciated!
function computerPlay(computerSelection){
let choices=['Rock','Paper','Scissors']
let pick= choices[Math.floor(Math.random()*choices.length)];
}
//plays single round
function singleRound(playerSelection,computerSelection){
if (playerSelection === 'Paper'|| computerSelection === 'Rock') {
playerPoints=+1
return "You Win! Paper beats Rock";
}
else if (playerSelection === 'Paper'|| computerSelection=='Scissors') {
computerPoints=+1
return"Paper does not beat Scissors! You lose";
}
else if (playerSelection === 'Paper' || computerSelection ==='Paper') {
return "Paper does not beat Paper! Tie Game!";
}
else if (playerSelection === 'Rock' || computerSelection ==='Paper') {
computerPoints=+1
return"Rock does not beat Paper! You lose";
}
else if (playerSelection === 'Rock' || computerSelection ==='Rock') {
return"Rock does not beat Rock! Tie Game!";
}
else if (playerSelection === 'Rock' || computerSelection ==='Scissors') {
playerPoints=+1
return "Rock beats Scissors! You Win!";
}
else if (playerSelection === 'Scissors' || computerSelection ==='Paper') {
playerPoints=+1
return "Scissors Beats Paper! You Win!";
}
else if (playerSelection === 'Scissors' || computerSelection ==='Rock') {
computerPoints=+1
return "Scissors does not beat Rock! You lose!";
}
else if (playerSelection === 'Scissors' || computerSelection ==='Scissors') {
return"Scissors does not beat Scissors! Tie Game!";
}
}
//plays 5 rounds**strong text**
function game(){
for (let i = 0; i < 5; i++) {
let playerPoints=0;
let computerPoints=0;
if (playerPoints === i++)
{console.log('1 point for player');}
else if (computerPoints === i++){
console.log('1 point for the computer');}
else if (computerPoints !== i++ && playerPoints !== i++){ console.log('No one won this round. No points for either of you.');}
if (playerPoints= 5 && computerPoints< 5){
console.log('Yay! Congrats! You won the game! ');
}
if (computerPoints=5 && playerPoints < 5){
console.log('Sorry :/ You lost the game.');
}
else{
endGame();
}
}
}
let playerSelection=['Rock','Paper','Scissors']
const computerSelection=computerPlay
console.log('The computer chose:' + computerSelection());
prompt("Do you want to pick Rock, Paper, or Scissors?");
console.log(singleRound(playerSelection,computerSelection));
computerPlay();
Add return pick; in the computerPlay function. It is returning undefined because computerPlay returns nothing in the above code
function computerPlay(computerSelection){
let choices=['Rock','Paper','Scissors']
let pick= choices[Math.floor(Math.random()*choices.length)];
return pick
}
Also I would change the bottom code to the following since computerPlay returns the selection and we want to preserve the selection between the first console.log statement and when you call the singleRound
let playerSelection=['Rock','Paper','Scissors']
const computerSelection=computerPlay()
console.log('The computer chose:' + computerSelection);
prompt("Do you want to pick Rock, Paper, or Scissors?");
console.log(singleRound(playerSelection,computerSelection));
computerPlay();

Building a Rock/Paper/Scissors game with HTML/Javascript but not getting the desired output

I am pretty new to coding still, so I apologize in advance if this seems super basic. I've been doing The Odin Project and have made it to the RPS assignment. Now, I've kind of been playing with different iterations of the code just to get a better idea as to how things could work.
Right now I am just putting script tags in an html file to get the desired result and running the function through a console.log() in my browser. The issue I am having is that even when I run the function with the right inputs - I sometimes get the final else statement. I'll post the code below and then try to explain in greater detail what I mean.
<script>
function game(playerSelection) {
playerSelection = playerSelection.toLowerCase();
function computerSelection() {
let cAnswer = Math.floor(Math.random() * 3 + 1);
if (cAnswer == 1) {
return 'rock';
} else if (cAnswer == 2) {
return 'paper';
} else {
return 'scissors';
}
}
if (playerSelection == computerSelection()) {
return 'It\'s a tie! Try again.'
} else if (playerSelection == 'rock' && computerSelection() == 'scissors') {
return 'Rock beats scissors, you win!'
} else if (playerSelection == 'rock' && computerSelection() == 'paper') {
return 'Paper beats rock, you lose!'
} else if (playerSelection == 'paper' && computerSelection() == 'scissors') {
return 'Scissors beats scissors, you lose!'
} else if (playerSelection == 'paper' && computerSelection() == 'rock') {
return 'Paper beats rock, you win!'
} else if (playerSelection == 'scissors' && computerSelection() == 'paper') {
return 'Scissors beats paper, you win!'
} else if (playerSelection == 'scissors' && computerSelection() == 'rock') {
return 'Rock beats scissors, you lose!'
} else {
return 'It doesn\'t seem like you typed a valid option. Please type \'Rock\', \'Paper\', or \'Scissors\''
}
}
</script>
Whenever I run console.log(game('scissors')) for instance, I still occasionally get the final else statement from my if ... else block. Shouldn't that be impossible? When I go through it - as long as I type rock, paper, or scissors, I thought I should be hitting one of the other if statements before reaching the final else in the block. But still, sometimes the output I get in my console is 'It doesn't seem like you typed a valid option. Please type 'Rock', 'Paper', or 'Scissors
I imagine I didn't explain this very well so please let me know if I can help clarify.
Thank you!
You're running computerSelection every time in the if checks - every time the interpreter comes across the function call computerSelection(), a new computer answer is generated.
Generate the computer's answer just once instead:
const computerSelection = (() => {
let cAnswer = Math.floor(Math.random() * 3 + 1);
if (cAnswer == 1) {
return 'rock';
} else if (cAnswer == 2) {
return 'paper';
} else {
return 'scissors';
}
})();
if (playerSelection == computerSelection) {
return 'It\'s a tie! Try again.'
} else if (playerSelection == 'rock' && computerSelection == 'scissors') {
// etc
Or, less repetitively:
const computerSelection = ['rock', 'paper', 'scissors'][Math.floor(Math.random() * 3));

Rock, Paper, Scissors Game shows both win and lose messages

I'm currently working through a Rock, Paper, Scissors project that plays out in the console (this is for The Odin Project, front end coming soon).
Here is what my script looks like for reference:
<script>
function computerPlay() {
const choice = ["Rock", "Paper", "Scissors"]
return choice[Math.floor(Math.random() * choice.length)]
}
function play(playerSelection, computerSelection) {
const lose = console.log('You lose! ' + computerSelection + ' beats ' + playerSelection + '!')
const win = console.log('You win! ' + playerSelection + ' beats ' + computerSelection + '!')
if (playerSelection === computerSelection) {
return console.log("It's a draw! Try again!")
}
if (playerSelection === "rock" && computerSelection === "Paper") {
return lose
}
if (playerSelection === "rock" && computerSelection === "Scissors") {
return win
}
if (playerSelection === "paper" && computerSelection === "Scissors") {
return lose
}
if (playerSelection === "paper" && computerSelection === "Rock") {
return win
}
if (playerSelection === "scissors" && computerSelection === "Rock") {
return lose
}
if (playerSelection === "scissors" && computerSelection === "Paper") {
return win
}
}
function game() {
playerSelect = prompt("Welcome to Rock, Paper, Scissors! Which one do you choose? \n")
compSelect = computerPlay()
console.log("Player chose " + playerSelect)
console.log("Computer chose " + compSelect)
console.log(play(playerSelect, compSelect))
}
</script>
Right now my output is showing both the win and lose conditions for any given choice like this:
Player chose rock
Computer chose Rock
You lose! Rock beats rock!
You win! rock beats Rock!
I chose to keep the win and lose messages in variables but I know I probably screwed some small detail up there. I've tried adding/removing the if else statements but both messages still show up no matter what choice.
I'm planning on making either choice case insensitive until I solve this error.
Any help would be appreciated, thanks!:
When you are calling your console.log at the beginning of the script, you are not saving them for later, you are running them and assigning their return value to a variable. What you could do is have a win and a lose variable that are function and then call them when the player is winning/loosing.
function computerPlay() {
const choice = ["Rock", "Paper", "Scissors"];
return choice[Math.floor(Math.random() * choice.length)];
}
function play(playerSelection, computerSelection) {
// we are storing a function into the win and lose variable.
const lose = () => console.log('You lose! ' + computerSelection + ' beats ' + playerSelection + '!');
const win = () => console.log('You win! ' + playerSelection + ' beats ' + computerSelection + '!');
if (playerSelection === computerSelection) {
return console.log("It's a draw! Try again!")
}
if (playerSelection === "rock" && computerSelection === "Paper") {
return lose()
}
if (playerSelection === "rock" && computerSelection === "Scissors") {
return win()
}
if (playerSelection === "paper" && computerSelection === "Scissors") {
return lose()
}
if (playerSelection === "paper" && computerSelection === "Rock") {
return win()
}
if (playerSelection === "scissors" && computerSelection === "Rock") {
return lose()
}
if (playerSelection === "scissors" && computerSelection === "Paper") {
return win()
}
}
function game() {
playerSelect = 'rock';
compSelect = computerPlay();
console.log("Player chose " + playerSelect);
console.log("Computer chose " + compSelect);
// You don't need to console.log the return value of a console.log
play(playerSelect, compSelect);
}
game();
Try changing your lose and win variables to their string values instead of console.log("/message/").
Your lose and win variable declarations are already printing their messages instead of storing them, since your code calls an instance of console.log().
That way, when you return either win or lose, your console.log(play(playerSelect, compSelect)) will receive a string, and then print it.

Game counter for a JavaScript Rock Paper Scissors Game is not working

I have created a Rock Paper Scissors game that plays 5 rounds in the console and am now trying to refactor it to work in a browser with buttons using DOM manipulation.
The button and round functions are:
rock_btn.addEventListener('click',function(){
round('rock');
})
paper_btn.addEventListener('click',function(){
round('paper');
})
scissors_btn.addEventListener('click',function(){
round('scissors');
})
function round (playerSelection) {
let computerSelection = computerPlay();
if (playerSelection === 'rock' && computerSelection === 'scissors') {
playerScore++
userScore_span.innerHTML = playerScore;
result_div.innerHTML = 'You Win\! Rock beats Scissors\!';
} else if (playerSelection === 'scissors' && computerSelection === 'rock') {
computerScore++;
compScore_span.innerHTML = computerScore;
result_div.innerHTML = 'You Lose\! Rock beats Scissors\!';
} else if(playerSelection === 'paper' && computerSelection === 'rock') {
playerScore++;
userScore_span.innerHTML = playerScore;
result_div.innerHTML ='You Win\! Paper beats Rock\!';
} else if(playerSelection === 'rock' && computerSelection === 'paper') {
computerScore++;
compScore_span.innerHTML = computerScore;
result_div.innerHTML = 'You Lose\! Paper beats Rock\!';
} else if(playerSelection === 'scissors' && computerSelection === 'paper') {
playerScore++;
userScore_span.innerHTML = playerScore;
result_div.innerHTML ='You Win\! Scissors beats Paper\!';
} else if(playerSelection === 'paper' && computerSelection === 'scissors') {
computerScore++;
compScore_span.innerHTML = computerScore;
result_div.innerHTML = 'You Lose\! Scissors beats Paper\!';
} else {
result_div.innerHTML = ('A draw! Please play again!');
}
}
the game function used to count the rounds worked when called in the console but now has no effect:
let playerScore = 0;
let computerScore = 0;
function game () {
while (playerScore <= 5 || computerScore <= 5) {
round();
if(playerScore === 5) {
result_div.innerHTML = 'Player Wins!!!';
}
if(computerScore === 5) {
result_div.innerHTML = 'Computer Wins!!!';
}
}
}
Could someone please advise me how I can insert the game function into the sequence so the counter works?
Welcome to Stackoverflow.
Since you're relying on the game being played with buttons on your DOM, you should check for the win condition at the end of our round function:
Win condition:
function win_condition () {
if(playerScore === 5) {
result_div.innerHTML = 'Player Wins!!!';
}
if(computerScore === 5) {
result_div.innerHTML = 'Computer Wins!!!';
}
}
in your round function:
...
else if(playerSelection === 'paper' && computerSelection === 'scissors') {
computerScore++;
compScore_span.innerHTML = computerScore;
result_div.innerHTML = 'You Lose\! Scissors beats Paper\!';
} else {
result_div.innerHTML = ('A draw! Please play again!');
}
win_condition();
}
You could refactor a bit of your code by DRYing it up, maybe abstract the rules away (i.e. rocks win against scissor but loses against paper, etc.)
I did something like this on another post. See this CodePen:
lines 66 to 79 define the win conditions;
lines 93 to 99 how it's used.
Mind you, it's in ReactJS, so you'd need to apply it a bit differently, but the principle stays: abstract the logic away and DRY up your code.
(BTW: global mutable state will bite you eventually, you'd improve your code a lot by making your functions pure)

Categories

Resources