9. Next Steps


#1



9. Next Steps


I was just wondering if anyone could give me a hint on how i can add some more code so if a user inputs "rope" or "dog" it will tell them that it is an invalid choice. I am pretty new and appreciate any help . My code works when i save it but i just cant figure out where to start to add the other bit of code


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);

function compare(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 ==="paper"){
            return "scissors wins";
        }
        else {
            return "rock wins";
        }
    }
}

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


If user CANCELS out of 'cancellation' of game continue with prompt?
#2

well, given you don't know loops, this is going to be tricky. But we can use function:

var valid = function(){
   var userChoice = prompt("Do you choose rock, paper or scissors?");
   if (userChoice == "rock"){
     return ""rock"
   }
  /* you can code the paper and scissors */
  valid();
}
userChoice = valid();

Okay, what is happening? I created a function called valid, which i then call, and i store the output of the function call in userChoice. The moment the user choices rock, rock is returned (stored in userChoice), and the rest of the program runs

If the user enters something invalid, a return keyword won't be reached (function ends when return keyword are reached, this has been taught in 3. introduction to functions), the function calls itself (yes, this is possible, a function can call itself)

Because the function calls itself, the user will again be prompted to make a valid choice. You still have to code the paper and scissors

A loop would be better, but isn't taught yet


#3

Thanks, the explanation and code helped out greatly.