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

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.

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

Rock Paper Scissors Javascript (The Odin Project)

Hello everyone this is my first question here so sorry if it doesn't match all the rules. I am trying to make a rock paper scissors game from the Odin Project in javascript, and I'm having problem with the result output because it doesn't display what it should. If computer plays rock for e. and i play rock i should get it's a draw but i get something random all the time. Current code is with prompt() for user input, but I tried putting a fixed string like "paper" and it was the same, I also thought it was because I didn't put toLowerCase() properly so I removed it completely and it's still the same, I would appreciate your help!
function computerPlay() {
let rps = ["rock", "paper", "scissors"];
let random = rps[Math.floor(Math.random() * rps.length)];
return random;
}
console.log(computerPlay());
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return ("It's a draw!");
} else if ((playerSelection === "rock") && (computerSelection === "scissors")) {
return ("You win! Rock beats scissors");
} else if (playerSelection === "rock" && computerSelection === "paper") {
return ("You lose! Paper beats rock");
} else if (playerSelection === "paper" && computerSelection === "rock") {
return ("You win! Paper beats rock");
} else if (playerSelection === "paper" && computerSelection === "scissors") {
return ("You lose! Scissors beat paper");
} else if (playerSelection === "scissors" && computerSelection === "paper") {
return ("You win! Scissors beat paper");
} else if (playerSelection === "scissors" && computerSelection === "rock") {
return ("You lose!Rock beats scissors");
}
}
let computerSelection = computerPlay();
let playerSelection = prompt("Choose your weapon");
console.log(playRound(playerSelection, computerSelection));
You first console.log the function computerPlay() and that returns a certain value. After that you play the round and calls again the function computerPlay(), this computes the round with another value than you first console.log.
Try this code below
function computerPlay() {
let rps = ["rock", "paper", "scissors"];
let random = rps[Math.floor(Math.random() * rps.length)];
return random;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
return ("It's a draw!");
} else if ((playerSelection === "rock") && (computerSelection === "scissors")) {
return ("You win! Rock beats scissors");
} else if (playerSelection === "rock" && computerSelection === "paper") {
return ("You lose! Paper beats rock");
} else if (playerSelection === "paper" && computerSelection === "rock") {
return ("You win! Paper beats rock");
} else if (playerSelection === "paper" && computerSelection === "scissors") {
return ("You lose! Scissors beat paper");
} else if (playerSelection === "scissors" && computerSelection === "paper") {
return ("You win! Scissors beat paper");
} else if (playerSelection === "scissors" && computerSelection === "rock") {
return ("You lose!Rock beats scissors");
}
}
let computerSelection = computerPlay();
let playerSelection = prompt("Choose your weapon");
console.log(computerSelection)
console.log(playRound(playerSelection, computerSelection));
You can simplify your conditions in this way
const choices = ["Rock", "Paper", "Scissors"]
const computerPlay = () => choices[Math.floor(Math.random() * choices.length)]
function playRound(playerSelection, computerSelection) {
const difference = (choices.length + choices.indexOf(playerSelection) - choices.indexOf(computerSelection) )% choices.length
switch(difference){
case 0:
return "It's a draw!"
case 2:
return `You lose! ${computerSelection} beats ${playerSelection}`
default:
return `You win! ${playerSelection} beats ${computerSelection}`
}
}
let computerSelection = computerPlay();
let playerSelection
while(!choices.includes(playerSelection)){
const selected = prompt("Choose your weapon").trim().toLowerCase();
playerSelection = selected[0].toUpperCase()+selected.slice(1)
}
console.log(playRound(playerSelection, computerSelection));

Can anyone tell me why my code doesn't work properly? Game ROCK, PAPER, SCISSORS. Java Script

Can anyone tell me why my code doesn't work properly? I'm trying to make game ROCK, PAPER, SCISSORS on plain Java Script. For some reason it doesn't work as I expect.
const computerAanswer = ["rock", "paper", "scissors"];
function computerPlay() {
let answer = computerAanswer[Math.floor(Math.random() * computerAanswer.length)];
return answer;
}
console.log('computer choice is: ' + computerPlay().toUpperCase());
function playRound (playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase()
if (playerSelection == "rock" && computerSelection == "scissors") {
return "Congrats,you are winner!";
} else if (playerSelection == "paper" && computerSelection == "rock") {
return "Congrats,you are winner!";
} else if (playerSelection == "scissors" && computerSelection == "paper") {
return "Congrats,you are winner!";
} else if (playerSelection == "rock" && computerSelection == "rock") {
return "Draw!";
} else if (playerSelection == "paper" && computerSelection == "paper") {
return "Draw!";
} else if (playerSelection == "scissors" && computerSelection == "scissors") {
return "Draw!";
} else {
return "You lose. Maybe next time...";
}
}
let playerSelection = prompt("Make your choose: Rock, Paper or Scissors?");
let computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
console.log('player choice is: ' + playerSelection.toUpperCase());
I guess that's just your first console.log :
console.log('computer choice is: ' + computerPlay().toUpperCase());
It plays a round for computer, then you play another one against prompted user.
Do that instead :
function computerPlay() {
let answer = computerAanswer[Math.floor(Math.random() * computerAanswer.length)];
console.log('computer choice is: ' + answer.toUpperCase());
return answer;
}
When I nested
console.log('computer choice is: ' + answer.toUpperCase());
into computerPlay function it works.
const computerAanswer = ["rock", "paper", "scissors"];
function computerPlay() {
let answer = computerAanswer[Math.floor(Math.random() * computerAanswer.length)];
console.log('computer choice is: ' + answer.toUpperCase());
return answer;
}
function playRound (playerSelection, computerSelection) {
playerSelection = playerSelection.toLowerCase()
if (playerSelection == "rock" && computerSelection == "scissors") {
return "Congrats,you are winner!";
} else if (playerSelection == "paper" && computerSelection == "rock") {
return "Congrats,you are winner!";
} else if (playerSelection == "scissors" && computerSelection == "paper") {
return "Congrats,you are winner!";
} else if (playerSelection == "rock" && computerSelection == "rock") {
return "Draw!";
} else if (playerSelection == "paper" && computerSelection == "paper") {
return "Draw!";
} else if (playerSelection == "scissors" && computerSelection == "scissors") {
return "Draw!";
} else {
return "You lose. Maybe next time...";
}
}
let playerSelection = prompt("Make your choose: Rock, Paper or Scissors?");
let computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
console.log('player choice is: ' + playerSelection.toUpperCase());

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

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

Categories

Resources