Sergi Sergi - 3 months ago 25
Javascript Question

JS - Rock, Paper, Scissor, buttons instead of Prompt

I have the code for a basic "rock, paper, scissor" game in JS. It works with a promt but I would like to be able to make your choices with buttons. I would like to use "getElementById" and "addEventListener("click")". Could anyone point me in the right direction?

HTML:

<button id ="rock"> Rock </button>


Paper
Scissor

JavaScript:

var userChoice = prompt("Do you choose rock, paper or scissors?");



var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";

} else if(computerChoice <= 0.67) {
computerChoice = "paper";

} else {
computerChoice = "scissors";
} console.log("Computer: " + computerChoice);


var compare = function (choice1, choice2) {
if (choice1 === choice2) {
return "The result is a tie!";
}

else if (choice1 === "rock") {
if (choice2 === "scissors") {
return "rock wins";
}
else {
return "paper wins";


} if (choice1 === "paper") {
if (choice2 === "rock") {
return "paper wins";
}
else {
return "scissors wins";


} if (choice1 === "scissors") {
if (choice2 === "rock") {
return "rock wins";

} else if (choice2 === "paper") {
return "scissors wins";
}
}
}
}
}
compare (userChoice, computerChoice);

Answer

Here is an example (click "run code snippet"):

document.getElementById('rock').onclick = user;
document.getElementById('paper').onclick = user;
document.getElementById('scissors').onclick = user;


function user(){
    var userChoice = this.id;
    console.log("User: " + userChoice)

    var computerChoice = Math.random();
         if (computerChoice < 0.34) {
             computerChoice = "rock";
          }else if(computerChoice <= 0.67) {
             computerChoice = "paper";
          }else{
             computerChoice = "scissors";
          }; 

    console.log("Computer: " + computerChoice);

    console.log(compare(userChoice, computerChoice)); 

    function compare(choice1, choice2) {
    
		    if (choice1 === choice2) {
            return "The result is a tie!";
        }
 
        if (choice1 === "rock") {
            if (choice2 === "scissors") {
                return "rock wins";
            }else{
                return "paper wins";
            }
				}
 
         if (choice1 === "paper") {
             if (choice2 === "rock") {
                 return "paper wins";
              } else {
                  return "scissors wins";
              }
		     }
		
		     if (choice1 === "scissors") {
             if (choice2 === "rock") {
                 return "rock wins";
             } else {
                 return "scissors wins";
            }
        }
    }
}
<button id="rock">Rock</button>
<button id="paper">Paper</button>
<button id="scissors">Scissor</button>

PS: your function compare was returning undefined for some cases.