I’ve written a function that’s supposed to (1) generate a random number, (2) judge a user’s for that number and (3) keep track of the user’s attempts.
The first two goals are done, but I’m having trouble with (3), keeping track of the user attempts.
function randNum(){
var num = Math.floor(Math.random()*(100)+1);
var usrGuess = document.forms.guess.visitor.value;
var attempt = 0;
if (usrGuess != num){
if ((usrGuess < 1) || (usrGuess > 100))
document.getElementById("wizard").innerHTML = "Fool! This number isn't even part of the set!";
else if (usrGuess > num)
document.getElementById("wizard").innerHTML = "Wrong, fool! This is greater than my number! I was thinking of " + num + "!";
else if (usrGuess < num)
document.getElementById("wizard").innerHTML = "Wrong, fool! This is less than my number! I was thinking of " + num + "!";
attempt += 1; // Here's the change.
alert(attempt); // Here's the output. It doesn't change.
}
else if (usrGuess == num){
if (attempt <= 5)
document.getElementById("wizard").innerHTML = "Right... fool. You only guessed in " + attempt + " tries.";
else if ((attempt <= 10) && (attempt > 5))
document.getElementById("wizard").innerHTML = "Right, fool. You only after " + attempt + " tries.";
else if (attempt > 10 )
document.getElementById("wizard").innerHTML = "Haha, fool! You finally guessed after " + attempt + " tries.<br />Go wallow in your lost time.";
}
}
For some reason, even if I place “attempt” as an outside parameter, the number only tracks up to one attempt.
Anyone have a solution?
You’re declaring “attempt” as a local variable. It’ll be re-initialized every time you call the function.
You’re also making up a new random number on each call to the function, which seems a little mean 🙂
Declare the variables outside the function and see how it goes. (Keep “usrGuess” inside however; just move “num” and “attempt”.)