I've put playerScore and computerScore variables in global scope. When user wins or loses these values increment by one number. They do work well. But in my HTML page they do not change dynamically.
Why my playerScore and computerScore values do not change in my HTML page, when I console.log them separately in console they are changed, but not in html page. I've tried to put them in function but it didn't work as expected.
// Selecting all the items with tag button
const buttons = document.querySelectorAll('button');
// Returns random item and assignes it to computerSelection variable
function computerPlay() {
const rps = ['rock', 'paper', 'scissors'];
let numberItem = Math.floor(Math.random() * rps.length);
computerSelection = rps[numberItem];
if (computerSelection === 'rock') {
console.log('computer selections is rock');
return computerSelection;
}
else if (computerSelection === 'paper' ) {
console.log('It is a paper!');
return computerSelection;
}
console.log('it is scissors');
return computerSelection;
}
// Plays game only five rounds;
let computerScore = 0;
let playerScore = 0;
function playRound(playerSelection, computerSelection) {
if(playerScore < 5 && computerScore < 5 ) {
if(((playerSelection == 'rock') && (computerSelection == 'paper')) || ((playerSelection == 'paper') && (computerSelection == 'scissors')) ||
((playerSelection == 'scissors') && (computerSelection == 'rock') )) {
console.log(`${computerSelection} beats ${playerSelection} the ROBOT WINS!`);
playerScore++;
return console.log(playerScore);
}
else if (((playerSelection == 'rock') && (computerSelection == 'scissors')) || ((playerSelection == 'paper') && (computerSelection == 'rock')) ||
((playerSelection == 'scissors') && (computerSelection == 'paper'))) {
console.log(` ${playerSelection} beats ${computerSelection} the PLAYER WINS!`);
computerScore++;
return console.log(computerScore);
}
return console.log('It is a DRAW');;
}
return console.log("GAME OVER!!!");
}
// returns value of clicked button and plays round
function fetchButtonValue(e) {
let itemClicked = e.target.dataset.item;
console.log(` THIS WAS CLICKED ${itemClicked}`);
return playRound(itemClicked, computerPlay());
}
// uses fetchButtonValue
buttons.forEach(function(button) {
button.addEventListener('click', fetchButtonValue);
});
// implement the vlaues to HTML but they doesn't change but the value changes when tracking them in console of browser.
let score= `
<p class = 'playerPoints'>Player: ${playerScore}</p>
<p class = 'computerPoints'>Computer: ${computerScore}</p>
`;
const divScore = document.querySelector('.score');
divScore.insertAdjacentHTML('beforebegin', scoreHTML);
Related
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;
}
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)
});
I am creating rock paper scissors with a user interface in html/css.
I have 3 html buttons for the choices:
<div class="options">
<button class="button rock"><i class="fas fa-hand-rock fa-10x"></i>Rock</button>
<button class="button paper"><i class="fas fa-toilet-paper fa-10x"></i>Paper</button>
<button class="button scissor"><i class="fas fa-cut fa-10x"></i>Scissor</button>
</div>
My problem is connecting a click event on the buttons to input as the player selection variable in the playRound function. Can someone provide insight on how to accomplish this. I was trying to connect them in the userPlay function using event listeners. Thanks in advance.
Javascript:
// returns a random computer choice
function computerPlay() {
options = ['Rock', 'Paper', 'Scissor'];
return options[Math.floor(Math.random() * options.length)]
}
// should return a user choice
function userPlay() {
let rock = document.querySelector('.button.rock');
rock.addEventListener('click', setChoice);
let paper = document.querySelector('.button.paper');
paper.addEventListener('click', setChoice)
let scissor = document.querySelector('.button.scissor');
scissor.addEventListener('click', setChoice)
var userChoice;
function setChoice() {
userChoice=
}
return userChoice
}
function playRound() {
// defining the starting score
let playerScore = 0;
let computerScore = 0;
// play 5 times per round
for (let i = 0; i <= 4; i++) {
computerSelection = computerPlay();
playerSelection = userPlay()
// game conditionals
if (
(playerSelection === 'Rock' && computerSelection === 'Paper') ||
(playerSelection === 'Paper' && computerSelection === 'Scissor') ||
(playerSelection === 'Scissor' && computerSelection === 'Rock')
) {
computerScore++;
console.log(`Computer: ${computerSelection} You: ${playerSelection} You Lost`)
console.log(`computer: ${computerScore} You: ${playerScore}`)
}
if (
(playerSelection === 'Paper' && computerSelection === 'Rock') ||
(playerSelection === 'Scissor' && computerSelection === 'Paper') ||
(playerSelection === 'Rock' && computerSelection === 'Scissor')
) {
playerScore++;
console.log(`Computer: ${computerSelection} You: ${playerSelection} You Won`)
console.log(`computer: ${computerScore} You: ${playerScore}`)
}
if (playerSelection === computerSelection) {
console.log(`Computer: ${computerSelection} You: ${playerSelection} Its a tie`);
console.log(`computer: ${computerScore} You: ${playerScore}`);
continue
}
}
// ending score
if (computerScore > playerScore) {
console.log('Sorry, you lost')
}
if (playerScore > computerScore) {
console.log('Congrats, you won')
}
else {
'It was a tie game'
}
}
You don't want the events inside the function.
Consider using a data-attribute on the buttons and event delegations like this
<button data-shake='rock'>
.
document.addEventListener('click', function(event) {
if ( event.target.matches('button') ) {
runFunction(event.target.dataset.shake); // would get 'rock' etc...
}
});
You can use the arrow function so you'd be able to pass a parameter to the function.
(Read more about it: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#event_listener_with_an_arrow_function)
let rock = document.querySelector('.button.rock');
rock.addEventListener('click', () => {setChoice("scissor")});
let paper = document.querySelector('.button.paper');
paper.addEventListener('click', () => {setChoice("scissor")})
let scissor = document.querySelector('.button.scissor');
scissor.addEventListener('click', () => {setChoice("scissor")})
var userChoice;
function setChoice(userChoice) {
// ....
}
I am building my first rock paper scissors game. I have not formally done loops as yet but I am trying to apply a for loop to the playRound function so it plays five times. Sadly I am not certain where to apply it. I have tried a few ways but keep getting errors. Anyone able to take a look and provide an option. code is below.
function computerPlay() {
const number = Math.floor(Math.random() * 1000);
if (number % 3 === 0) {
return "rock";
}
if (number % 3 === 1) {
return "paper";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
playerSelection = "rock";
computerSelection = computerPlay();
if (
(playerSelection == "rock" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "rock")
) {
return "Player Wins!";
} else if (
(playerSelection == "rock" && computerSelection == "paper") ||
(playerSelection == "paper" && computerSelection == "scissors") ||
(playerSelection == "scissors" && computerSelection == "rock")
) {
return "Computer Wins!";
} else {
return "Tie";
}
}
playerSelection = "rock";
computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
If I understood correctly what you want, you can do a while loop with a counter, also I improved a bit your code, making strict equality (from == to ===), and removed redundant code
let counter = 1;
function computerPlay() {
const number = Math.floor(Math.random() * 1000);
if (number % 3 === 0) {
return "rock";
} else if (number % 3 === 1) {
return "paper";
} else {
return "scissors";
}
}
function playRound(playerSelection, computerSelection) {
counter++;
if (
(playerSelection === "rock" && computerSelection === "scissors") ||
(playerSelection === "scissors" && computerSelection === "paper") ||
(playerSelection === "paper" && computerSelection === "rock")
) {
return "Player Wins!";
} else if (
(playerSelection === "rock" && computerSelection == "paper") ||
(playerSelection === "paper" && computerSelection === "scissors") ||
(playerSelection === "scissors" && computerSelection === "rock")
) {
return "Computer Wins!";
} else {
return "Tie";
}
}
playerSelection = "rock";
while (counter < 6) {
console.log(playRound(playerSelection, computerPlay()));
}
Hope this example gives some hint on how to do good programming
// rock = 0
// paper = 1
// scissor = 2
const valueMap = {
0: 'rock',
1: 'paper',
2: 'scissor'
}
function pick() {
return Math.floor(Math.random() * 3)
}
function decide(p1, p2) {
const pool = [p1, p2]
const sortedPool = pool.sort((a, b) => b.value - a.value)
const diff = sortedPool[0].value - sortedPool[1].value
if (diff === 2) {
return sortedPool[1].name
} else if (diff === 0) {
return 'draw'
} else {
return pool.find(v => v.value === sortedPool[0].value).name
}
}
function play(times, cb) {
let n = 1
while (n <= times) {
cb(n)
n++
}
}
play(5, function(n) {
const player1 = {
name: 'Player',
value: pick()
}
const player2 = {
name: 'Computer',
value: pick()
}
const result = decide(player1, player2)
console.log(
`Game ${n}`,
`${player1.name} ${valueMap[player1.value]}`,
` vs `,
`${player2.name} ${valueMap[player2.value]}`,
`>>> Winner ${result}
`
)
})
Add loop for last 3 line
for (i=0; i<5; i++){
playerSelection = "rock";
computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));
}
Edit: Please note that you have redundant call function computerPlay() inside playRound function since computer selection is passed in second argument
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();
});