JSFiddle - React, Tailwind, and code Playground
by tchalvakspam
JavaScript
// Global function that returns the win matrix
function matrix(){
return {scissors:'paper',paper:'rock',rock:'scissors'};
}
function compare(choice1, choice2){
var mat = matrix();
if(choice1===choice2){
return 'The result is a tie!';
} else if (mat[choice1] === choice2){
return choice1+' wins!';
} else {
return choice1+' loses!';
}
}
var mat = matrix(); // Returns an object.
do{
var userChoice = prompt("Do you choose rock, paper or scissors?");
if(userChoice){ // Non-blank.
userChoice = userChoice.toLowerCase();
}
} while (!userChoice || (typeof mat[userChoice] === 'undefined'));
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
console.log('you chose '+userChoice);
console.log('enemy chose '+computerChoice);
compare(userChoice, computerChoice);