I am new to coding I have to do this rock paper scissors but can't find my error it still show me the else result each time.
Any help are welcome
// Get the computer choice
function getComputerChoice() {
"use strict";
const computerPlay = Math.floor(Math.random()*3);
if (computerPlay === 1){
return("rock")
}
else if(computerPlay === 2){
return ("paper")
}
else {
return ("scissors")
}
}
// Get the user choice
function getUserChoice(){
prompt("Please enter 'rock', 'paper', 'scissors': ").toLowerCase();
}
// Play a round
function playRound(){
let computerSelection = getComputerChoice();
let playerSelection = getUserChoice();
if (computerSelection === playerSelection){
console.log("Game is a Tie")
}
else if (computerSelection == 'paper' && playerSelection == 'rock'){
console.log("Computer Win")
}
else if (computerSelection == 'rock' && playerSelection == 'scissors'){
console.log("Computer Win")
}
else if (computerSelection == 'scissors' && playerSelection == 'paper'){
console.log("Computer Win")
}
else {
console.log("User Win")
}
}
// Play Game function
function playGame(){
for (let i = 0; i < 5; i++){
playRound()
}
}
playGame()
I try the if seems it miss something to run correctly.
Solution
You've missed the return keyword from the getUserChoice method.
function getUserChoice(){
return prompt("Please enter 'rock', 'paper', 'scissors': ").toLowerCase();
}
Related
I am working on a game of rock, paper, scissors in the course "The Odin Project." Unfortunately, I've been at a standstill for several days because I can't figure out how to set the outcome of the duel. I am uploading my code below. I am a beginner so please understand :) I would appreciate your help.
const choice = ['rock', 'paper', 'scissors']
function getComputerChoice() {
const computerPlay = choice[Math.floor(Math.random() * choice.length)]
return computerPlay
}
function playRound(playerSelection, computerSelection) {
let YouLose = `You lose ${computerSelection} beats ${playerSelection.toLowerCase()}!`
let YouWin = `You win ${playerSelection.toLowerCase()} beats ${computerSelection}!`
if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'paper') {
return YouLose
score ++
} else if (playerSelection.toLowerCase() === 'paper' && computerSelection === 'rock') {
return YouWin
}
else if (playerSelection.toLowerCase() === 'paper' && computerSelection === 'scissors') {
return YouLose
}
else if (playerSelection.toLowerCase() === 'scissors' && computerSelection === 'paper') {
return YouWin
} else if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'scissors') {
return YouLose
}
else if (playerSelection.toLowerCase() === 'scissors' && computerSelection === 'rock') {
return YouLose
}else if(playerSelection.toLowerCase() === computerSelection) {
return "Tie!"
} else {
return "Error"
}
}
// function checkWinner() {
// if (playRound(playerSelection, computerSelection) === YouWin) {
// playerScore++;
// }else if (playRound(playerSelection, computerSelection) === YouLose) {
// computerScore++;
// }
// }
function game() {
console.log("Let's play the game!");
let playerScore = 0
let computerScore = 0
for (let i = 0; i < 5; i++) {
const playerSelection = prompt('What do you choose, rock, scissors or paper?')
const computerSelection = getComputerChoice()
playRound(playerSelection, computerSelection)
if (playRound(playerSelection.toLowerCase(), computerSelection) === YouWin) {
playerScore++;
}else if (playRound(playerSelection.toLowerCase(), computerSelection) === YouLose) {
computerScore++;
}
console.log(playRound(playerSelection, computerSelection));
console.log('-------------------');
console.log(playerScore);
console.log(computerScore);
}
}
console.log(game());
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="script.js"></script>
<title>Document</title>
</head>
<body>
<script>
// function computerPlay() {
// let game = ['rock', 'paper' , 'scissors'];
// let randomPlay = Math.floor(Math.random()*game.length);
// return game[randomPlay]
// }
// let player = 0
// let computer = 0
// let round = 0
// function playRound(playerSelection, computerSelection) {
// if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'paper') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// } else if (playerSelection.toLowerCase() === 'paper' && computerSelection === 'rock') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// }
// else if (playerSelection.toLowerCase() === 'paper' && computerSelection === 'scissors') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// }
// else if (playerSelection.toLowerCase() === 'scissors' && computerSelection === 'paper') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// } else if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'scissors') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// }
// else if (playerSelection.toLowerCase() === 'scissors' && computerSelection === 'rock') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// } else if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'rock') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// } else if (playerSelection.toLowerCase() === 'paper' && computerSelection === 'paper') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// } else if (playerSelection.toLowerCase() === 'scissors' && computerSelection === 'scissors') {
// computer++;
// return "You Win! Paper beats Rock";
// console.log(computer);
// } else {
// return "Erorr"
// }
// console.log(computer);
// }
// function game () {
// for (let i = 0; i < 5; i++) {
// playerSelection = prompt('What do you choose, rock, scissors or paper?');
// computerSelection = computerPlay();
// console.log(playRound(playerSelection, computerSelection));
// }
// }
// // console.log(computerSelection);
// // console.log(playerSelection);
// console.log(game());
</script>
</body>
</html>
https://github.com/RadekLewandowski/rock-paper-scissors/blob/6f60d9721a3f7e7835e5e9254cb26fcb766bedc2/script.js
i just fixed your ideas:
const choice = ['rock', 'paper', 'scissors']
function getComputerChoice() {
const computerPlay = choice[Math.floor(Math.random() * choice.length)]
return computerPlay
}
function playRound(playerSelection, computerSelection) {
if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'paper') {
return 'YouLose'
score ++
} else if (playerSelection.toLowerCase() === 'paper' && computerSelection === 'rock') {
return 'YouWin'
}
else if (playerSelection.toLowerCase() === 'paper' && computerSelection === 'scissors') {
return 'YouLose'
}
else if (playerSelection.toLowerCase() === 'scissors' && computerSelection === 'paper') {
return 'YouWin'
} else if (playerSelection.toLowerCase() === 'rock' && computerSelection === 'scissors') {
return 'YouLose'
}
else if (playerSelection.toLowerCase() === 'scissors' && computerSelection === 'rock') {
return 'YouLose'
}else if(playerSelection.toLowerCase() === computerSelection) {
return "Tie!"
} else {
return "Error"
}
}
function game() {
console.log("Let's play the game!");
let playerScore = 0
let computerScore = 0
for (let i = 0; i < 5; i++) {
const playerSelection = prompt('What do you choose, rock, scissors or paper?')
const computerSelection = getComputerChoice()
const outcome = playRound(playerSelection, computerSelection)
if (outcome === 'YouWin')
{
alert(`You win ${playerSelection.toLowerCase()} beats ${computerSelection}!`)
playerScore++;
}
else if (outcome === 'YouLose')
{
computerScore++;
alert(`You lose ${computerSelection} beats ${playerSelection.toLowerCase()}!`)
}
console.log(playRound(playerSelection, computerSelection));
console.log('-------------------');
console.log(playerScore);
console.log(computerScore);
}
}
console.log(game());
Applied lots of fixes, simplified the code which determines whether you win or lose and ended up with this:
const choice = ['rock', 'paper', 'scissors']
function getComputerChoice() {
const computerPlay = choice[Math.floor(Math.random() * choice.length)]
return computerPlay
}
let YouLose;
let YouWin;
function playRound(playerSelection, computerSelection) {
YouLose = `You lose ${computerSelection} beats ${playerSelection.toLowerCase()}!`;
YouWin = `You win ${playerSelection.toLowerCase()} beats ${computerSelection}!`;
let diff = ((choice.indexOf(playerSelection.toLowerCase()) - choice.indexOf(computerSelection.toLowerCase())) + 3) % 3;
switch (diff) {
case 1: return YouWin;
case 2: return YouLose;
default: return "Tie!";
}
}
// function checkWinner() {
// if (playRound(playerSelection, computerSelection) === YouWin) {
// playerScore++;
// }else if (playRound(playerSelection, computerSelection) === YouLose) {
// computerScore++;
// }
// }
function game() {
console.log("Let's play the game!");
let playerScore = 0
let computerScore = 0
function round(index) {
let playerSelection = prompt('What do you choose, rock, scissors or paper?');
while (choice.indexOf(playerSelection ? playerSelection.toLowerCase() : "") < 0) {
playerSelection = prompt('Invalid choice. What do you choose, rock, scissors or paper?');
}
const computerSelection = getComputerChoice();
let result = playRound(playerSelection.toLowerCase(), computerSelection.toLowerCase());
if (result === YouWin) {
playerScore++;
}else if (result === YouLose) {
computerScore++;
}
alert(result);
console.log('-------------------');
console.log('Player: ' + playerScore);
console.log('Computer: ' + computerScore);
setTimeout(function() {
round(index + 1);
}, 1000);
}
round(0);
}
console.log(game());
I'm trying to make a console version of rock paper scissors. The game is working for now but I can't run the for loop, what I want to do is at the end of each round, the console will say what round we are in and tell who won the current round. It will be the Best of 5 and the winner will be determined in round 5.
Since I'm a beginner I couldn't try too much. I know my code is not clean and complicated because I proceed by trying and I'm also new to Stackoverflow, if there is something missing in the topic, I apologize in advance for those.
// PLAYER CODES
let playerSelection = prompt('Do you choose Rock, Paper or Scissors?')
if (playerSelection === 'Rock' || playerSelection === 'Paper' || playerSelection === 'Scissors') {
console.log("You chose " + `${playerSelection}`);
} else {
console.log('Error! Pick Rock, Paper or Scissors')
}
// COMPUTER CODES
let computerSelection = getComputerChoice();
function getComputerChoice() {
let choices = ['Rock', 'Paper', 'Scissors'];
let random = choices[Math.floor(Math.random() * 3)];
return random;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection){
return ('Draw')
} else if ((playerSelection === 'Rock') && (computerSelection === 'Scissors')) {
return ('Player Wins! Rock beats Scissors.')
} else if ((playerSelection === 'Scissors') && (computerSelection === 'Paper')) {
return ('Player Wins! Scissors beats Paper.')
} else if ((playerSelection === 'Paper') && (computerSelection === 'Rock')) {
return ('Player Wins! Paper beats Rock.')
} else if ((computerSelection === 'Scissors') && (playerSelection === 'Paper')) {
return ('Computer Wins! Scissors beats Paper.')
} else if ((computerSelection === 'Paper') && (playerSelection === 'Rock')) {
return ('Computer Wins! Paper beats Rock.')
} else if ((computerSelection === 'Rock') && (playerSelection === 'Scissors')) {
return ('Computer Wins! Rock beats Scissors.')
}
}
function game() {
for (let i = 1; i < 6; i++){
playRound(playerSelection, computerSelection);
if (i == 1)
return ('Round 1')
else if (i == 2)
return ('Round 2')
else if (i == 3)
return ('Round 3')
else if (i == 4)
return ('Round 4')
else if (i == 5)
return ('Round 5')
}
}
console.log("Computer chose " + `${computerSelection}`);
console.log(playRound(playerSelection, computerSelection));
console.log(game(playRound));
You have to put the sections to get the player and computer choices inside the loop. I fixed some other problems, too.
// PLAYER CODES
function getPlayerChoice () {
let playerSelection = prompt('Do you choose Rock, Paper or Scissors?')
if (playerSelection === 'Rock' || playerSelection === 'Paper' || playerSelection === 'Scissors') {
console.log("You chose " + `${playerSelection}`);
return playerSelection
} else {
console.log('Error! Pick Rock, Paper or Scissors')
return getPlayerChoice()
}
}
// COMPUTER CODES
function getComputerChoice() {
let choices = ['Rock', 'Paper', 'Scissors'];
let random = choices[Math.floor(Math.random() * 3)];
return random;
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection){
return ('Draw')
} else if ((playerSelection === 'Rock') && (computerSelection === 'Scissors')) {
return ('Player Wins! Rock beats Scissors.')
} else if ((playerSelection === 'Scissors') && (computerSelection === 'Paper')) {
return ('Player Wins! Scissors beats Paper.')
} else if ((playerSelection === 'Paper') && (computerSelection === 'Rock')) {
return ('Player Wins! Paper beats Rock.')
} else if ((computerSelection === 'Scissors') && (playerSelection === 'Paper')) {
return ('Computer Wins! Scissors beats Paper.')
} else if ((computerSelection === 'Paper') && (playerSelection === 'Rock')) {
return ('Computer Wins! Paper beats Rock.')
} else if ((computerSelection === 'Rock') && (playerSelection === 'Scissors')) {
return ('Computer Wins! Rock beats Scissors.')
}
}
function game() {
for (let i = 1; i < 6; i++){
console.log('Round ' + i)
let playerSelection = getPlayerChoice();
let computerSelection = getComputerChoice();
console.log("Computer chose " + `${computerSelection}`);
console.log(playRound(playerSelection, computerSelection));
}
}
game()
As you can tell by my messy code, I am still a beginner at JavaScript so I'm really sorry If this will hurt your eyes.
I am working on this Rock, Paper, Scissors project from The Odin Project where we would add a simple UI to it by applying DOM Methods. To be honest, I really don't know if I'm doing this right. I feel like the if statements shouldn't be inside the event listener but this is the only way I have found to make the tallying of scores work. By putting the code here I made it playable, but not quite right:
let playerScore = 0;
let computerScore = 0;
let scores = document.createElement('p');
let body = document.querySelector('body');
const results = document.createElement('div');
body.appendChild(results);
const buttons = document.querySelectorAll('button');
buttons.forEach((button) => {
button.addEventListener('click', () => {
let playerSelection = button.className;
let computerSelection = computerPlay();
let roundResult = playRound(playerSelection, computerSelection);
console.log(roundResult);
score();
gameEnd();
if (roundResult === 'playerWin') {
playerScore++;
} else if (roundResult === 'computerWin') {
computerScore++;
}
})
})
//computer pick
function computerPlay() {
const pick = ['rock', 'paper', 'scissors'];
return pick[Math.floor(Math.random() * pick.length)];
}
// Round Play
function playRound(playerSelection, computerSelection) {
//message that specifies the winner
let tie = `It's a tie you both picked ${playerSelection}`;
let playerWin = `You win this round! ${playerSelection} beats ${computerSelection}`;
let computerWin = `You lose this round! ${computerSelection} beats
${playerSelection}`;
if(playerSelection === computerSelection) {
results.innerHTML = tie;
return 'tie';
} else if (playerSelection === 'rock' && computerSelection === 'scisors') {
results.innerHTML = playerWin;
return 'playerWin';
} else if (playerSelection === 'paper' && computerSelection === 'rock') {
results.innerHTML = playerWin;
return 'playerWin';
} else if (playerSelection === 'scissors' && computerSelection === 'paper') {
results.innerHTML = playerWin;
return 'playerWin';
} else {
results.innerHTML = computerWin;
return 'computerWin';
}
}
function score() {
//new element where score would be seen
scores.innerHTML = `player: ${playerScore} | computer: ${computerScore}`;
body.appendChild(scores);
}
function gameEnd() {
if(playerScore === 5 || computerScore === 5) {
document.querySelector('.rock').disabled = true;
document.querySelector('.paper').disabled = true;
document.querySelector('.scissors').disabled = true;
if (playerScore > computerScore) {
alert('You win the game');
} else if (computerScore > playerScore) {
alert('Aww you lose');
}
}
}
<button class="rock">Rock</button>
<button class="paper">Paper</button>
<button class="scissors">Scissors</button>
Here's the problem, scores remain both at 0 after the first round. It would show who the winner is but it won't tally its score until I have picked for the next round. Where exactly did I go wrong with this one? (feels like in everything I'm genuinely sorry if my explanation sounds as confusing as my code.)
Anyways this is what the initial code looks like, before applying the DOM Methods.
I was initially trying to use this code but I cant even tally the scores with this one because I can't seem to get the return value of of the function playRound().
function computerPlay() {
const pick = ['rock', 'paper', 'scissors'];
return pick[Math.floor(Math.random() * pick.length)];
}
function playRound(playerSelection, computerSelection) {
if (playerSelection === computerSelection) {
alert(`It's a tie! you both picked ${playerSelection}`);
return "tie";
} else if (playerSelection !== "rock" && playerSelection !== "paper" &&
playerSelection !== "scissors"){
alert(`You sure about using ${playerSelection} on a game of "Rock, Paper,
Scissors"?`)
} else if (playerSelection === "rock" && computerSelection === "scissors") {
alert(`You win this round! ${playerSelection} beats ${computerSelection}`);
return "playerWin";
} else if (playerSelection === "paper" && computerSelection === "rock") {
alert(`You win this round! ${playerSelection} beats ${computerSelection}`);
return "playerWin";
} else if (playerSelection === "scissors" && computerSelection === "paper") {
alert(`You win this! ${playerSelection} beats ${computerSelection}`);
return "playerWin";
} else {
alert(`You lose this round! ${computerSelection} beats ${playerSelection}`);
return "botWin";
}
}
const computerSelection = computerPlay();
// to loop the game until 5 rounds
function game() {
let playerScore = 0;
let botScore = 0;
let gameWinner = '';
for (let i = 0; i < 5; i++) {
let playerSelection = prompt(`Round ${i+1}: Choose among "Rock, Paper, Scissors"
as your weapon`).toLowerCase();
let roundResult = playRound(playerSelection, computerPlay());
if (roundResult === "playerWin" ) {
playerScore++;
} else if (roundResult === "botWin" ) {
botScore++;
}
}
if (playerScore > botScore) {
gameWinner = 'You win!';
} else if (botScore > playerScore) {
gameWinner = 'You lose, Computer wins!';
} else {
gameWinner = 'Draw';
}
alert(`Player: ${playerScore} | Bot: ${botScore}`);
if (gameWinner === 'Draw') {
alert("There is no match winner, draw!");
} else {
alert(`${gameWinner}`);
}
}
game();
between these codes which is more likely to be fixed? or would it be better to completely throw this code and just start anew?
The problem is in this part of the code:
score();
gameEnd();
if (roundResult === 'playerWin') {
playerScore++;
} else if (roundResult === 'computerWin') {
computerScore++;
}
score() will update the score in the HTML page, but at that moment the scores have not been updated yet. That only happens later in that if ... else if block.
So the solution is to first update the score, and then to call score():
score();
gameEnd();
if (roundResult === 'playerWin') {
playerScore++;
} else if (roundResult === 'computerWin') {
computerScore++;
}
There is another issue related to this: at the end of the game (when a player reaches 5 points), gameEnd() will call alert. But alert does not allow the page to actually display the latest changes. Instead it blocks any update to it. I would display the game-over message in an HTML element instead of in an alert, just like you already do for the scores. Alternatively, you could delay the execution of alert with a timer, but I would just avoid using alert.
Here is what you can do in the function gameEnd where you currently use alert:
if (playerScore > computerScore) {
results.innerHTML += '<p><b>You win the game</b>';
} else if (computerScore > playerScore) {
results.innerHTML += '<p><b>Aww you lose</b>';
}
I'm having problems getting my simple Rock Paper Scissors game to display the winner of each game when the user chooses anything either than Rock. How do I use multiple if...else statements so that my declareWinner function works when the user chooses Scissors or Paper?
let choices = ["rock", "paper", "scissors"];
// GETTING USER INPUT
const userInput = prompt("Do you choose rock, paper or scissors?").toLocaleLowerCase();
if(userInput ==="paper" || userInput ==="rock" || userInput ==="scissors"){
console.log("You chose " + `${userInput}`);
} else {
console.log("Error! Try again!");
}
// GETTING COMPUTER INPUT
const computerInput = choices[Math.floor(Math.random() * 3)];
console.log("Computer chose" + ` ${computerInput}`);
if (computerInput <= 0.33) {
computerInput = "rock";
}
if (computerInput >= 0.67) {
computerInput = "paper";
}
if (computerInput >= 0.66) {
computerInput = "scissors";
}
// DECLARE WINNER
// User Chooses Rock
function declareWinner(userInput, computerInput) {
if(userInput === "rock" && computerInput === 'paper') {
console.log ('You win! Rock beats paper!');
} else if (userInput === 'rock' && computerInput === 'rock') {
console.log ('Its a tie!');
} else if (userInput === 'rock' && computerInput === 'scissors') {
console.log ('You win! Rock beats scissors!');
// User Chooses Paper
} else if(userInput === "paper" && computerInput === 'rock') {
console.log ('You win! Rock beats paper!');
} else if (userInput === 'paper' && computerInput === 'paper') {
console.log ('Its a tie!');
} else if (userInput === 'paper' && computerInput === 'scissors') {
console.log ('You lose! Scissors beats paper!');
// User Chooses Scissors
} else if(userInput === "scissors" && computerInput === 'rock') {
console.log ('You lose! Rock beats scissors!');
} else if (userInput === 'scissors' && computerInput === 'paper') {
console.log ('You win! Scissors beats paper!');
} else {
console.log ('It is a tie!');
}
}
declareWinner();
There were two problems with the code:-
You are doing choices[Math.floor(Math.random() * 3)]; which results in a random value from choices array, so there is no need for multiple if-else statements that were after it.
You were missing the declareWinner function declaration.
Also, You are missing some conditions in declareWinner function, like userInput === 'paper' && computerInput === 'rock', userInput === 'rock' && computerInput === 'scissors' etc.
const choices = ["rock", "paper", "scissors"];
// GETTING USER INPUT
const userInput = prompt("Do you choose rock, paper or scissors?");
if (userInput === "paper" || userInput === "rock" || userInput === "scissors") {
console.log("You chose " + `${userInput}`);
} else {
console.log("Error! Try again!");
}
// GETTING COMPUTER INPUT
let computerInput = choices[Math.floor(Math.random()*3)];
console.log("Computer chose" + ` ${computerInput}`);
// DECLARE WINNER
const winner = declareWinner(userInput, computerInput);
function declareWinner(userInput, computerInput) {
if (userInput === 'rock' && computerInput === 'paper') {
console.log('You lose! Rock beats Paper');
} else if (userInput === 'scissors' && computerInput === 'paper') {
console.log('You win! Scissors beats Paper');
} else {
console.log('You tie!');
}
}
Tip:- You can use an object to choose the winner in declareWinner function.
const choices = ["rock", "paper", "scissors"];
// GETTING USER INPUT
const userInput = prompt("Do you choose rock, paper or scissors?");
if (userInput === "paper" || userInput === "rock" || userInput === "scissors") {
console.log("You chose " + `${userInput}`);
} else {
console.log("Error! Try again!");
}
// GETTING COMPUTER INPUT
let computerInput = choices[Math.floor(Math.random() * 3)];
console.log("Computer chose" + ` ${computerInput}`);
// DECLARE WINNER
const winner = declareWinner(userInput, computerInput);
function declareWinner(userInput, computerInput) {
let win = {
rock: "scissors",
paper: "rock",
scissors: "paper"
};
if (win[userInput] === computerInput) {
console.log(`You won! ${userInput} beats ${computerInput}`);
} else if (win[computerInput] === userInput) {
console.log(`You lost! ${computerInput} beats ${userInput}`);
} else console.log("Tie")
}
You can't change a const value. Use let instead:
let computerInput = choices[Math.floor(Math.random() * 3)];
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()