I think the problem is on the line indicated:
function rock() {
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice < 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
} // <-- I don't think you want this closing brace here
if (computerChoice === "rock") {
alert("Link and Computer both chose Rock! It's a Tie!");
} else if (computerChoice === "scissors") {
alert("Link chose Rock and Computer chose Scissors! Computer took a heart of damage!");
} else {
alert("Link chose Rock and Computer chose Paper! Link took a heart of damage!");
}
}
The closing brace I've indicated brings an end to the rock()
function. As it stands, the rock()
function doesn't actually do anything; it assigns a value "rock"
, "paper"
or "scissors"
at random to a local variable, but the function ends without the variable being used, so the value is lost.
The rest of the code is then run once when the JavaScript is first loaded into the browser. At this point, computerChoice
will be undefined
, and hence you will get a JavaScript error.
If we remove the errant brace, and reformat the code, we get the following:
function rock() {
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if (computerChoice < 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
if (computerChoice === "rock") {
alert("Link and Computer both chose Rock! It's a Tie!");
} else if (computerChoice === "scissors") {
alert("Link chose Rock and Computer chose Scissors! Computer took a heart of damage!");
} else {
alert("Link chose Rock and Computer chose Paper! Link took a heart of damage!");
}
}
I ran this function several times. Each time it alerted one of the three messages at random.