Inappropriate choice -- expansion of the game


#1

Error message: undefined
(this is what I get if I don’t write "rock", "scissors", or "paper" in the prompt window)

I want the code to return an "Error" if none of the three options are written.. E.g. If I wrote "dog" in the prompt, I’d get an error (look at the last "else if"). How do I achieve that?


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";
    } 
    }
    else if (choice1 === "paper") {
        if (choice2 === "rock") {
            return "paper wins";
        }
        else {
            return "scissors wins";
        }  
    }
    else if (choice1 ==="scissors") {
        if (choice2 ==="rock") {
            return "rock wins";
        }
        else {
            return "scissors wins";
        }
    }
    else if ((choice1 ^ choice2) !== ("rock" ^ "paper" ^ "scissors")) {
        return "Error";
    }
};
console.log(compare(userChoice,computerChoice));


#2

here:

else if ((choice1 ^ choice2) !== ("rock" ^ "paper" ^ "scissors"))

^ is a bitwise operator, are you sure that is wise to use here?

if you simply want to return Error why not simply add else?

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

you covered all choice1 cases, and choice2 can't be faulty (you code it, its not user input), so you can simply add else to return an error


#3

oh yeah... that works too :slight_smile:

Thanks for the fast reply!
I also tried replacing ^ with || and it worked.


#4

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.