Profile image of byteJumper39920
Submitted by byteJumper39920
almost 11 years

Full perfect code for this section (please!)

I can see why that as soon as choice1 is not “rock” and computer choice is “scissors” my code will return “Computer with paper wins”, the else option of the first if/if/else block.

What I don’t know is how to fix this.

Obviously we learn more if we don’t just rush to a completed answer, but not having one available is very frustrating when i’m not even sure of how to organise the if/if/else statments, let alone code them.

This is what I have so far (and I explicitly assign choice1 and choice2, can someone also explain why not doing this can still result in workable code, how does the program know which to assign to which or to assign them at all?)

Thanks

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(“User Chose: “ + userChoice); console.log(“Computer Chose: “ + computerChoice);

choice1 = userChoice; choice2 = computerChoice;

var compare = function (choice1, choice2) { if (choice1 === choice2) { return “The result is a tie!”; } {if (choice1 === “rock”) {if (choice2 === “scissors”) return “User with rock wins”; } else if (choice2 === “paper”) return “Computer with paper wins”; } {if (choice1 === “paper”) {if (choice2 === “rock”) return “User with paper wins”; } else if (choice2 === “scissors”) return “Computer with scissors wins”; } {if (choice1 === “scissors”) {if (choice2 === “paper”) return “User with scissors wins”; } else if (choice2 === “rock”) return “Computer with rock wins”; } }; console.log (compare(choice1,choice2));

Answer 52e7fe259c4e9d8513002984

0 votes

Permalink

choice1 = userChoice; choice2 = computerChoice;

You didn’t need this. A function has parameters (placeholders) choice1 and choice2 … your variables go automatic in this placeholders. You do this with the call compare(userChoice, computerChoice); … The power of functions is, that they could used everywhere you need the code inside. Only by calling them.

{if (choice1 === “rock”) … This if decicion opens a block, the brackets in front of the if was to much. e.g.: if ( a < b ) { BLOCK }

else if (choice2 === “paper”) return “Computer with paper wins”; Here you don’t open the “if”-Bock … e.g. else if (a < b) { BLOCK }

Hope i could help.

Profile image of anonymous
Submitted by anonymous
almost 11 years