Code Sharing [JavaScript changes to Rock, paper, scissors ]


#1

I just want to share this code with you, basically it turns the whole game into an executable function, so you can play up to three times:

function game() {
var userChoice = prompt("Rock, paper or scissors?").toLowerCase();
var computerChoice = Math.random();
if (computerChoice >= 0 && computerChoice <= 0.33) {
	computerChoice = "rock";
} else if (computerChoice >= 0.34 && computerChoice <= 0.66) {
	computerChoice = "paper";
} else {
	computerChoice = "scissors";
}
console.log("User: " + userChoice);
console.log("Computer: " + computerChoice);

var compare = function(choice1, choice2) {
    if (choice1 === choice2) {
        alert("Tie! Enter again");
        game();
    } else if (choice1 === "rock") {
        if (choice2 === "scissors") {
            console.log("Rock wins!");  
        } else {
            console.log("Paper wins!");   
        }
    } else if (choice1 === "paper") {
        if (choice2 === "rock") {
            console.log("Paper wins!");    
        } else {
            console.log("Scissors wins!");    
        }
    } else if (choice1 === "scissors") {
        if (choice2 === "rock") {
            console.log("Rock wins!");    
        } else {
            console.log("Scissors wins!");   
        }
    } else {
        console.log("Invalid input");    
    }
}
compare(userChoice, computerChoice);
}
game();
var again = prompt("Play one more time?").toLowerCase();
if (again === "yes") {
    game();
    again = prompt("Maybe again?").toLowerCase();
    if (again === "yes") {
        game();    
    } else if (again === "no") {
      alert("Ok, thanks for playing");
    } else {
      alert("Invalid input");
    }
} else if (again === "no") {
    alert("Thanks for playing!");    
} else {
    alert("Invalid input");    
}

#2

Thank you for sharing this! I found it helpful. Is there a difference between using the && in the computerChoice if/else statements versus just using < ?

Here was my code which worked, but I don't know if it would have been worth it to take the extra step to lay out the parameters like you did:

if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);


#3

What if `computerChoices is 0.331? Or, 0.33999999? Or any number in between?

Answer: It stays a number and doesn't not get changed to a string.

What happens if the user clicks Cancel or presses the Esc key?

Answer: TypeError: null has no property 'toLowerCase'.

One could go on with a broader explanation; however, this is covered in depth in many topics already, so I won't repeat it here.