How using DOM assign value to variable in JS? - javascript

Hello I'm working on Rock,Paper and Scissors project. I'm stuck at this problem. I don't know how to assign value to variable using DOM. When user clicks rock button the value of rocks hould be passed to variable and the variable should be used in playRound function. I don't understand how to fix the problem. When I click to button nothing works.
//Gives the random item to item var
function computerPlay() {
const theArr = ["rock", "paper", "scissors"];
var item = theArr[Math.floor(Math.random() * 3)];
return item;
}
//Returns players selection
function playerPlay(e) {
var pItem = e;
console.log(`${e}`);
return pItem;
}
var r = document.querySelector('.rock').addEventListener('click', playerPlay);
var p = document.querySelector('.paper').addEventListener('click', playerPlay);
var s = document.querySelector('.scissors').addEventListener('click', playerPlay);
var play = document.querySelector('.playbtn').addEventListener('click', playRound);
function playRound(playerSelection, computerSelection) {
playerSelection = playerPlay();
computerSelection = computerPlay();
if (playerSelection == 'rock' && computerSelection == 'paper' || playerSelection == 'paper' && computerSelection == 'scissors' ||
playerSelection == 'scissors' && computerSelection == 'rock') {
window.alert(`${computerSelection} beats ${playerSelection} YOU LOST!`);
} else if (playerSelection == computerSelection) {
window.alert(`${computerSelection} and ${playerSelection} it is a DRAW!`);
} else {
window.alert(`${playerSelection} beats ${computerSelection} YOU WIN!!!`);
}
}
<div class="buttons">
<button class="rock">ROCK</button>
<button class="paper">PAPER</button>
<button class="scissors">SCISSORS</button>
</div>
<div class="play-btn">
<button class="playbtn">PLAY</button>
</div>
</div>
</div>

You're not fetching the player's selection anywhere, and calling playerPlay() manually does not work, because it is supposed to be a callback.
I changed your code a little and the play button can be removed because it is kind of ambiguous. Try this out:
function computerPlay() {
const theArr = ["rock", "paper", "scissors"];
var item = theArr[Math.floor(Math.random() * 3)];
return item;
}
//Returns players selection
function playerPlay(e) {
var playerSelection = e.srcElement.classList[0];
console.log(playerSelection);
computerSelection = computerPlay();
if (playerSelection == 'rock' && computerSelection == 'paper' || playerSelection == 'paper' && computerSelection == 'scissors' || playerSelection == 'scissors' && computerSelection == 'rock') {
window.alert(`${computerSelection} beats ${playerSelection} YOU LOST!`);
} else if (playerSelection == computerSelection) {
window.alert(`${computerSelection} and ${playerSelection} it is a DRAW!`);
} else {
window.alert(`${playerSelection} beats ${computerSelection} YOU WIN!!!`);
}
}
var r = document.querySelector('.rock').addEventListener('click', playerPlay);
var p = document.querySelector('.paper').addEventListener('click', playerPlay);
var s = document.querySelector('.scissors').addEventListener('click', playerPlay);

Related

how to use for loop for functions

hope you all doing well. I am making a "Rock Paper Scissors" game for 'TheOdinProject', I completed it but here is the problem with loop, when I use it for console it works fine, and when calling a function its not looping. sorry for the bad english.
The last function game() is for looping, please help me to find the problem. thanks in advance.
function getComputerChoice() {
const gameChoice = ['rock', 'paper', 'scissor'];
const randomChoice = gameChoice[Math.floor(Math.random() * gameChoice.length)];
// console.log(randomChoice);
return randomChoice;
}
function playRound(playerSelection, computerSelection) {
switch (true) {
case (playerSelection === computerSelection):
return console.log('Game Tie, please try again.');
break;
case (playerSelection === 'rock' && computerSelection === 'scissor'):
let greetingRock = `You Choose: ${playerSelection} and`;
return console.log(`${greetingRock} You Win, Rock beats the scissor`);
break;
case (playerSelection === 'rock' && computerSelection === 'paper'):
let courageRock = `You Choose: ${playerSelection} and`;
return console.log(`${courageRock} You Lose, Paper beats the Rock`);
break;
case (playerSelection === 'scissor' && computerSelection === 'rock'):
let courageScissor = `You Choose: ${playerSelection} and`;
return console.log(`${courageScissor} You Lose, Rock beats the scissor`);
break;
case (playerSelection === 'scissor' && computerSelection === 'paper'):
let greetingScissor = `You Choose: ${playerSelection} and`;
return console.log(`${greetingScissor} You Win, Scissor beats the Paper`);
break;
case (playerSelection === 'paper' && computerSelection === 'scissors'):
let couragePaper = `You Choose: ${playerSelection} and`;
return console.log(`${couragePaper} You Lose, Scissor beats the Paper`);
break;
case (playerSelection === 'paper' && computerSelection === 'rock'):
let greetingPaper = `You Choose: ${playerSelection} and`;
return console.log(`${greetingPaper} You Win, Paper beats the Rock`);
break;
}
}
let userValue = prompt('Choose your Item:', '').toLowerCase();
if( userValue == null || userValue == "") {
prompt('Please Choose one of: Rock, Paper, scissor')
}
const playerSelection = userValue;
const computerSelection = getComputerChoice();
// console.log(playRound(playerSelection, computerSelection))
function game() {
for ( let i = 0; i < 5; i++ ) {
let playAgain = playRound(playerSelection, computerSelection);
return playAgain;
}
}
game();
// console.log(game());
function getComputerChoice() {
const gameChoice = ['rock', 'paper', 'scissor'];
const randomChoice = gameChoice[Math.floor(Math.random() * gameChoice.length)];
// console.log(randomChoice);
return randomChoice;
}
function playRound(playerSelection, computerSelection) {
switch (true) {
case (playerSelection === computerSelection):
console.log('Game Tie, please try again.');
break;
case (playerSelection === 'rock' && computerSelection === 'scissor'):
let greetingRock = `You Choose: ${playerSelection} and`;
console.log(`${greetingRock} You Win, Rock beats the scissor`);
break;
case (playerSelection === 'rock' && computerSelection === 'paper'):
let courageRock = `You Choose: ${playerSelection} and`;
console.log(`${courageRock} You Lose, Paper beats the Rock`);
break;
case (playerSelection === 'scissor' && computerSelection === 'rock'):
let courageScissor = `You Choose: ${playerSelection} and`;
console.log(`${courageScissor} You Lose, Rock beats the scissor`);
break;
case (playerSelection === 'scissor' && computerSelection === 'paper'):
let greetingScissor = `You Choose: ${playerSelection} and`;
console.log(`${greetingScissor} You Win, Scissor beats the Paper`);
break;
case (playerSelection === 'paper' && computerSelection === 'scissors'):
let couragePaper = `You Choose: ${playerSelection} and`;
console.log(`${couragePaper} You Lose, Scissor beats the Paper`);
break;
case (playerSelection === 'paper' && computerSelection === 'rock'):
let greetingPaper = `You Choose: ${playerSelection} and`;
console.log(`${greetingPaper} You Win, Paper beats the Rock`);
break;
}
}
function getPlayerChoice() {
const userValue = prompt('Choose your Item:', '').toLowerCase();
if (userValue == null || userValue == '') {
prompt('Please choose one of: Rock, Paper, Scissor');
}
const playerSelection = userValue;
const computerSelection = getComputerChoice();
console.log(playRound(playerSelection, computerSelection));
}
function game() {
let playAgain;
for (let i = 0; i < 5; i++) {
playAgain = getPlayerChoice();
}
}
game()

I am unable to pass my button's event into my function's parameter

I am trying to make a simple rock paper scissors game and so far I've written this much code but I'm not sure how to get the value of my buttons (rock, paper, scissors) to pass through my function parameters.
I have identified the values in javascript using an array but also in html using "value =" inside the button tag of the selection
const scorePlayer = document.getElementsByClassName("playerScore")
const scoreComputer = document.getElementsByClassName("computerScore")
const buttons = document.querySelectorAll("button")
const results = document.getElementsByClassName("Results")
buttons.forEach(button => {
button.addEventListener('click', function() {
playRound(this.value)
})
})
let playerScore = 0
let computerScore = 0
function computerPlay() {
const selections = ["rock", "paper", "scissors"]
return selections[Math.floor(Math.random() * selections.length)];
}
function playRound(playerSelection) {
let computerSelection = computerPlay()
let result = ""
if (playerSelection == "rock" && computerSelection == "scissors" || playerSelection == "paper" && computerSelection == "rock" || playerSelection == "scissors" && computerSelection == "paper") {
result = ("you win! " + playerSelection + " beats " + computerSelection + "!")
playerScore += 1
}
if (playerSelection == "scissors" && computerSelection == "rock" || playerSelection == "rock" && computerSelection == "paper" || playerSelection == "paper" && computerSelection == "scissors") {
result = ("you lose! " + computerSelection + " beats " + playerSelection + "!")
computerScore += 1
} else if (playerSelection == computerSelection) {
result = ("its a draw");
}
results.innerhtml = result
return
}
scorePlayer.innerhtml = playerScore
scoreComputer.innerhtml = computerScore
<div class="playerScore"></div>
<div class="computerScore"></div>
<button value="rock">Rock</button>
<button value="paper">Paper</button>
<button value="scissors">Scissors</button>
Typos like innerhtml instead of innerHTML
Issues like
getElementsByClassName returns a nodelist
missing quotes in the array
Missing showing the score
const scorePlayer = document.querySelector(".playerScore")
const scoreComputer = document.querySelector(".computerScore")
const buttons = document.querySelectorAll("button")
const results = document.querySelector(".results")
const selections = ["rock", "paper", "scissors"]
let playerScore = 0
let computerScore = 0
buttons.forEach(button => {
button.addEventListener('click', function() {
playRound(this.value)
})
})
function computerPlay() {
return selections[Math.floor(Math.random() * selections.length)];
}
function playRound(playerSelection) {
let computerSelection = computerPlay()
let result = "It's a draw"; // default
console.log(playerSelection,computerSelection)
if (playerSelection === "rock" && computerSelection === "scissors" ||
playerSelection === "paper" && computerSelection === "rock" ||
playerSelection === "scissors" && computerSelection === "paper") {
result = ("you win! " + playerSelection + " beats " + computerSelection + "!")
playerScore += 1
}
if (playerSelection === "scissors" && computerSelection === "rock" ||
playerSelection === "rock" && computerSelection === "paper" ||
playerSelection === "paper" && computerSelection === "scissors") {
result = ("you lose! " + computerSelection + " beats " + playerSelection + "!")
computerScore += 1
}
scorePlayer.innerHTML = playerScore
scoreComputer.innerHTML = computerScore
results.innerHTML = result
}
scorePlayer.innerhtml = playerScore
scoreComputer.innerhtml = computerScore
<button value="rock">Rock</button>
<button value="paper">Paper</button>
<button value="scissors">Scissors</button>
<div class="playerScore"></div>
<div class="computerScore"></div>
<div class="results"></div>

Function is not called when button is clicked but works fine in console

I am trying to call a function with a specific parameter when button is clicked but it just won't work. Functions playRock and playRound work when tested in console but not with event listener. Please let me know what the problem is, I spent 8h trying to make it work.
It may have something to do with my lack of understanding how callback functions work. I could really use an example on how to call function playRound('rock') when button is pressed.
All examples I found online would have functions without parameters in them or a confusing callback functions.
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button id="rockbtn">Rock</button>
<button id="papertn">Paper</button>
<button id="scissorsbtn">Scissors</button>
<script>
// Call PlayRock upon clicking button #rockbtn
const rockbtn = document.querySelector('#rockbtn');
rockbtn.addEventListener('click', playRock);
// Call function playRound with propery 'rock'
function playRock() {
result = playRound('rock');
return result
}
// Randomly selects computer's choice out of rock, paper or scissors
function computerPlay() {
const choices = ['rock', 'paper', 'scissors'];
let choice = choices[Math.floor(Math.random()*choices.length)];
return choice
}
// Plays round of rock, paper, scissors between computer and player
function playRound(playerSelection) {
playerSelection = playerSelection.toLowerCase();
computerSelection = computerPlay();
let result;
if (playerSelection !== 'rock' & playerSelection !== 'paper' & playerSelection !== 'scissors'){
result = 'There is no such choice. Please choose either rock, paper or scissors.';
} else if (playerSelection === computerSelection) {
result = 'It is a draw!';
} else if (playerSelection === 'rock' & computerSelection === 'paper') {
result = 'You lost! Paper beats rock.';
} else if (playerSelection === 'rock' & computerSelection === 'scissors') {
result = 'You won! Rock beats scissors.';
} else if (playerSelection === 'paper' & computerSelection === 'scissors') {
result = 'You lost! Scissors beat paper.';
} else if (playerSelection === 'paper' & computerSelection === 'rock') {
result = 'You won! Paper beats rock.';
} else if (playerSelection === 'scissors' & computerSelection === 'paper') {
result = 'You won! Scissors beat paper.';
} else if (playerSelection === 'scissors' & computerSelection === 'rock') {
result = 'You lost! Rock beats scissors.';
}
return result
}
/* function game() {
let playerScore = 0;
let computerScore = 0;
let finalResult;
for (let i = 0; i < 5; i++) {
let outcome = playRound();
if (roundResult = outcome.includes('won')) {
playerScore += 1;
console.log('You won this round!');
} else if (roundResult = outcome.includes('lost')) {
computerScore += 1;
console.log('You won this round!');
} else {
console.log('This round ended in a draw!');
}
}
if (playerScore > computerScore) {
finalResult = `Congratulations! You won ${playerScore} to ${computerScore}!`;
} else {
finalResult = `You lost ${playerScore} to ${computerScore}`;
}
return finalResult;
}
*/
</script>
</body>
</html>
// Call PlayRock upon clicking button #rockbtn
const rockbtn = document.querySelector('#rockbtn');
rockbtn.addEventListener('click', playRock);
// Call function playRound with propery 'rock'
function playRock() {
result = playRound('rock');
return result
}
// Randomly selects computer's choice out of rock, paper or scissors
function computerPlay() {
const choices = ['rock', 'paper', 'scissors'];
let choice = choices[Math.floor(Math.random() * choices.length)];
return choice
}
// Plays round of rock, paper, scissors between computer and player
function playRound(playerSelection) {
playerSelection = playerSelection.toLowerCase();
computerSelection = computerPlay();
let result;
if (playerSelection !== 'rock' & playerSelection !== 'paper' & playerSelection !== 'scissors') {
result = 'There is no such choice. Please choose either rock, paper or scissors.';
} else if (playerSelection === computerSelection) {
result = 'It is a draw!';
} else if (playerSelection === 'rock' & computerSelection === 'paper') {
result = 'You lost! Paper beats rock.';
} else if (playerSelection === 'rock' & computerSelection === 'scissors') {
result = 'You won! Rock beats scissors.';
} else if (playerSelection === 'paper' & computerSelection === 'scissors') {
result = 'You lost! Scissors beat paper.';
} else if (playerSelection === 'paper' & computerSelection === 'rock') {
result = 'You won! Paper beats rock.';
} else if (playerSelection === 'scissors' & computerSelection === 'paper') {
result = 'You won! Scissors beat paper.';
} else if (playerSelection === 'scissors' & computerSelection === 'rock') {
result = 'You lost! Rock beats scissors.';
}
return result
}
/* function game() {
let playerScore = 0;
let computerScore = 0;
let finalResult;
for (let i = 0; i < 5; i++) {
let outcome = playRound();
if (roundResult = outcome.includes('won')) {
playerScore += 1;
console.log('You won this round!');
} else if (roundResult = outcome.includes('lost')) {
computerScore += 1;
console.log('You won this round!');
} else {
console.log('This round ended in a draw!');
}
}
if (playerScore > computerScore) {
finalResult = `Congratulations! You won ${playerScore} to ${computerScore}!`;
} else {
finalResult = `You lost ${playerScore} to ${computerScore}`;
}
return finalResult;
}
*/
<button id="rockbtn">Rock</button>
<button id="papertn">Paper</button>
<button id="scissorsbtn">Scissors</button>
In functions, when you return something, that is just passing that data to the caller of that function. It doesn't show it to the user.
In the below example, the user will not have any clue that aa was returned as it isn't being shown or alerted in anyway.
function test(){
return test2("aa");
}
function test2(str){
return str;
}
For learning, at the end of function playRound(playerSelection) {
just add alert(result);
That will just popup a message to the user telling them the result. There are many other ways to do this, this is just the easiest for learning.
you can also use console.log(result); to show the results in the console.
In the below code, I add a class to all of the buttons, and use a data attribute to hold the button's action (ie rock, paper, scissors).
Then in the javascript I loop through the buttons and add an event handler to each that grabs that data attribute and passes it to playRound.
For testing, I didn't use your for playRound function, mine is for demo purposes only.
let btns = document.querySelectorAll(".btn");
function playRound(action){
console.log(action)
}
btns.forEach(function(el){
el.addEventListener("click",function(e){
playRound(e.target.getAttribute("data-action"));
});
});
<button class="btn" data-action="rock">Rock</button>
<button class="btn" data-action="paper">Paper</button>
<button class="btn" data-action="scissors">Scissors</button>

i need help Rock , paper and scissors exercise

i did the "mechanics" but i tried to figured out how to play more rounds, i try a do_while loop but no work so what could be a good practice for more rounds?
const arrayPlay = ["rock","paper","scissors"];
const computerPlay = () =>{
return arrayPlay[~~(Math.random()*arrayPlay.length)]
}
let playerScore = 0;
let computerScore = 0;
const playRound = (playerSelection,computerSelection) =>{
if(playerSelection == "rock" && computerSelection == "scissors"){
console.log("player get's one point");
playerScore += 1;
}else if(playerSelection == "paper" && computerSelection == "rock"){
console.log("player get's one point");
playerScore += 1;
}else if(playerSelection == "scissors" && computerSelection == "paper"){
console.log("player get's one point");
playerScore += 1;
}
if(computerSelection == "rock" && playerSelection == "scissors"){
console.log("computer get's one point");
computerScore += 1;
}else if(computerSelection == "paper" && playerSelection == "rock"){
console.log("computer get's one point");
computerScore += 1;
}else if(computerSelection == "scissors" && playerSelection == "paper"){
console.log("computer get's one point");
computerScore += 1;
}
}
const playerSelection = prompt("rock,paper or scissors");
const computerSelection = computerPlay();
playRound(playerSelection,computerSelection);
You could move the playerSelection and computerSelection constants inside the playRound function. Then you can use the Window.confirm() method to show the results with a prompt to play again. If they select OK, then just call the playRound function again. If they click cancel then the game stops.
See snippet below.
More on Window.confirm() here: https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm
const arrayPlay = ["rock", "paper", "scissors"];
const computerPlay = () => arrayPlay[~~(Math.random() * arrayPlay.length)];
let playerScore = 0;
let computerScore = 0;
const playRound = () => {
let playerSelection = prompt(`Please enter either "rock", "paper" or "scissors"`);
playerSelection = playerSelection ? playerSelection.toLowerCase() : playerSelection;
if (arrayPlay.includes(playerSelection)) {
const computerSelection = computerPlay();
let winner;
if (playerSelection == "rock" && computerSelection == "scissors") {
playerScore += 1;
winner = `player`;
} else if (playerSelection == "paper" && computerSelection == "rock") {
playerScore += 1;
winner = `player`;
} else if (playerSelection == "scissors" && computerSelection == "paper") {
playerScore += 1;
winner = `player`;
} else if (computerSelection == "rock" && playerSelection == "scissors") {
computerScore += 1;
winner = `computer`;
} else if (computerSelection == "paper" && playerSelection == "rock") {
computerScore += 1;
winner = `computer`;
} else if (computerSelection == "scissors" && playerSelection == "paper") {
computerScore += 1;
winner = `computer`;
}
showResults(computerSelection, playerSelection, winner);
} else if (playerSelection != null){
if (confirm(`The value you entered: "${playerSelection}" is invalid.\n\nWould you like to try again?`)) {
playRound();
}
}
}
const showResults = (computer, player, winner) => {
const playAgain = confirm(`
---Selection---
Player: ${player}
Computer: ${computer}
Results: ${winner ? `${winner} WINS!!` : "Draw"}
----Score----
Player: ${playerScore}
Computer: ${computerScore}
Would you like to play again?`);
if (playAgain) {
playRound();
} else {
playerScore = 0;
computerScore = 0;
}
}
playRound();
const arrayPlay = ["rock","paper","scissors"];
const computerPlay = () =>{
return arrayPlay[~~(Math.random()*arrayPlay.length)]
}
let playerScore = 0;
let computerScore = 0;
let keepPlaying = true;
// added keep playing condition and a while loop
while(keepPlaying) {
const playRound = (playerSelection,computerSelection) =>{
// empty input or 'quit' will end the game
if (playerSelection == "" || playerSelection == "quit") {
keepPlaying = false;
}
else if(playerSelection == "rock" && computerSelection == "scissors"){
console.log("player get's one point");
playerScore += 1;
}else if(playerSelection == "paper" && computerSelection == "rock"){
console.log("player get's one point");
playerScore += 1;
}else if(playerSelection == "scissors" && computerSelection == "paper"){
console.log("player get's one point");
playerScore += 1;
}
if(computerSelection == "rock" && playerSelection == "scissors"){
console.log("computer get's one point");
computerScore += 1;
}else if(computerSelection == "paper" && playerSelection == "rock"){
console.log("computer get's one point");
computerScore += 1;
}else if(computerSelection == "scissors" && playerSelection == "paper"){
console.log("computer get's one point");
computerScore += 1;
}
}
const playerSelection = prompt("rock,paper or scissors");
const computerSelection = computerPlay();
playRound(playerSelection,computerSelection);
// logging the new results
console.log({playerScore, computerScore})
}
const playRound = (playerSelection,computerSelection) =>{
if(playerSelection == computerSelection) return console.log("tie!")
//rest of your code here
}
console.log("Type end or stop to finish the game.");
while(true){
const playerSelection = prompt("rock, paper or scissors");
if(playerSelection == "end" || playerSelection == "stop"){
//code to show who won
break;
}
const computerSelection = computerPlay();
playRound(playerSelection,computerSelection);
}
Next time show code on what you tried, and what part wasn't working.

Rock, Paper, Scissors game: entering the correct value returns the wrong console.log message

Sometimes when I enter "rock" in the prompt and hit OK, the console will say "Please type Rock, Paper, or Scissors" even in case I had actually done that. I believe this is due to the else clause, I'm just not sure what I did wrong.
Also, other times when I enter "rock" in the prompt and hit OK, nothing happens in the console (no score is added). Below is the screenshot
const playerSelection = ''
const computerSelection = computerPlay()
let computerScore = 0;
let playerScore = 0;
console.log(playRound(playerSelection, computerSelection))
function computerPlay(){
let values = ['rock', 'paper', 'scissors'],
valueToUse = values [Math.floor(Math.random()* values.length)];
return valueToUse;
};
function playRound(playerSelection, computerSelection) {
while(true){
playerSelection = prompt ('Pick your poison');
if (playerSelection.toLowerCase() === 'rock' && computerPlay() === 'paper'){
computerScore += 1
console.log('Sorry! Paper beats Rock')
}
else if (playerSelection.toLowerCase() === 'rock'.toLowerCase() && computerPlay() === 'scissors'){
playerScore += 1
console.log('Good job! Rock beats Scissors');
}
else
{
console.log('Please type Rock, Paper, or Scissors')
}
console.log (`User Selection: ${playerSelection.toUpperCase()} | Player Score: ${playerScore}
Computer Selection: ${computerSelection.toUpperCase()} | Computer Score: ${computerScore}`);
}
}
You only call computerSelection once, at the beginning of pageload:
const computerSelection = computerPlay()
It then proceeds to only get used in the log:
Computer Selection: ${computerSelection.toUpperCase()} |
But your tests call computerPlay again, creating new strings for the computer every time:
if (playerSelection.toLowerCase() === 'rock' && computerPlay() === 'paper'){
// function invocation ^^^^^^^^^^^^^^
computerScore += 1
console.log('Sorry! Paper beats Rock')
}
else if (playerSelection.toLowerCase() === 'rock'.toLowerCase() && computerPlay() === 'scissors'){
// function invocation ^^^^^^^^^^^^^^
In addition to that, you aren't exhaustively testing each possibility for rock-paper-scissors (like when the player picks something other than 'rock').
To start with, call computerPlay only once, then use the computerSelection variable:
if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'paper') {
computerScore += 1
console.log('Sorry! Paper beats Rock')
} else if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'scissors') {
Also note that there isn't much point calling toLowerCase on something that's already a lower-cased string literal - just use the plain string.
You can update the code as following
Remove all unnecessary global variable declarations.
Remove unnecessary arguments of playRound function.
Add more logic for other player selection cases.
Nest condition for computer selection cases.
playRound();
function computerPlay(){
let values = ['rock', 'paper', 'scissors'],
valueToUse = values [Math.floor(Math.random()* values.length)];
return valueToUse;
};
function playRound() {
let playerSelection;
let computerSelection;
let playerScore = 0;
let computerScore = 0;
while(true){
playerSelection = prompt('Pick your poison').toLowerCase();
computerSelection = computerPlay();
if (playerSelection === 'rock') {
if (computerSelection === 'paper') {
computerScore += 1;
} else if (computerSelection === 'scissors') {
playerScore += 1;
}
} else if (playerSelection === 'paper') {
if (computerSelection === 'scissors') {
computerScore += 1;
} else if (computerSelection === 'rock') {
playerScore += 1;
}
} else if (playerSelection === 'scissors') {
if (computerSelection === 'rock') {
computerScore += 1;
} else if (computerSelection === 'paper') {
playerScore += 1;
}
} else {
console.log('Please type Rock, Paper, or Scissors');
continue;
}
console.log (`User Selection: ${playerSelection.toUpperCase()} | Player Score: ${playerScore}
Computer Selection: ${computerSelection.toUpperCase()} | Computer Score: ${computerScore}`);
}
}
Here is a minimalist version of the game as a complete rewrite:
function game(){
var usr, u, c, g, score=[0,0],last="";
const words=["rock","paper","scissors"];
while(usr=prompt(last+"\nScore (you:computer): "+score.join(":")+"\nYour choice:")) {
while((u=words.indexOf(usr.toLowerCase()))<0) usr=prompt("invalid choice, please enter again,\none of: "+words.join(", "));
c=Math.floor(Math.random()*3);
g=(3+u-c)%3; // who wins?
if(g) score[g-1]++;
last="you: "+words[u]+", computer: "+words[c]+" --> "
+["draw","you win!!!","you lost - sorry."][g];
}
}
game()

Categories